[cfe-commits] [PATCH] Use ExprResult& instead of Expr *& in Sema

John Wiegley johnw at boostpro.com
Fri Mar 4 13:41:19 PST 2011


This patch authored by Eric Niebler.

Many methods on the Sema class (e.g. ConvertPropertyForRValue) take Expr
pointers as in/out parameters (Expr *&).  This is especially true for the
routines that apply implicit conversions to nodes in-place.  This design is
workable only as long as those conversions cannot fail.  If they are allowed
to fail, they need a way to report their failures.  The typical way of doing
this in clang is to use an ExprResult, which has an extra bit to signal a
valid/invalid state.  Returning ExprResult is de riguour elsewhere in the Sema
interface.  We suggest changing the Expr *& parameters in the Sema interface
to ExprResult &.  This increases interface consistency and maintainability.

This interface change is important for work supporting MS-style C++
properties.  For reasons explained here
<http://lists.cs.uiuc.edu/pipermail/cfe-dev/2011-February/013180.html>,
seemingly trivial operations like rvalue/lvalue conversions that formerly
could not fail now can.  (The reason is that given the semantics of the
feature, getter/setter method lookup cannot happen until the point of use, at
which point it may be found that the method does not exist, or it may have the
wrong type, or overload resolution may fail, or it may be inaccessible.)

Performance impact:
---
 include/clang/Sema/Initialization.h |    2 +
 include/clang/Sema/Sema.h           |  108 +++--
 lib/Sema/SemaCXXCast.cpp            |  210 +++++---
 lib/Sema/SemaChecking.cpp           |   35 +-
 lib/Sema/SemaCodeComplete.cpp       |    9 +-
 lib/Sema/SemaExpr.cpp               | 1027 ++++++++++++++++++++---------------
 lib/Sema/SemaExprCXX.cpp            |  336 +++++++-----
 lib/Sema/SemaExprObjC.cpp           |   62 ++-
 lib/Sema/SemaInit.cpp               |  151 +++---
 lib/Sema/SemaOverload.cpp           |  267 ++++++----
 lib/Sema/SemaStmt.cpp               |   52 ++-
 lib/Sema/SemaTemplate.cpp           |  110 ++--
 lib/Sema/SemaType.cpp               |   10 +-
 lib/Sema/TreeTransform.h            |   53 +-
 14 files changed, 1414 insertions(+), 1018 deletions(-)

diff --git a/include/clang/Sema/Initialization.h b/include/clang/Sema/Initialization.h
index 7ccd272..a7caf00 100644
--- a/include/clang/Sema/Initialization.h
+++ b/include/clang/Sema/Initialization.h
@@ -597,6 +597,8 @@ public:
     FK_ReferenceInitFailed,
     /// \brief Implicit conversion failed.
     FK_ConversionFailed,
+    /// \brief Implicit conversion failed.
+    FK_ConversionFromPropertyFailed,
     /// \brief Too many initializers for scalar
     FK_TooManyInitsForScalar,
     /// \brief Reference initialization from an initializer list
diff --git a/include/clang/Sema/Sema.h b/include/clang/Sema/Sema.h
index 26b3d96..6c1344b 100644
--- a/include/clang/Sema/Sema.h
+++ b/include/clang/Sema/Sema.h
@@ -1153,13 +1153,13 @@ public:
   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
                                        SourceLocation EqualLoc,
                                        ExprResult Init);
-  bool PerformObjectArgumentInitialization(Expr *&From,
+  bool PerformObjectArgumentInitialization(ExprResult &From,
                                            NestedNameSpecifier *Qualifier,
                                            NamedDecl *FoundDecl,
                                            CXXMethodDecl *Method);
 
-  bool PerformContextuallyConvertToBool(Expr *&From);
-  bool PerformContextuallyConvertToObjCId(Expr *&From);
+  bool PerformContextuallyConvertToBool(ExprResult &From);
+  bool PerformContextuallyConvertToObjCId(ExprResult &From);
 
   ExprResult 
   ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
@@ -1171,7 +1171,7 @@ public:
                                      const PartialDiagnostic &AmbigNote,
                                      const PartialDiagnostic &ConvDiag);
   
-  bool PerformObjectMemberConversion(Expr *&From,
+  bool PerformObjectMemberConversion(ExprResult &From,
                                      NestedNameSpecifier *Qualifier,
                                      NamedDecl *FoundDecl,
                                      NamedDecl *Member);
@@ -2024,7 +2024,7 @@ public:
                                  const TemplateArgumentListInfo *TemplateArgs,
                                       bool SuppressQualifierCheck = false);
 
-  ExprResult LookupMemberExpr(LookupResult &R, Expr *&Base,
+  ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
                               bool &IsArrow, SourceLocation OpLoc,
                               CXXScopeSpec &SS,
                               Decl *ObjCImpDecl,
@@ -2448,7 +2448,7 @@ public:
 
   //// ActOnCXXThrow -  Parse throw expressions.
   ExprResult ActOnCXXThrow(SourceLocation OpLoc, Expr *expr);
-  bool CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E);
+  bool CheckCXXThrowOperand(SourceLocation ThrowLoc, ExprResult &E);
 
   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
   /// Can be interpreted either as function-style casting ("int(x)")
@@ -3357,7 +3357,7 @@ public:
   bool CheckTemplateArgumentPointerToMember(Expr *Arg,
                                             TemplateArgument &Converted);
   bool CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
-                             QualType InstantiatedParamType, Expr *&Arg,
+                             QualType InstantiatedParamType, ExprResult &Arg,
                              TemplateArgument &Converted,
                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
@@ -4714,34 +4714,42 @@ public:
                          ExprValueKind VK = VK_RValue,
                          const CXXCastPath *BasePath = 0);
 
+  void ImpCastExprToType(ExprResult &ExprRes, QualType Type, CastKind CK,
+                         ExprValueKind VK = VK_RValue,
+                         const CXXCastPath *BasePath = 0) {
+    Expr *E = ExprRes.take();
+    ImpCastExprToType(E, Type, CK, VK, BasePath);
+    ExprRes = Owned(E);
+  }
+
   /// IgnoredValueConversions - Given that an expression's result is
   /// syntactically ignored, perform any conversions that are
   /// required.
-  void IgnoredValueConversions(Expr *&expr);
+  void IgnoredValueConversions(ExprResult &expr);
 
   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
   // functions and arrays to their respective pointers (C99 6.3.2.1).
-  Expr *UsualUnaryConversions(Expr *&expr);
+  void UsualUnaryConversions(ExprResult &expr);
 
   // DefaultFunctionArrayConversion - converts functions and arrays
   // to their respective pointers (C99 6.3.2.1).
-  void DefaultFunctionArrayConversion(Expr *&expr);
+  void DefaultFunctionArrayConversion(ExprResult &expr);
 
   // DefaultFunctionArrayLvalueConversion - converts functions and
   // arrays to their respective pointers and performs the
   // lvalue-to-rvalue conversion.
-  void DefaultFunctionArrayLvalueConversion(Expr *&expr);
+  void DefaultFunctionArrayLvalueConversion(ExprResult &expr);
 
   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
   // the operand.  This is DefaultFunctionArrayLvalueConversion,
   // except that it assumes the operand isn't of function or array
   // type.
-  void DefaultLvalueConversion(Expr *&expr);
+  void DefaultLvalueConversion(ExprResult &expr);
 
   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
   // do not have a prototype. Integer promotions are performed on each
   // argument, and arguments that have type float are promoted to double.
-  void DefaultArgumentPromotion(Expr *&Expr);
+  void DefaultArgumentPromotion(ExprResult &Expr);
 
   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
   enum VariadicCallType {
@@ -4764,7 +4772,7 @@ public:
 
   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
   // will warn if the resulting type is not a POD type.
-  bool DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
+  bool DefaultVariadicArgumentPromotion(ExprResult &ExprRes, VariadicCallType CT,
                                         FunctionDecl *FDecl);
 
   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
@@ -4772,7 +4780,7 @@ public:
   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
   // routine returns the first non-arithmetic type found. The client is
   // responsible for emitting appropriate error diagnostics.
-  QualType UsualArithmeticConversions(Expr *&lExpr, Expr *&rExpr,
+  QualType UsualArithmeticConversions(ExprResult &lExpr, ExprResult &rExpr,
                                       bool isCompAssign = false);
 
   /// AssignConvertType - All of the 'assignment' semantic checks return this
@@ -4860,36 +4868,36 @@ public:
 
   /// Check assignment constraints and prepare for a conversion of the
   /// RHS to the LHS type.
-  AssignConvertType CheckAssignmentConstraints(QualType lhs, Expr *&rhs,
+  AssignConvertType CheckAssignmentConstraints(QualType lhs, ExprResult &rhs,
                                                CastKind &Kind);
 
   // CheckSingleAssignmentConstraints - Currently used by
   // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
   // this routine performs the default function/array converions.
   AssignConvertType CheckSingleAssignmentConstraints(QualType lhs,
-                                                     Expr *&rExpr);
+                                                     ExprResult &rExprRes);
 
   // \brief If the lhs type is a transparent union, check whether we
   // can initialize the transparent union with the given expression.
   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType lhs,
-                                                             Expr *&rExpr);
+                                                             ExprResult &rExpr);
 
   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
 
   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
 
-  bool PerformImplicitConversion(Expr *&From, QualType ToType,
+  bool PerformImplicitConversion(ExprResult &From, QualType ToType,
                                  AssignmentAction Action,
                                  bool AllowExplicit = false);
-  bool PerformImplicitConversion(Expr *&From, QualType ToType,
+  bool PerformImplicitConversion(ExprResult &From, QualType ToType,
                                  AssignmentAction Action,
                                  bool AllowExplicit,
                                  ImplicitConversionSequence& ICS);
-  bool PerformImplicitConversion(Expr *&From, QualType ToType,
+  bool PerformImplicitConversion(ExprResult &From, QualType ToType,
                                  const ImplicitConversionSequence& ICS,
                                  AssignmentAction Action,
                                  bool CStyle = false);
-  bool PerformImplicitConversion(Expr *&From, QualType ToType,
+  bool PerformImplicitConversion(ExprResult &From, QualType ToType,
                                  const StandardConversionSequence& SCS,
                                  AssignmentAction Action,
                                  bool CStyle);
@@ -4898,56 +4906,64 @@ public:
   /// or a null QualType (indicating an error diagnostic was issued).
 
   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
-  QualType InvalidOperands(SourceLocation l, Expr *&lex, Expr *&rex);
+  QualType InvalidOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
   QualType CheckPointerToMemberOperands( // C++ 5.5
-    Expr *&lex, Expr *&rex, ExprValueKind &VK,
+    ExprResult &lex, ExprResult &rex, ExprValueKind &VK,
     SourceLocation OpLoc, bool isIndirect);
   QualType CheckMultiplyDivideOperands( // C99 6.5.5
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign,
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign,
                                        bool isDivide);
   QualType CheckRemainderOperands( // C99 6.5.5
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
   QualType CheckAdditionOperands( // C99 6.5.6
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
   QualType CheckSubtractionOperands( // C99 6.5.6
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0);
   QualType CheckShiftOperands( // C99 6.5.7
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc,
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
     bool isCompAssign = false);
   QualType CheckCompareOperands( // C99 6.5.8/9
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc,
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc,
                                 bool isRelational);
   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false);
   QualType CheckLogicalOperands( // C99 6.5.[13,14]
-    Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc);
+    ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc);
   // CheckAssignmentOperands is used for both simple and compound assignment.
   // For simple assignment, pass both expressions and a null converted type.
   // For compound assignment, pass both expressions and the converted type.
   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
-    Expr *lex, Expr *&rex, SourceLocation OpLoc, QualType convertedType);
-  
-  void ConvertPropertyForRValue(Expr *&E);
-  void ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType& LHSTy);
+    Expr *lex, ExprResult &rex, SourceLocation OpLoc, QualType convertedType);
+
+  void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType& LHSTy);
+  void ConvertPropertyForRValue(ExprResult &E);
                                    
   QualType CheckConditionalOperands( // C99 6.5.15
-    Expr *&cond, Expr *&lhs, Expr *&rhs,
+    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
   QualType CXXCheckConditionalOperands( // C++ 5.16
-    Expr *&cond, Expr *&lhs, Expr *&rhs,
+    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
                                     bool *NonStandardCompositeType = 0);
+  QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2,
+                                    bool *NonStandardCompositeType = 0) {
+    Expr *E1Tmp = E1.take(), *E2Tmp = E2.take();
+    QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType);
+    E1 = Owned(E1Tmp);
+    E2 = Owned(E2Tmp);
+    return Composite;
+  }
 
-  QualType FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
+  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
                                         SourceLocation questionLoc);
 
   bool DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
                                   SourceLocation QuestionLoc);
 
   /// type checking for vector binary operators.
-  QualType CheckVectorOperands(SourceLocation l, Expr *&lex, Expr *&rex);
-  QualType CheckVectorCompareOperands(Expr *&lex, Expr *&rx,
+  QualType CheckVectorOperands(SourceLocation l, ExprResult &lex, ExprResult &rex);
+  QualType CheckVectorCompareOperands(ExprResult &lex, ExprResult &rx,
                                       SourceLocation l, bool isRel);
 
   /// type checking declaration initializers (C99 6.7.8)
@@ -4985,7 +5001,7 @@ public:
 
   /// CheckCastTypes - Check type constraints for casting between types under
   /// C semantics, or forward to CXXCheckCStyleCast in C++.
-  bool CheckCastTypes(SourceRange TyRange, QualType CastTy, Expr *&CastExpr,
+  bool CheckCastTypes(SourceRange TyRange, QualType CastTy, ExprResult &CastExpr,
                       CastKind &Kind, ExprValueKind &VK, CXXCastPath &BasePath,
                       bool FunctionalStyle = false);
 
@@ -5001,13 +5017,13 @@ public:
   // We allow casting between vectors and integer datatypes of the same size,
   // or vectors and the element type of that vector.
   // returns true if the cast is invalid
-  bool CheckExtVectorCast(SourceRange R, QualType VectorTy, Expr *&CastExpr,
+  bool CheckExtVectorCast(SourceRange R, QualType VectorTy, ExprResult &CastExpr,
                           CastKind &Kind);
 
   /// CXXCheckCStyleCast - Check constraints of a C-style or function-style
   /// cast under C++ semantics.
   bool CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
-                          Expr *&CastExpr, CastKind &Kind,
+                          ExprResult &CastExpr, CastKind &Kind,
                           CXXCastPath &BasePath, bool FunctionalStyle);
 
   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
@@ -5027,7 +5043,7 @@ public:
   /// \param Loc - A location associated with the condition, e.g. the
   /// 'if' keyword.
   /// \return true iff there were any errors
-  bool CheckBooleanCondition(Expr *&CondExpr, SourceLocation Loc);
+  bool CheckBooleanCondition(ExprResult &CondExpr, SourceLocation Loc);
 
   ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
                                            Expr *SubExpr);
@@ -5041,7 +5057,7 @@ public:
   void DiagnoseEqualityWithExtraParens(ParenExpr *parenE);
 
   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
-  bool CheckCXXBooleanCondition(Expr *&CondExpr);
+  bool CheckCXXBooleanCondition(ExprResult &CondExpr);
 
   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
   /// the specified width and sign.  If an overflow occurs, detect it and emit
diff --git a/lib/Sema/SemaCXXCast.cpp b/lib/Sema/SemaCXXCast.cpp
index 5b28bc3..e7baaea 100644
--- a/lib/Sema/SemaCXXCast.cpp
+++ b/lib/Sema/SemaCXXCast.cpp
@@ -42,21 +42,21 @@ enum CastType {
 
 
 
-static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+static void CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                            ExprValueKind &VK,
                            const SourceRange &OpRange,
                            const SourceRange &DestRange);
-static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+static void CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                                  ExprValueKind &VK,
                                  const SourceRange &OpRange,
                                  const SourceRange &DestRange,
                                  CastKind &Kind);
-static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+static void CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                             ExprValueKind &VK,
                             const SourceRange &OpRange,
                             CastKind &Kind,
                             CXXCastPath &BasePath);
-static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+static void CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                              ExprValueKind &VK,
                              const SourceRange &OpRange,
                              const SourceRange &DestRange,
@@ -100,7 +100,7 @@ static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
                                        QualType OrigDestType, unsigned &msg,
                                        CastKind &Kind,
                                        CXXCastPath &BasePath);
-static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
+static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
                                                QualType SrcType,
                                                QualType DestType,bool CStyle,
                                                const SourceRange &OpRange,
@@ -108,12 +108,12 @@ static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
                                                CastKind &Kind,
                                                CXXCastPath &BasePath);
 
-static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
+static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
                                            QualType DestType, bool CStyle,
                                            const SourceRange &OpRange,
                                            unsigned &msg,
                                            CastKind &Kind);
-static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
+static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
                                    QualType DestType, bool CStyle,
                                    const SourceRange &OpRange,
                                    unsigned &msg,
@@ -121,7 +121,7 @@ static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
                                    CXXCastPath &BasePath);
 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
                                   bool CStyle, unsigned &msg);
-static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
+static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
                                         QualType DestType, bool CStyle,
                                         const SourceRange &OpRange,
                                         unsigned &msg,
@@ -159,8 +159,9 @@ Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
 
 ExprResult
 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
-                        TypeSourceInfo *DestTInfo, Expr *Ex,
+                        TypeSourceInfo *DestTInfo, Expr *E,
                         SourceRange AngleBrackets, SourceRange Parens) {
+  ExprResult Ex = Owned(E);
   QualType DestType = DestTInfo->getType();
 
   SourceRange OpRange(OpLoc, Parens.getEnd());
@@ -168,11 +169,11 @@ Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
 
   // If the type is dependent, we won't do the semantic analysis now.
   // FIXME: should we check this in a more fine-grained manner?
-  bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
+  bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
 
-  if (Ex->isBoundMemberFunction(Context))
-    Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
-      << Ex->getSourceRange();
+  if (Ex.get()->isBoundMemberFunction(Context))
+    Diag(Ex.get()->getLocStart(), diag::err_invalid_use_of_bound_member_func)
+      << Ex.get()->getSourceRange();
 
   ExprValueKind VK = VK_RValue;
   if (TypeDependent)
@@ -182,42 +183,54 @@ Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
   default: llvm_unreachable("Unknown C++ cast!");
 
   case tok::kw_const_cast:
-    if (!TypeDependent)
+    if (!TypeDependent) {
       CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
+      if (Ex.isInvalid())
+        return ExprError();
+    }
     return Owned(CXXConstCastExpr::Create(Context,
                                         DestType.getNonLValueExprType(Context),
-                                          VK, Ex, DestTInfo, OpLoc,
+                                          VK, Ex.take(), DestTInfo, OpLoc,
                                           Parens.getEnd()));
 
   case tok::kw_dynamic_cast: {
     CastKind Kind = CK_Dependent;
     CXXCastPath BasePath;
-    if (!TypeDependent)
+    if (!TypeDependent) {
       CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
                        Kind, BasePath);
+      if (Ex.isInvalid())
+        return ExprError();
+    }
     return Owned(CXXDynamicCastExpr::Create(Context,
                                           DestType.getNonLValueExprType(Context),
-                                            VK, Kind, Ex, &BasePath, DestTInfo,
+                                            VK, Kind, Ex.take(), &BasePath, DestTInfo,
                                             OpLoc, Parens.getEnd()));
   }
   case tok::kw_reinterpret_cast: {
     CastKind Kind = CK_Dependent;
-    if (!TypeDependent)
+    if (!TypeDependent) {
       CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
+      if (Ex.isInvalid())
+        return ExprError();
+    }
     return Owned(CXXReinterpretCastExpr::Create(Context,
                                   DestType.getNonLValueExprType(Context),
-                                  VK, Kind, Ex, 0,
+                                  VK, Kind, Ex.take(), 0,
                                   DestTInfo, OpLoc, Parens.getEnd()));
   }
   case tok::kw_static_cast: {
     CastKind Kind = CK_Dependent;
     CXXCastPath BasePath;
-    if (!TypeDependent)
+    if (!TypeDependent) {
       CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
+      if (Ex.isInvalid())
+        return ExprError();
+    }
     
     return Owned(CXXStaticCastExpr::Create(Context,
                                          DestType.getNonLValueExprType(Context),
-                                           VK, Kind, Ex, &BasePath,
+                                           VK, Kind, Ex.take(), &BasePath,
                                            DestTInfo, OpLoc, Parens.getEnd()));
   }
   }
@@ -424,11 +437,11 @@ CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
 /// checked downcasts in class hierarchies.
 static void
-CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                  ExprValueKind &VK, const SourceRange &OpRange,
                  const SourceRange &DestRange, CastKind &Kind,
                  CXXCastPath &BasePath) {
-  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
+  QualType OrigDestType = DestType, OrigSrcType = SrcExpr.get()->getType();
   DestType = Self.Context.getCanonicalType(DestType);
 
   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
@@ -475,11 +488,11 @@ CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
       SrcPointee = SrcPointer->getPointeeType();
     } else {
       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
-        << OrigSrcType << SrcExpr->getSourceRange();
+        << OrigSrcType << SrcExpr.get()->getSourceRange();
       return;
     }
   } else if (DestReference->isLValueReferenceType()) {
-    if (!SrcExpr->isLValue()) {
+    if (!SrcExpr.get()->isLValue()) {
       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
         << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
     }
@@ -492,11 +505,11 @@ CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
   if (SrcRecord) {
     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
                              Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
-                                   << SrcExpr->getSourceRange()))
+                                   << SrcExpr.get()->getSourceRange()))
       return;
   } else {
     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
-      << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
+      << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
     return;
   }
 
@@ -543,7 +556,7 @@ CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
   assert(SrcDecl && "Definition missing");
   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
-      << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
+      << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
   }
   Self.MarkVTableUsed(OpRange.getBegin(), 
                       cast<CXXRecordDecl>(SrcRecord->getDecl()));
@@ -558,17 +571,20 @@ CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
 /// const char *str = "literal";
 /// legacy_function(const_cast\<char*\>(str));
 void
-CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
+CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, ExprValueKind &VK,
                const SourceRange &OpRange, const SourceRange &DestRange) {
   VK = Expr::getValueKindForType(DestType);
-  if (VK == VK_RValue)
+  if (VK == VK_RValue) {
     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
+    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
+      return;
+  }
 
   unsigned msg = diag::err_bad_cxx_cast_generic;
-  if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
+  if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
       && msg != 0)
     Self.Diag(OpRange.getBegin(), msg) << CT_Const
-      << SrcExpr->getType() << DestType << OpRange;
+      << SrcExpr.get()->getType() << DestType << OpRange;
 }
 
 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
@@ -577,27 +593,32 @@ CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
 /// like this:
 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
 void
-CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                      ExprValueKind &VK, const SourceRange &OpRange,
                      const SourceRange &DestRange, CastKind &Kind) {
   VK = Expr::getValueKindForType(DestType);
-  if (VK == VK_RValue)
+  if (VK == VK_RValue) {
     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
+    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
+      return;
+  }
 
   unsigned msg = diag::err_bad_cxx_cast_generic;
   if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
                          msg, Kind)
       != TC_Success && msg != 0)
   {
-    if (SrcExpr->getType() == Self.Context.OverloadTy) {
+    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
+      return;
+    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
       //FIXME: &f<int>; is overloaded and resolvable 
       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 
-        << OverloadExpr::find(SrcExpr).Expression->getName()
+        << OverloadExpr::find(SrcExpr.get()).Expression->getName()
         << DestType << OpRange;
-      Self.NoteAllOverloadCandidates(SrcExpr);
+      Self.NoteAllOverloadCandidates(SrcExpr.get());
 
     } else {
-      diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr, DestType);
+      diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
     }
   }    
 }
@@ -607,7 +628,7 @@ CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
 /// implicit conversions explicit and getting rid of data loss warnings.
 void
-CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                 ExprValueKind &VK, const SourceRange &OpRange,
                 CastKind &Kind, CXXCastPath &BasePath) {
   // This test is outside everything else because it's the only case where
@@ -615,15 +636,17 @@ CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
   if (DestType->isVoidType()) {
     Self.IgnoredValueConversions(SrcExpr);
-    if (SrcExpr->getType() == Self.Context.OverloadTy) {
+    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
+      return;
+    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
       ExprResult SingleFunctionExpression = 
-         ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr, 
+         ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr.get(), 
                 false, // Decay Function to ptr 
                 true, // Complain
                 OpRange, DestType, diag::err_bad_static_cast_overload);
         if (SingleFunctionExpression.isUsable())
         {
-          SrcExpr = SingleFunctionExpression.release();
+          SrcExpr = SingleFunctionExpression;
           Kind = CK_ToVoid;
         }
     }
@@ -633,30 +656,36 @@ CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
   }
 
   VK = Expr::getValueKindForType(DestType);
-  if (VK == VK_RValue && !DestType->isRecordType())
+  if (VK == VK_RValue && !DestType->isRecordType()) {
     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
+    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
+      return;
+  }
 
   unsigned msg = diag::err_bad_cxx_cast_generic;
   if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
                     Kind, BasePath) != TC_Success && msg != 0) {
-    if (SrcExpr->getType() == Self.Context.OverloadTy) {
-      OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
+    if (SrcExpr.isInvalid())
+      return;
+    if (SrcExpr.get()->getType() == Self.Context.OverloadTy)
+    {
+      OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
       Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
         << oe->getName() << DestType << OpRange 
         << oe->getQualifierLoc().getSourceRange();
-      Self.NoteAllOverloadCandidates(SrcExpr);
+      Self.NoteAllOverloadCandidates(SrcExpr.get());
     } else {
-      diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr, DestType);
+      diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
     }
   }
   else if (Kind == CK_BitCast)
-    Self.CheckCastAlign(SrcExpr, DestType, OpRange);
+    Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
 }
 
 /// TryStaticCast - Check if a static cast can be performed, and do so if
 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
 /// and casting away constness.
-static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
+static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
                                    QualType DestType, bool CStyle,
                                    const SourceRange &OpRange, unsigned &msg,
                                    CastKind &Kind,
@@ -681,7 +710,7 @@ static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
   // C++ 5.2.9p5, reference downcast.
   // See the function for details.
   // DR 427 specifies that this is to be applied before paragraph 2.
-  tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
+  tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
                                    msg, Kind, BasePath);
   if (tcr != TC_NotApplicable)
     return tcr;
@@ -689,7 +718,7 @@ static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
   // C++0x [expr.static.cast]p3: 
   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
   //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
-  tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, CStyle, Kind, BasePath, 
+  tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath, 
                               msg);
   if (tcr != TC_NotApplicable)
     return tcr;
@@ -698,6 +727,8 @@ static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
   //   [...] if the declaration "T t(e);" is well-formed, [...].
   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
                               Kind);
+  if (SrcExpr.isInvalid())
+    return TC_Failed;
   if (tcr != TC_NotApplicable)
     return tcr;
   
@@ -709,7 +740,7 @@ static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
   // In the CStyle case, the earlier attempt to const_cast should have taken
   // care of reverse qualification conversions.
 
-  QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
+  QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
 
   // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
   // converted to an integral type. [...] A value of a scoped enumeration type
@@ -1039,7 +1070,7 @@ TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
 ///   where B is a base class of D [...].
 ///
 TryCastResult
-TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType, 
+TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 
                              QualType DestType, bool CStyle, 
                              const SourceRange &OpRange,
                              unsigned &msg, CastKind &Kind,
@@ -1050,9 +1081,9 @@ TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
 
   bool WasOverloadedFunction = false;
   DeclAccessPair FoundOverload;
-  if (SrcExpr->getType() == Self.Context.OverloadTy) {
+  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
     if (FunctionDecl *Fn
-          = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
+          = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
                                                     FoundOverload)) {
       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
       SrcType = Self.Context.getMemberPointerType(Fn->getType(),
@@ -1123,7 +1154,7 @@ TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
   if (WasOverloadedFunction) {
     // Resolve the address of the overloaded function again, this time
     // allowing complaints if something goes wrong.
-    FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr, 
+    FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 
                                                                DestType, 
                                                                true,
                                                                FoundOverload);
@@ -1133,7 +1164,7 @@ TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
     }
 
     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
-    if (!SrcExpr) {
+    if (!SrcExpr.isUsable()) {
       msg = 0;
       return TC_Failed;
     }
@@ -1150,7 +1181,7 @@ TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
 ///   An expression e can be explicitly converted to a type T using a
 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
 TryCastResult
-TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
+TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                       bool CStyle, const SourceRange &OpRange, unsigned &msg,
                       CastKind &Kind) {
   if (DestType->isRecordType()) {
@@ -1164,7 +1195,8 @@ TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
   InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
   InitializationKind InitKind
     = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);    
-  InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
+  Expr *SrcExprRaw = SrcExpr.get();
+  InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
 
   // At this point of CheckStaticCast, if the destination is a reference,
   // or the expression is an overload expression this has to work. 
@@ -1177,7 +1209,7 @@ TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
     return TC_NotApplicable;
     
   ExprResult Result
-    = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
+    = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
   if (Result.isInvalid()) {
     msg = 0;
     return TC_Failed;
@@ -1188,7 +1220,7 @@ TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
   else
     Kind = CK_NoOp;
   
-  SrcExpr = Result.takeAs<Expr>();
+  SrcExpr = Result;
   return TC_Success;
 }
 
@@ -1282,8 +1314,11 @@ static ExprResult ResolveAndFixSingleFunctionTemplateSpecialization(
       SingleFunctionExpression = Self.FixOverloadedFunctionReference(SrcExpr, 
                                                                     Found, Fn);
       
-      if (DoFunctionPointerConverion)
-        Self.DefaultFunctionArrayLvalueConversion(SingleFunctionExpression);
+      if (DoFunctionPointerConverion) {
+        ExprResult SingleFunRes = Self.Owned(SingleFunctionExpression);
+        Self.DefaultFunctionArrayLvalueConversion(SingleFunRes);
+        SingleFunctionExpression = SingleFunRes.take(); // NULL if SingleFunRes.isInvalid()
+      }
     }      
   }
   if (!SingleFunctionExpression && Complain) {
@@ -1296,7 +1331,7 @@ static ExprResult ResolveAndFixSingleFunctionTemplateSpecialization(
   return SingleFunctionExpression;
 }
 
-static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
+static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
                                         QualType DestType, bool CStyle,
                                         const SourceRange &OpRange,
                                         unsigned &msg,
@@ -1304,19 +1339,19 @@ static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
   bool IsLValueCast = false;
   
   DestType = Self.Context.getCanonicalType(DestType);
-  QualType SrcType = SrcExpr->getType();
+  QualType SrcType = SrcExpr.get()->getType();
 
   // Is the source an overloaded name? (i.e. &foo)
   // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
   if (SrcType == Self.Context.OverloadTy) {
     // ... unless foo<int> resolves to an lvalue unambiguously
     ExprResult SingleFunctionExpr = 
-        ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr, 
+        ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr.take(), 
           Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 
         );
     if (SingleFunctionExpr.isUsable()) {
-      SrcExpr = SingleFunctionExpr.release();
-      SrcType = SrcExpr->getType();
+      SrcExpr = SingleFunctionExpr;
+      SrcType = SrcExpr.get()->getType();
     }      
     else  
       return TC_NotApplicable;
@@ -1324,7 +1359,7 @@ static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
 
   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
     bool LValue = DestTypeTmp->isLValueReferenceType();
-    if (LValue && !SrcExpr->isLValue()) {
+    if (LValue && !SrcExpr.get()->isLValue()) {
       // Cannot cast non-lvalue to lvalue reference type. See the similar 
       // comment in const_cast.
       msg = diag::err_bad_cxx_cast_rvalue;
@@ -1528,29 +1563,31 @@ static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
 
 bool 
 Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
-                         Expr *&CastExpr, CastKind &Kind, 
+                         ExprResult &CastExpr, CastKind &Kind, 
                          CXXCastPath &BasePath,
                          bool FunctionalStyle) {
-  if (CastExpr->isBoundMemberFunction(Context))
-    return Diag(CastExpr->getLocStart(),
+  if (CastExpr.get()->isBoundMemberFunction(Context))
+    return Diag(CastExpr.get()->getLocStart(),
                 diag::err_invalid_use_of_bound_member_func)
-        << CastExpr->getSourceRange();
+        << CastExpr.get()->getSourceRange();
 
   // This test is outside everything else because it's the only case where
   // a non-lvalue-reference target type does not lead to decay.
   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
   if (CastTy->isVoidType()) {
     IgnoredValueConversions(CastExpr);    
+    if (CastExpr.isInvalid())
+      return true;
     bool ret = false; // false is 'able to convert'
-    if (CastExpr->getType() == Context.OverloadTy) {
+    if (CastExpr.get()->getType() == Context.OverloadTy) {
       ExprResult SingleFunctionExpr = 
         ResolveAndFixSingleFunctionTemplateSpecialization(*this, 
-              CastExpr, 
+              CastExpr.take(), 
               /* Decay Function to ptr */ false, 
               /* Complain */ true, 
               R, CastTy, diag::err_bad_cstyle_cast_overload);
       if (SingleFunctionExpr.isUsable()) {
-        CastExpr = SingleFunctionExpr.release();
+        CastExpr = SingleFunctionExpr;
         Kind = CK_ToVoid;
       }
       else
@@ -1566,13 +1603,16 @@ Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
   VK = Expr::getValueKindForType(CastTy);
 
   // If the type is dependent, we won't do any other semantic analysis now.
-  if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
+  if (CastTy->isDependentType() || CastExpr.get()->isTypeDependent()) {
     Kind = CK_Dependent;
     return false;
   }
 
-  if (VK == VK_RValue && !CastTy->isRecordType())
+  if (VK == VK_RValue && !CastTy->isRecordType()) {
     DefaultFunctionArrayLvalueConversion(CastExpr);
+    if (CastExpr.isInvalid())
+      return true;
+  }
 
   // C++ [expr.cast]p5: The conversions performed by
   //   - a const_cast,
@@ -1586,7 +1626,7 @@ Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
   //   even if a cast resulting from that interpretation is ill-formed.
   // In plain language, this means trying a const_cast ...
   unsigned msg = diag::err_bad_cxx_cast_generic;
-  TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
+  TryCastResult tcr = TryConstCast(*this, CastExpr.get(), CastTy, /*CStyle*/true,
                                    msg);
   if (tcr == TC_Success)
     Kind = CK_NoOp;
@@ -1595,17 +1635,21 @@ Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
     // ... or if that is not possible, a static_cast, ignoring const, ...
     tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
                         BasePath);
+    if (CastExpr.isInvalid())
+      return true;
     if (tcr == TC_NotApplicable) {
       // ... and finally a reinterpret_cast, ignoring const.
       tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
                                Kind);
+      if (CastExpr.isInvalid())
+        return true;
     }
   }
 
   if (tcr != TC_Success && msg != 0) {
-    if (CastExpr->getType() == Context.OverloadTy) {
+    if (CastExpr.get()->getType() == Context.OverloadTy) {
       DeclAccessPair Found;
-      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr, 
+      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr.get(), 
                                 CastTy,
                                 /* Complain */ true,
                                 Found);
@@ -1616,11 +1660,11 @@ Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
 
     } else {
       diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
-                      R, CastExpr, CastTy);
+                      R, CastExpr.get(), CastTy);
     }
   }
   else if (Kind == CK_BitCast)
-    CheckCastAlign(CastExpr, CastTy, R);
+    CheckCastAlign(CastExpr.get(), CastTy, R);
 
   return tcr != TC_Success;
 }
diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp
index cdcab31..94fc767 100644
--- a/lib/Sema/SemaChecking.cpp
+++ b/lib/Sema/SemaChecking.cpp
@@ -491,14 +491,14 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
   // deduce the types of the rest of the arguments accordingly.  Walk
   // the remaining arguments, converting them to the deduced value type.
   for (unsigned i = 0; i != NumFixed; ++i) {
-    Expr *Arg = TheCall->getArg(i+1);
+    ExprResult Arg = TheCall->getArg(i+1);
 
     // If the argument is an implicit cast, then there was a promotion due to
     // "...", just remove it now.
-    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
+    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
       Arg = ICE->getSubExpr();
       ICE->setSubExpr(0);
-      TheCall->setArg(i+1, Arg);
+      TheCall->setArg(i+1, Arg.get());
     }
 
     // GCC does an implicit conversion to the pointer or integer ValType.  This
@@ -506,7 +506,8 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
     CastKind Kind = CK_Invalid;
     ExprValueKind VK = VK_RValue;
     CXXCastPath BasePath;
-    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
+    if (CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg, Kind, VK, BasePath) ||
+        Arg.isInvalid())
       return ExprError();
 
     // Okay, we have something that *can* be converted to the right type.  Check
@@ -516,7 +517,7 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
     // for things like 45.123 -> char, etc.
     // FIXME: Do this check.
     ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
-    TheCall->setArg(i+1, Arg);
+    TheCall->setArg(i+1, Arg.get());
   }
 
   // Switch the DeclRefExpr to refer to the new decl.
@@ -525,9 +526,11 @@ Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
 
   // Set the callee in the CallExpr.
   // FIXME: This leaks the original parens and implicit casts.
-  Expr *PromotedCall = DRE;
+  ExprResult PromotedCall = Owned(DRE);
   UsualUnaryConversions(PromotedCall);
-  TheCall->setCallee(PromotedCall);
+  if (PromotedCall.isInvalid())
+    return ExprError();
+  TheCall->setCallee(PromotedCall.take());
 
   // Change the result type of the call to match the original value type. This
   // is arbitrary, but the codegen for these builtins ins design to handle it
@@ -650,29 +653,31 @@ bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
       << SourceRange(TheCall->getArg(2)->getLocStart(),
                      (*(TheCall->arg_end()-1))->getLocEnd());
 
-  Expr *OrigArg0 = TheCall->getArg(0);
-  Expr *OrigArg1 = TheCall->getArg(1);
+  ExprResult OrigArg0 = TheCall->getArg(0);
+  ExprResult OrigArg1 = TheCall->getArg(1);
 
   // Do standard promotions between the two arguments, returning their common
   // type.
   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
+  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
+    return true;
 
   // Make sure any conversions are pushed back into the call; this is
   // type safe since unordered compare builtins are declared as "_Bool
   // foo(...)".
-  TheCall->setArg(0, OrigArg0);
-  TheCall->setArg(1, OrigArg1);
+  TheCall->setArg(0, OrigArg0.get());
+  TheCall->setArg(1, OrigArg1.get());
 
-  if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
+  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
     return false;
 
   // If the common type isn't a real floating type, then the arguments were
   // invalid for this operation.
   if (!Res->isRealFloatingType())
-    return Diag(OrigArg0->getLocStart(),
+    return Diag(OrigArg0.get()->getLocStart(),
                 diag::err_typecheck_call_invalid_ordered_compare)
-      << OrigArg0->getType() << OrigArg1->getType()
-      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
+      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
+      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
 
   return false;
 }
diff --git a/lib/Sema/SemaCodeComplete.cpp b/lib/Sema/SemaCodeComplete.cpp
index bab665a..18ed0d3 100644
--- a/lib/Sema/SemaCodeComplete.cpp
+++ b/lib/Sema/SemaCodeComplete.cpp
@@ -4816,8 +4816,13 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
   
   // If necessary, apply function/array conversion to the receiver.
   // C99 6.7.5.3p[7,8].
-  if (RecExpr)
-    DefaultFunctionArrayLvalueConversion(RecExpr);
+  if (RecExpr) {
+    ExprResult Conv = Owned(RecExpr);
+    DefaultFunctionArrayLvalueConversion(Conv);
+    if (Conv.isInvalid()) // conversion failed. bail.
+      return;
+    RecExpr = Conv.take();
+  }
   QualType ReceiverType = RecExpr? RecExpr->getType() 
                           : Super? Context.getObjCObjectPointerType(
                                             Context.getObjCInterfaceType(Super))
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index 3da647a..b82e1f7 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -232,8 +232,8 @@ SourceRange Sema::getExprRange(ExprTy *E) const {
 //===----------------------------------------------------------------------===//
 
 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
-void Sema::DefaultFunctionArrayConversion(Expr *&E) {
-  QualType Ty = E->getType();
+void Sema::DefaultFunctionArrayConversion(ExprResult &E) {
+  QualType Ty = E.get()->getType();
   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
 
   if (Ty->isFunctionType())
@@ -251,32 +251,32 @@ void Sema::DefaultFunctionArrayConversion(Expr *&E) {
     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
     // T" can be converted to an rvalue of type "pointer to T".
     //
-    if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
+    if (getLangOptions().C99 || getLangOptions().CPlusPlus || E.get()->isLValue())
       ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
                         CK_ArrayToPointerDecay);
   }
 }
 
-void Sema::DefaultLvalueConversion(Expr *&E) {
+void Sema::DefaultLvalueConversion(ExprResult &E) {
   // C++ [conv.lval]p1:
   //   A glvalue of a non-function, non-array type T can be
   //   converted to a prvalue.
-  if (!E->isGLValue()) return;
+  if (!E.get()->isGLValue()) return;
 
-  QualType T = E->getType();
+  QualType T = E.get()->getType();
   assert(!T.isNull() && "r-value conversion on typeless expression?");
 
   // Create a load out of an ObjCProperty l-value, if necessary.
-  if (E->getObjectKind() == OK_ObjCProperty) {
+  if (E.get()->getObjectKind() == OK_ObjCProperty) {
     ConvertPropertyForRValue(E);
-    if (!E->isGLValue())
+    if (!E.get()->isGLValue())
       return;
   }
 
   // We don't want to throw lvalue-to-rvalue casts on top of
   // expressions of certain types in C++.
   if (getLangOptions().CPlusPlus &&
-      (E->getType() == Context.OverloadTy ||
+      (E.get()->getType() == Context.OverloadTy ||
        T->isDependentType() ||
        T->isRecordType()))
     return;
@@ -301,13 +301,13 @@ void Sema::DefaultLvalueConversion(Expr *&E) {
   if (T.hasQualifiers())
     T = T.getUnqualifiedType();
 
-  CheckArrayAccess(E);
+  CheckArrayAccess(E.get());
   
-  E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
-                               E, 0, VK_RValue);
+  E = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
+                                     E.take(), 0, VK_RValue));
 }
 
-void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
+void Sema::DefaultFunctionArrayLvalueConversion(ExprResult &E) {
   DefaultFunctionArrayConversion(E);
   DefaultLvalueConversion(E);
 }
@@ -318,11 +318,13 @@ void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
 /// sometimes surpressed. For example, the array->pointer conversion doesn't
 /// apply if the array is an argument to the sizeof or address (&) operators.
 /// In these instances, this routine should *not* be called.
-Expr *Sema::UsualUnaryConversions(Expr *&E) {
+void Sema::UsualUnaryConversions(ExprResult &E) {
   // First, convert to an r-value.
   DefaultFunctionArrayLvalueConversion(E);
+  if (E.isInvalid())
+    return;
   
-  QualType Ty = E->getType();
+  QualType Ty = E.get()->getType();
   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
   
   // Try to perform integral promotions if the object has a theoretically
@@ -342,42 +344,44 @@ Expr *Sema::UsualUnaryConversions(Expr *&E) {
     //   unsigned int. These are called the integer promotions. All
     //   other types are unchanged by the integer promotions.
   
-    QualType PTy = Context.isPromotableBitField(E);
+    QualType PTy = Context.isPromotableBitField(E.get());
     if (!PTy.isNull()) {
       ImpCastExprToType(E, PTy, CK_IntegralCast);
-      return E;
+      return;
     }
     if (Ty->isPromotableIntegerType()) {
       QualType PT = Context.getPromotedIntegerType(Ty);
       ImpCastExprToType(E, PT, CK_IntegralCast);
-      return E;
+      return;
     }
   }
-
-  return E;
 }
 
 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
 /// do not have a prototype. Arguments that have type float are promoted to
 /// double. All other argument types are converted by UsualUnaryConversions().
-void Sema::DefaultArgumentPromotion(Expr *&Expr) {
-  QualType Ty = Expr->getType();
+void Sema::DefaultArgumentPromotion(ExprResult &Expr) {
+  QualType Ty = Expr.get()->getType();
   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
 
   UsualUnaryConversions(Expr);
+  if (Expr.isInvalid())
+    return;
 
   // If this is a 'float' (CVR qualified or typedef) promote to double.
   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
-    return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
+    ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
 }
 
 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
 /// will warn if the resulting type is not a POD type, and rejects ObjC
 /// interfaces passed by value.  This returns true if the argument type is
 /// completely illegal.
-bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
+bool Sema::DefaultVariadicArgumentPromotion(ExprResult &ExprRes, VariadicCallType CT,
                                             FunctionDecl *FDecl) {
-  DefaultArgumentPromotion(Expr);
+  DefaultArgumentPromotion(ExprRes);
+  if (ExprRes.isInvalid())
+    return true;
 
   // __builtin_va_start takes the second argument as a "varargs" argument, but
   // it doesn't actually do anything with it.  It doesn't need to be non-pod
@@ -385,16 +389,16 @@ bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
   if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
     return false;
   
-  if (Expr->getType()->isObjCObjectType() &&
-      DiagRuntimeBehavior(Expr->getLocStart(), 0,
+  if (ExprRes.get()->getType()->isObjCObjectType() &&
+      DiagRuntimeBehavior(ExprRes.get()->getLocStart(), 0,
         PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
-          << Expr->getType() << CT))
+          << ExprRes.get()->getType() << CT))
     return true;
 
-  if (!Expr->getType()->isPODType() &&
-      DiagRuntimeBehavior(Expr->getLocStart(), 0,
+  if (!ExprRes.get()->getType()->isPODType() &&
+      DiagRuntimeBehavior(ExprRes.get()->getLocStart(), 0,
                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
-                            << Expr->getType() << CT))
+                            << ExprRes.get()->getType() << CT))
     return true;
 
   return false;
@@ -406,19 +410,24 @@ bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
 /// responsible for emitting appropriate error diagnostics.
 /// FIXME: verify the conversion rules for "complex int" are consistent with
 /// GCC.
-QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
+QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
                                           bool isCompAssign) {
-  if (!isCompAssign)
+  if (!isCompAssign) {
     UsualUnaryConversions(lhsExpr);
+    if (lhsExpr.isInvalid())
+      return QualType();
+  }
 
   UsualUnaryConversions(rhsExpr);
+  if (rhsExpr.isInvalid())
+    return QualType();
 
   // For conversion purposes, we ignore any qualifiers.
   // For example, "const float" and "float" are equivalent.
   QualType lhs =
-    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
+    Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
   QualType rhs =
-    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
+    Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
 
   // If both types are identical, no conversion is needed.
   if (lhs == rhs)
@@ -433,7 +442,7 @@ QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
   QualType lhs_unpromoted = lhs;
   if (lhs->isPromotableIntegerType())
     lhs = Context.getPromotedIntegerType(lhs);
-  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
+  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
   if (!LHSBitfieldPromoteTy.isNull())
     lhs = LHSBitfieldPromoteTy;
   if (lhs != lhs_unpromoted && !isCompAssign)
@@ -1852,13 +1861,14 @@ Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
       if (SelfExpr.isInvalid())
         return ExprError();
 
-      Expr *SelfE = SelfExpr.take();
-      DefaultLvalueConversion(SelfE);
+      DefaultLvalueConversion(SelfExpr);
+      if (SelfExpr.isInvalid())
+        return ExprError();
 
       MarkDeclarationReferenced(Loc, IV);
       return Owned(new (Context)
                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
-                                   SelfE, true, true));
+                                   SelfExpr.take(), true, true));
     }
   } else if (CurMethod->isInstanceMethod()) {
     // We should warn if a local variable hides an ivar.
@@ -1905,7 +1915,7 @@ Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
 ///   declaring class of the member.  This conversion does not
 ///   obey access control.
 bool
-Sema::PerformObjectMemberConversion(Expr *&From,
+Sema::PerformObjectMemberConversion(ExprResult &From,
                                     NestedNameSpecifier *Qualifier,
                                     NamedDecl *FoundDecl,
                                     NamedDecl *Member) {
@@ -1916,7 +1926,7 @@ Sema::PerformObjectMemberConversion(Expr *&From,
   QualType DestRecordType;
   QualType DestType;
   QualType FromRecordType;
-  QualType FromType = From->getType();
+  QualType FromType = From.get()->getType();
   bool PointerConversions = false;
   if (isa<FieldDecl>(Member)) {
     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
@@ -1955,10 +1965,10 @@ Sema::PerformObjectMemberConversion(Expr *&From,
   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
     return false;
 
-  SourceRange FromRange = From->getSourceRange();
+  SourceRange FromRange = From.get()->getSourceRange();
   SourceLocation FromLoc = FromRange.getBegin();
 
-  ExprValueKind VK = CastCategory(From);
+  ExprValueKind VK = CastCategory(From.get());
 
   // C++ [class.member.lookup]p8:
   //   [...] Ambiguities can often be resolved by qualifying a name with its
@@ -2118,10 +2128,12 @@ BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
   }
 
   S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
-  if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
-                                      FoundDecl, Field))
+  ExprResult Base = BaseExpr;
+  if (S.PerformObjectMemberConversion(Base, SS.getScopeRep(),
+                                      FoundDecl, Field) ||
+      Base.isInvalid())
     return ExprError();
-  return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
+  return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
                                  Field, FoundDecl, MemberNameInfo,
                                  MemberType, VK, OK));
 }
@@ -2854,33 +2866,36 @@ Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
   return move(Result);
 }
 
-static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
+static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
                                      bool isReal) {
-  if (V->isTypeDependent())
+  if (V.get()->isTypeDependent())
     return S.Context.DependentTy;
 
   // _Real and _Imag are only l-values for normal l-values.
-  if (V->getObjectKind() != OK_Ordinary)
+  if (V.get()->getObjectKind() != OK_Ordinary) {
     S.DefaultLvalueConversion(V);
+    if (V.isInvalid())
+      return QualType();
+  }
 
   // These operators return the element type of a complex type.
-  if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
+  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
     return CT->getElementType();
 
   // Otherwise they pass through real integer and floating point types here.
-  if (V->getType()->isArithmeticType())
-    return V->getType();
+  if (V.get()->getType()->isArithmeticType())
+    return V.get()->getType();
 
   // Test for placeholders.
-  ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
+  ExprResult PR = S.CheckPlaceholderExpr(V.get(), Loc);
   if (PR.isInvalid()) return QualType();
-  if (PR.take() != V) {
-    V = PR.take();
+  if (PR.get() != V.get()) {
+    V = PR;
     return CheckRealImagOperand(S, V, Loc, isReal);
   }
 
   // Reject anything else.
-  S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
+  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
     << (isReal ? "__real" : "__imag");
   return QualType();
 }
@@ -2950,9 +2965,18 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
   Expr *RHSExp = Idx;
 
   // Perform default conversions.
-  if (!LHSExp->getType()->getAs<VectorType>())
-      DefaultFunctionArrayLvalueConversion(LHSExp);
-  DefaultFunctionArrayLvalueConversion(RHSExp);
+  if (!LHSExp->getType()->getAs<VectorType>()) {
+    ExprResult Result = Owned(LHSExp);
+    DefaultFunctionArrayLvalueConversion(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    LHSExp = Result.take();
+  }
+  ExprResult Result = Owned(RHSExp);
+  DefaultFunctionArrayLvalueConversion(Result);
+  if (Result.isInvalid())
+    return ExprError();
+  RHSExp = Result.take();
 
   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
   ExprValueKind VK = VK_LValue;
@@ -3435,10 +3459,15 @@ Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
 
   // Explicit member accesses.
   } else {
+    ExprResult BaseResult = Owned(Base);
     ExprResult Result =
-      LookupMemberExpr(R, Base, IsArrow, OpLoc,
+      LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
                        SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
 
+    if (BaseResult.isInvalid())
+      return ExprError();
+    Base = BaseResult.take();
+
     if (Result.isInvalid()) {
       Owned(Base);
       return ExprError();
@@ -3562,8 +3591,13 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
 
   // Perform a property load on the base regardless of whether we
   // actually need it for the declaration.
-  if (BaseExpr->getObjectKind() == OK_ObjCProperty)
-    ConvertPropertyForRValue(BaseExpr);
+  if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
+    ExprResult Result = Owned(BaseExpr);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    BaseExpr = Result.take();
+  }
 
   if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
     return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
@@ -3622,9 +3656,9 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
 /// types would be profitable.  The redefinition type is whatever
 /// this translation unit tried to typedef to id/Class;  we store
 /// it to the side and then re-use it in places like this.
-static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
+static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
   const ObjCObjectPointerType *opty
-    = base->getType()->getAs<ObjCObjectPointerType>();
+    = base.get()->getType()->getAs<ObjCObjectPointerType>();
   if (!opty) return false;
 
   const ObjCObjectType *ty = opty->getObjectType();
@@ -3659,17 +3693,22 @@ static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
 /// The ObjCImpDecl bit is a gross hack that will need to be properly
 /// fixed for ObjC++.
 ExprResult
-Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
+Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
                        bool &IsArrow, SourceLocation OpLoc,
                        CXXScopeSpec &SS,
                        Decl *ObjCImpDecl, bool HasTemplateArgs) {
-  assert(BaseExpr && "no base expression");
+  assert(BaseExpr.get() && "no base expression");
 
   // Perform default conversions.
   DefaultFunctionArrayConversion(BaseExpr);
-  if (IsArrow) DefaultLvalueConversion(BaseExpr);
 
-  QualType BaseType = BaseExpr->getType();
+  if (IsArrow) {
+    DefaultLvalueConversion(BaseExpr);
+    if (BaseExpr.isInvalid())
+      return ExprError();
+  }
+
+  QualType BaseType = BaseExpr.get()->getType();
   assert(!BaseType->isDependentType());
 
   DeclarationName MemberName = R.getLookupName();
@@ -3693,19 +3732,19 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
       // overloaded operator->, but that should have been dealt with
       // by now.
       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
-        << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
+        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
         << FixItHint::CreateReplacement(OpLoc, ".");
       IsArrow = false;
     } else {
       Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
-        << BaseType << BaseExpr->getSourceRange();
+        << BaseType << BaseExpr.get()->getSourceRange();
       return ExprError();
     }
   }
 
   // Handle field access to simple records.
   if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
-    if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
+    if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
                                  RTy, OpLoc, SS, HasTemplateArgs))
       return ExprError();
 
@@ -3728,7 +3767,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
       // But we only actually find it this way on objects of type 'id',
       // apparently.
       if (OTy->isObjCId() && Member->isStr("isa"))
-        return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
+        return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
                                                Context.getObjCClassType()));
 
       if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
@@ -3761,7 +3800,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
 
         Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
           << IDecl->getDeclName() << MemberName
-          << BaseExpr->getSourceRange();
+          << BaseExpr.get()->getSourceRange();
         return ExprError();
       }
     }
@@ -3807,7 +3846,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
     }
 
     return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
-                                               MemberLoc, BaseExpr,
+                                               MemberLoc, BaseExpr.take(),
                                                IsArrow));
   }
 
@@ -3816,7 +3855,10 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
   if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
     // This actually uses the base as an r-value.
     DefaultLvalueConversion(BaseExpr);
-    assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
+    if (BaseExpr.isInvalid())
+      return ExprError();
+
+    assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
 
     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
 
@@ -3836,7 +3878,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
                                                          VK_LValue,
                                                          OK_ObjCProperty,
                                                          MemberLoc, 
-                                                         BaseExpr));
+                                                         BaseExpr.take()));
         }
 
         if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
@@ -3860,7 +3902,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
 
           return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
                                                          VK, OK,
-                                                         MemberLoc, BaseExpr));
+                                                         MemberLoc, BaseExpr.take()));
         }
       }
 
@@ -3930,7 +3972,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
         // FIXME: we must check that the setter has property type.
         return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
                                                        PType, VK, OK,
-                                                       MemberLoc, BaseExpr));
+                                                       MemberLoc, BaseExpr.take()));
       }
 
       if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
@@ -3942,7 +3984,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
     }
 
     // Normal property access.
-    return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
+    return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
                                      SourceLocation(), QualType(), false);
   }
 
@@ -3950,13 +3992,13 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
   if (BaseType->isExtVectorType()) {
     // FIXME: this expr should store IsArrow.
     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
-    ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
+    ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
     QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
                                            Member, MemberLoc);
     if (ret.isNull())
       return ExprError();
 
-    return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
+    return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
                                                     *Member, MemberLoc));
   }
 
@@ -3984,7 +4026,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
     if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
         MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
-          << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
+        << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
           << FixItHint::CreateReplacement(OpLoc, "->");
 
       // Recurse as an -> access.
@@ -3999,11 +4041,11 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
   bool TryCall = false;
   bool Overloaded = false;
   UnresolvedSet<8> AllOverloads;
-  if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr)) {
+  if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
     AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
     TryCall = true;
     Overloaded = true;
-  } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr)) {
+  } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
     if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
       AllOverloads.addDecl(Fun);
       TryCall = true;
@@ -4030,9 +4072,9 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
     }
 
     if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
-      Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
+      Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
           << 1 << 0
-          << BaseExpr->getSourceRange();
+          << BaseExpr.get()->getSourceRange();
       int ViableOverloadCount = ViableOverloads.size();
       int I;
       for (I = 0; I < ViableOverloadCount; ++I) {
@@ -4045,7 +4087,7 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
              diag::note_member_ref_possible_intended_overload);
       }
       if (I != ViableOverloadCount) {
-        Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
+        Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
             << int(ViableOverloadCount - I);
       }
       return ExprError();
@@ -4081,24 +4123,24 @@ Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
     // can emit a fixit and carry on pretending that BaseExpr was actually a
     // CallExpr.
     SourceLocation ParenInsertionLoc =
-        PP.getLocForEndOfToken(BaseExpr->getLocEnd());
-    Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
+        PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
+    Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
         << int(Overloaded) << 1
-        << BaseExpr->getSourceRange()
+        << BaseExpr.get()->getSourceRange()
         << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
-    ExprResult NewBase = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
+    ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
                                        MultiExprArg(*this, 0, 0),
                                        ParenInsertionLoc);
     if (NewBase.isInvalid())
       return ExprError();
-    BaseExpr = NewBase.takeAs<Expr>();
+    BaseExpr = NewBase;
     DefaultFunctionArrayConversion(BaseExpr);
     return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
                             ObjCImpDecl, HasTemplateArgs);
   }
 
   Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
-    << BaseType << BaseExpr->getSourceRange();
+    << BaseType << BaseExpr.get()->getSourceRange();
 
   return ExprError();
 }
@@ -4160,8 +4202,12 @@ ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
                                       NameInfo, TemplateArgs);
   } else {
     LookupResult R(*this, NameInfo, LookupMemberName);
-    Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
+    ExprResult BaseResult = Owned(Base);
+    Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
                               SS, ObjCImpDecl, TemplateArgs != 0);
+    if (BaseResult.isInvalid())
+      return ExprError();
+    Base = BaseResult.take();
 
     if (Result.isInvalid()) {
       Owned(Base);
@@ -4389,9 +4435,11 @@ bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
   if (CallType != VariadicDoesNotApply) {
     // Promote the arguments (C99 6.5.2.2p7).
     for (unsigned i = ArgIx; i != NumArgs; ++i) {
-      Expr *Arg = Args[i];
+      ExprResult Arg = Owned(Args[i]);
       Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
-      AllArgs.push_back(Arg);
+      if (Arg.isInvalid())
+        return true;
+      AllArgs.push_back(Arg.take());
     }
   }
   return Invalid;
@@ -4588,7 +4636,11 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
 
   // Promote the function operand.
-  UsualUnaryConversions(Fn);
+  ExprResult Result = Owned(Fn);
+  UsualUnaryConversions(Result);
+  if (Result.isInvalid())
+    return ExprError();
+  Fn = Result.take();
 
   // Make the call expr early, before semantic checks.  This guarantees cleanup
   // of arguments and function on error.
@@ -4696,7 +4748,13 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
         Arg = ArgE.takeAs<Expr>();
 
       } else {
-        DefaultArgumentPromotion(Arg);
+        ExprResult ArgE = Owned(Arg);
+        DefaultArgumentPromotion(ArgE);
+
+        if (ArgE.isInvalid())
+          return true;
+
+        Arg = ArgE.takeAs<Expr>();
       }
       
       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
@@ -4812,12 +4870,12 @@ Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
 
 /// Prepares for a scalar cast, performing all the necessary stages
 /// except the final cast and returning the kind required.
-static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
+static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
   // Also, callers should have filtered out the invalid cases with
   // pointers.  Everything else should be possible.
 
-  QualType SrcTy = Src->getType();
+  QualType SrcTy = Src.get()->getType();
   if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
     return CK_NoOp;
 
@@ -4847,7 +4905,7 @@ static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
   case Type::STK_Integral:
     switch (DestTy->getScalarTypeKind()) {
     case Type::STK_Pointer:
-      if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
+      if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
         return CK_NullToPointer;
       return CK_IntegralToPointer;
     case Type::STK_Bool:
@@ -4951,11 +5009,11 @@ static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
 
 /// CheckCastTypes - Check type constraints for casting between types.
 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
-                          Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
+                          ExprResult &castExpr, CastKind& Kind, ExprValueKind &VK,
                           CXXCastPath &BasePath, bool FunctionalStyle) {
   if (getLangOptions().CPlusPlus)
     return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
-                                          castExpr->getLocEnd()), 
+                                          castExpr.get()->getLocEnd()), 
                               castType, VK, castExpr, Kind, BasePath,
                               FunctionalStyle);
 
@@ -4967,6 +5025,8 @@ bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
   if (castType->isVoidType()) {
     // We don't necessarily do lvalue-to-rvalue conversions on this.
     IgnoredValueConversions(castExpr);
+    if (castExpr.isInvalid())
+      return true;
 
     // Cast to void allows any expr type.
     Kind = CK_ToVoid;
@@ -4974,18 +5034,20 @@ bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
   }
 
   DefaultFunctionArrayLvalueConversion(castExpr);
+  if (castExpr.isInvalid())
+    return true;
 
   if (RequireCompleteType(TyR.getBegin(), castType,
                           diag::err_typecheck_cast_to_incomplete))
     return true;
 
   if (!castType->isScalarType() && !castType->isVectorType()) {
-    if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
+    if (Context.hasSameUnqualifiedType(castType, castExpr.get()->getType()) &&
         (castType->isStructureType() || castType->isUnionType())) {
       // GCC struct/union extension: allow cast to self.
       // FIXME: Check that the cast destination type is complete.
       Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
-        << castType << castExpr->getSourceRange();
+        << castType << castExpr.get()->getSourceRange();
       Kind = CK_NoOp;
       return false;
     }
@@ -4997,71 +5059,71 @@ bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
            Field != FieldEnd; ++Field) {
         if (Context.hasSameUnqualifiedType(Field->getType(),
-                                           castExpr->getType()) &&
+                                           castExpr.get()->getType()) &&
             !Field->isUnnamedBitfield()) {
           Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
-            << castExpr->getSourceRange();
+            << castExpr.get()->getSourceRange();
           break;
         }
       }
       if (Field == FieldEnd)
         return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
-          << castExpr->getType() << castExpr->getSourceRange();
+          << castExpr.get()->getType() << castExpr.get()->getSourceRange();
       Kind = CK_ToUnion;
       return false;
     }
 
     // Reject any other conversions to non-scalar types.
     return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
-      << castType << castExpr->getSourceRange();
+      << castType << castExpr.get()->getSourceRange();
   }
 
   // The type we're casting to is known to be a scalar or vector.
 
   // Require the operand to be a scalar or vector.
-  if (!castExpr->getType()->isScalarType() &&
-      !castExpr->getType()->isVectorType()) {
-    return Diag(castExpr->getLocStart(),
+  if (!castExpr.get()->getType()->isScalarType() &&
+      !castExpr.get()->getType()->isVectorType()) {
+    return Diag(castExpr.get()->getLocStart(),
                 diag::err_typecheck_expect_scalar_operand)
-      << castExpr->getType() << castExpr->getSourceRange();
+      << castExpr.get()->getType() << castExpr.get()->getSourceRange();
   }
 
   if (castType->isExtVectorType())
     return CheckExtVectorCast(TyR, castType, castExpr, Kind);
 
   if (castType->isVectorType())
-    return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
-  if (castExpr->getType()->isVectorType())
-    return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
+    return CheckVectorCast(TyR, castType, castExpr.get()->getType(), Kind);
+  if (castExpr.get()->getType()->isVectorType())
+    return CheckVectorCast(TyR, castExpr.get()->getType(), castType, Kind);
 
   // The source and target types are both scalars, i.e.
   //   - arithmetic types (fundamental, enum, and complex)
   //   - all kinds of pointers
   // Note that member pointers were filtered out with C++, above.
 
-  if (isa<ObjCSelectorExpr>(castExpr))
-    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
+  if (isa<ObjCSelectorExpr>(castExpr.get()))
+    return Diag(castExpr.get()->getLocStart(), diag::err_cast_selector_expr);
 
   // If either type is a pointer, the other type has to be either an
   // integer or a pointer.
   if (!castType->isArithmeticType()) {
-    QualType castExprType = castExpr->getType();
+    QualType castExprType = castExpr.get()->getType();
     if (!castExprType->isIntegralType(Context) && 
         castExprType->isArithmeticType())
-      return Diag(castExpr->getLocStart(),
+      return Diag(castExpr.get()->getLocStart(),
                   diag::err_cast_pointer_from_non_pointer_int)
-        << castExprType << castExpr->getSourceRange();
-  } else if (!castExpr->getType()->isArithmeticType()) {
+        << castExprType << castExpr.get()->getSourceRange();
+  } else if (!castExpr.get()->getType()->isArithmeticType()) {
     if (!castType->isIntegralType(Context) && castType->isArithmeticType())
-      return Diag(castExpr->getLocStart(),
+      return Diag(castExpr.get()->getLocStart(),
                   diag::err_cast_pointer_to_non_pointer_int)
-        << castType << castExpr->getSourceRange();
+        << castType << castExpr.get()->getSourceRange();
   }
 
   Kind = PrepareScalarCast(*this, castExpr, castType);
 
   if (Kind == CK_BitCast)
-    CheckCastAlign(castExpr, castType, TyR);
+    CheckCastAlign(castExpr.get(), castType, TyR);
 
   return false;
 }
@@ -5086,11 +5148,11 @@ bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
   return false;
 }
 
-bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
+bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, ExprResult &CastExpr,
                               CastKind &Kind) {
   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
 
-  QualType SrcTy = CastExpr->getType();
+  QualType SrcTy = CastExpr.get()->getType();
 
   // If SrcTy is a VectorType, the total size must match to explicitly cast to
   // an ExtVectorType.
@@ -5143,9 +5205,12 @@ Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
   CastKind Kind = CK_Invalid;
   ExprValueKind VK = VK_RValue;
   CXXCastPath BasePath;
-  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
-                     Kind, VK, BasePath))
+  ExprResult CastResult = Owned(castExpr);
+  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), CastResult,
+                     Kind, VK, BasePath) ||
+      CastResult.isInvalid())
     return ExprError();
+  castExpr = CastResult.take();
 
   return Owned(CStyleCastExpr::Create(Context,
                                     Ty->getType().getNonLValueExprType(Context),
@@ -5276,22 +5341,19 @@ bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
 /// In that case, lhs = cond.
 /// C99 6.5.15
-QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
+QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
                                         ExprValueKind &VK, ExprObjectKind &OK,
                                         SourceLocation QuestionLoc) {
   // If both LHS and RHS are overloaded functions, try to resolve them.
-  if (Context.hasSameType(LHS->getType(), RHS->getType()) && 
-      LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
-    ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
-    if (LHSResult.isInvalid())
+  if (Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()) && 
+      LHS.get()->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
+    LHS = CheckPlaceholderExpr(LHS.take(), QuestionLoc);
+    if (LHS.isInvalid())
       return QualType();
 
-    ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
-    if (RHSResult.isInvalid())
+    RHS = CheckPlaceholderExpr(RHS.take(), QuestionLoc);
+    if (RHS.isInvalid())
       return QualType();
-
-    LHS = LHSResult.take();
-    RHS = RHSResult.take();
   }
 
   // C++ is sufficiently different to merit its own checker.
@@ -5302,11 +5364,18 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   OK = OK_Ordinary;
 
   UsualUnaryConversions(Cond);
+  if (Cond.isInvalid())
+    return QualType();
   UsualUnaryConversions(LHS);
+  if (LHS.isInvalid())
+    return QualType();
   UsualUnaryConversions(RHS);
-  QualType CondTy = Cond->getType();
-  QualType LHSTy = LHS->getType();
-  QualType RHSTy = RHS->getType();
+  if (RHS.isInvalid())
+    return QualType();
+
+  QualType CondTy = Cond.get()->getType();
+  QualType LHSTy = LHS.get()->getType();
+  QualType RHSTy = RHS.get()->getType();
 
   // first, check the condition.
   if (!CondTy->isScalarType()) { // C99 6.5.15p2
@@ -5314,14 +5383,14 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     // Throw an error if its not either.
     if (getLangOptions().OpenCL) {
       if (!CondTy->isVectorType()) {
-        Diag(Cond->getLocStart(), 
+        Diag(Cond.get()->getLocStart(), 
              diag::err_typecheck_cond_expect_scalar_or_vector)
           << CondTy;
         return QualType();
       }
     }
     else {
-      Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
+      Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
         << CondTy;
       return QualType();
     }
@@ -5337,12 +5406,12 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   if (getLangOptions().OpenCL && CondTy->isVectorType()) {
     // Both operands should be of scalar type.
     if (!LHSTy->isScalarType()) {
-      Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
+      Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
         << CondTy;
       return QualType();
     }
     if (!RHSTy->isScalarType()) {
-      Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
+      Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
         << CondTy;
       return QualType();
     }
@@ -5355,7 +5424,9 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // to find a common type: C99 6.5.15p3,5.
   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
     UsualArithmeticConversions(LHS, RHS);
-    return LHS->getType();
+    if (LHS.isInvalid() || RHS.isInvalid())
+      return QualType();
+    return LHS.get()->getType();
   }
 
   // If both operands are the same structure or union type, the result is that
@@ -5373,11 +5444,11 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // The following || allows only one side to be void (a GCC-ism).
   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
     if (!LHSTy->isVoidType())
-      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
-        << RHS->getSourceRange();
+      Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
+        << RHS.get()->getSourceRange();
     if (!RHSTy->isVoidType())
-      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
-        << LHS->getSourceRange();
+      Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
+        << LHS.get()->getSourceRange();
     ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
     ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
     return Context.VoidTy;
@@ -5385,13 +5456,13 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
   // the type of the other operand."
   if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
-      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
+      RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
     // promote the null to a pointer.
     ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
     return LHSTy;
   }
   if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
-      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
+      LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
     ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
     return RHSTy;
   }
@@ -5399,6 +5470,8 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // All objective-c pointer type analysis is done here.
   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
                                                         QuestionLoc);
+  if (LHS.isInvalid() || RHS.isInvalid())
+    return QualType();
   if (!compositeType.isNull())
     return compositeType;
 
@@ -5413,7 +5486,7 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
         return destType;
       }
       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
-      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
+      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       return QualType();
     }
     // We have 2 block pointer types.
@@ -5428,7 +5501,7 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
                                     rhptee.getUnqualifiedType())) {
       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
-      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
+      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       // In this situation, we assume void* type. No especially good
       // reason, but this is what gcc does, and we do have to pick
       // to get a consistent AST.
@@ -5479,7 +5552,7 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
                                     rhptee.getUnqualifiedType())) {
       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
-        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
+        << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       // In this situation, we assume void* type. No especially good
       // reason, but this is what gcc does, and we do have to pick
       // to get a consistent AST.
@@ -5504,13 +5577,13 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // null pointers have been filtered out by this point.
   if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
-      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
+      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
     ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
     return RHSTy;
   }
   if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
-      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
+      << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
     ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
     return LHSTy;
   }
@@ -5518,21 +5591,21 @@ QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // Emit a better diagnostic if one of the expressions is a null pointer
   // constant and the other is not a pointer type. In this case, the user most
   // likely forgot to take the address of the other expression.
-  if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
+  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
     return QualType();
 
   // Otherwise, the operands are not compatible.
   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
-    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
+    << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   return QualType();
 }
 
 /// FindCompositeObjCPointerType - Helper method to find composite type of
 /// two objective-c pointer types of the two input expressions.
-QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
+QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
                                         SourceLocation QuestionLoc) {
-  QualType LHSTy = LHS->getType();
-  QualType RHSTy = RHS->getType();
+  QualType LHSTy = LHS.get()->getType();
+  QualType RHSTy = RHS.get()->getType();
 
   // Handle things like Class and struct objc_class*.  Here we case the result
   // to the pseudo-builtin, because that will be implicitly cast back to the
@@ -5613,7 +5686,7 @@ QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
     else {
       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
       << LHSTy << RHSTy
-      << LHS->getSourceRange() << RHS->getSourceRange();
+      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       QualType incompatTy = Context.getObjCIdType();
       ImpCastExprToType(LHS, incompatTy, CK_BitCast);
       ImpCastExprToType(RHS, incompatTy, CK_BitCast);
@@ -5674,7 +5747,11 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
           && commonExpr->isOrdinaryOrBitFieldObject()
           && RHSExpr->isOrdinaryOrBitFieldObject()
           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
-      UsualUnaryConversions(commonExpr);
+      ExprResult commonRes = Owned(commonExpr);
+      UsualUnaryConversions(commonRes);
+      if (commonRes.isInvalid())
+        return ExprError();
+      commonExpr = commonRes.take();
     }
 
     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
@@ -5686,19 +5763,21 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
 
   ExprValueKind VK = VK_RValue;
   ExprObjectKind OK = OK_Ordinary;
-  QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr, 
+  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
+  QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
                                              VK, OK, QuestionLoc);
-  if (result.isNull())
+  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
+      RHS.isInvalid())
     return ExprError();
 
   if (!commonExpr)
-    return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
-                                                   LHSExpr, ColonLoc, 
-                                                   RHSExpr, result, VK, OK));
+    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
+                                                   LHS.take(), ColonLoc, 
+                                                   RHS.take(), result, VK, OK));
 
   return Owned(new (Context)
-    BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
-                              RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
+    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
+                              RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
 }
 
 // checkPointerTypesForAssignment - This is a very tricky routine (despite
@@ -5878,7 +5957,7 @@ Sema::CheckAssignmentConstraints(SourceLocation Loc,
   // adds casts to this they'll be wasted, but fortunately that doesn't
   // usually happen on valid code.
   OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
-  Expr *rhsPtr = &rhs;
+  ExprResult rhsPtr = &rhs;
   CastKind K = CK_Invalid;
 
   return CheckAssignmentConstraints(lhsType, rhsPtr, K);
@@ -5902,9 +5981,9 @@ Sema::CheckAssignmentConstraints(SourceLocation Loc,
 ///
 /// Sets 'Kind' for any result kind except Incompatible.
 Sema::AssignConvertType
-Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
+Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
                                  CastKind &Kind) {
-  QualType rhsType = rhs->getType();
+  QualType rhsType = rhs.get()->getType();
 
   // Get canonical types.  We're not formatting these types, just comparing
   // them.
@@ -6144,10 +6223,11 @@ Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
 
 /// \brief Constructs a transparent union from an expression that is
 /// used to initialize the transparent union.
-static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
+static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
                                       QualType UnionType, FieldDecl *Field) {
   // Build an initializer list that designates the appropriate member
   // of the transparent union.
+  Expr *E = EResult.take();
   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
                                                    &E, 1,
                                                    SourceLocation());
@@ -6157,13 +6237,14 @@ static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
   // Build a compound literal constructing a value of the transparent
   // union type from this initializer list.
   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
-  E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
-                                  VK_RValue, Initializer, false);
+  EResult = S.Owned(
+    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
+                                VK_RValue, Initializer, false));
 }
 
 Sema::AssignConvertType
-Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
-  QualType FromType = rExpr->getType();
+Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
+  QualType FromType = rExpr.get()->getType();
 
   // If the ArgType is a Union type, we want to handle a potential
   // transparent_union GCC extension.
@@ -6189,7 +6270,7 @@ Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
           break;
         }
 
-      if (rExpr->isNullPointerConstant(Context,
+      if (rExpr.get()->isNullPointerConstant(Context,
                                        Expr::NPC_ValueDependentIsNull)) {
         ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
         InitField = *it;
@@ -6197,12 +6278,10 @@ Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
       }
     }
 
-    Expr *rhs = rExpr;
     CastKind Kind = CK_Invalid;
-    if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
+    if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
           == Compatible) {
-      ImpCastExprToType(rhs, it->getType(), Kind);
-      rExpr = rhs;
+      ImpCastExprToType(rExpr, it->getType(), Kind);
       InitField = *it;
       break;
     }
@@ -6211,12 +6290,12 @@ Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
   if (!InitField)
     return Incompatible;
 
-  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
+  ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
   return Compatible;
 }
 
 Sema::AssignConvertType
-Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
+Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
   if (getLangOptions().CPlusPlus) {
     if (!lhsType->isRecordType()) {
       // C++ 5.17p3: If the left operand is not of class type, the
@@ -6237,7 +6316,7 @@ Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
   if ((lhsType->isPointerType() ||
        lhsType->isObjCObjectPointerType() ||
        lhsType->isBlockPointerType())
-      && rExpr->isNullPointerConstant(Context,
+      && rExpr.get()->isNullPointerConstant(Context,
                                       Expr::NPC_ValueDependentIsNull)) {
     ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
     return Compatible;
@@ -6249,8 +6328,11 @@ Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
   // expressions that suppress this implicit conversion (&, sizeof).
   //
   // Suppress this for references: C++ 8.5.3p5.
-  if (!lhsType->isReferenceType())
+  if (!lhsType->isReferenceType()) {
     DefaultFunctionArrayLvalueConversion(rExpr);
+    if (rExpr.isInvalid())
+      return Incompatible;
+  }
 
   CastKind Kind = CK_Invalid;
   Sema::AssignConvertType result =
@@ -6262,25 +6344,25 @@ Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
   // so that we can use references in built-in functions even in C.
   // The getNonReferenceType() call makes sure that the resulting expression
   // does not have reference type.
-  if (result != Incompatible && rExpr->getType() != lhsType)
+  if (result != Incompatible && rExpr.get()->getType() != lhsType)
     ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
   return result;
 }
 
-QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
+QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
   Diag(Loc, diag::err_typecheck_invalid_operands)
-    << lex->getType() << rex->getType()
-    << lex->getSourceRange() << rex->getSourceRange();
+    << lex.get()->getType() << rex.get()->getType()
+    << lex.get()->getSourceRange() << rex.get()->getSourceRange();
   return QualType();
 }
 
-QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
+QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
   // For conversion purposes, we ignore any qualifiers.
   // For example, "const float" and "float" are equivalent.
   QualType lhsType =
-    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
+    Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
   QualType rhsType =
-    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
+    Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
 
   // If the vector types are identical, return.
   if (lhsType == rhsType)
@@ -6355,72 +6437,78 @@ QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
 
   // Vectors of different size or scalar and non-ext-vector are errors.
   Diag(Loc, diag::err_typecheck_vector_not_convertable)
-    << lex->getType() << rex->getType()
-    << lex->getSourceRange() << rex->getSourceRange();
+    << lex.get()->getType() << rex.get()->getType()
+    << lex.get()->getSourceRange() << rex.get()->getSourceRange();
   return QualType();
 }
 
 QualType Sema::CheckMultiplyDivideOperands(
-  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
+  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
     return CheckVectorOperands(Loc, lex, rex);
 
   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
+  if (lex.isInvalid() || rex.isInvalid())
+    return QualType();
 
-  if (!lex->getType()->isArithmeticType() ||
-      !rex->getType()->isArithmeticType())
+  if (!lex.get()->getType()->isArithmeticType() ||
+      !rex.get()->getType()->isArithmeticType())
     return InvalidOperands(Loc, lex, rex);
 
   // Check for division by zero.
   if (isDiv &&
-      rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
-    DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_division_by_zero)
-                                      << rex->getSourceRange());
+      rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
+    DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
+                                     << rex.get()->getSourceRange());
 
   return compType;
 }
 
 QualType Sema::CheckRemainderOperands(
-  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
-    if (lex->getType()->hasIntegerRepresentation() && 
-        rex->getType()->hasIntegerRepresentation())
+  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
+    if (lex.get()->getType()->hasIntegerRepresentation() && 
+        rex.get()->getType()->hasIntegerRepresentation())
       return CheckVectorOperands(Loc, lex, rex);
     return InvalidOperands(Loc, lex, rex);
   }
 
   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
+  if (lex.isInvalid() || rex.isInvalid())
+    return QualType();
 
-  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
+  if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
     return InvalidOperands(Loc, lex, rex);
 
   // Check for remainder by zero.
-  if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
-    DiagRuntimeBehavior(Loc, rex, PDiag(diag::warn_remainder_by_zero)
-                                  << rex->getSourceRange());
+  if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
+    DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
+                                 << rex.get()->getSourceRange());
 
   return compType;
 }
 
 QualType Sema::CheckAdditionOperands( // C99 6.5.6
-  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
+  ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
     QualType compType = CheckVectorOperands(Loc, lex, rex);
     if (CompLHSTy) *CompLHSTy = compType;
     return compType;
   }
 
   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
+  if (lex.isInvalid() || rex.isInvalid())
+    return QualType();
 
   // handle the common case first (both operands are arithmetic).
-  if (lex->getType()->isArithmeticType() &&
-      rex->getType()->isArithmeticType()) {
+  if (lex.get()->getType()->isArithmeticType() &&
+      rex.get()->getType()->isArithmeticType()) {
     if (CompLHSTy) *CompLHSTy = compType;
     return compType;
   }
 
   // Put any potential pointer into PExp
-  Expr* PExp = lex, *IExp = rex;
+  Expr* PExp = lex.get(), *IExp = rex.get();
   if (IExp->getType()->isAnyPointerType())
     std::swap(PExp, IExp);
 
@@ -6433,23 +6521,23 @@ QualType Sema::CheckAdditionOperands( // C99 6.5.6
       if (PointeeTy->isVoidType()) {
         if (getLangOptions().CPlusPlus) {
           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
-            << lex->getSourceRange() << rex->getSourceRange();
+            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
           return QualType();
         }
 
         // GNU extension: arithmetic on pointer to void
         Diag(Loc, diag::ext_gnu_void_ptr)
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       } else if (PointeeTy->isFunctionType()) {
         if (getLangOptions().CPlusPlus) {
           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
-            << lex->getType() << lex->getSourceRange();
+            << lex.get()->getType() << lex.get()->getSourceRange();
           return QualType();
         }
 
         // GNU extension: arithmetic on pointer to function
         Diag(Loc, diag::ext_gnu_ptr_func_arith)
-          << lex->getType() << lex->getSourceRange();
+          << lex.get()->getType() << lex.get()->getSourceRange();
       } else {
         // Check if we require a complete type.
         if (((PExp->getType()->isPointerType() &&
@@ -6469,9 +6557,9 @@ QualType Sema::CheckAdditionOperands( // C99 6.5.6
       }
 
       if (CompLHSTy) {
-        QualType LHSTy = Context.isPromotableBitField(lex);
+        QualType LHSTy = Context.isPromotableBitField(lex.get());
         if (LHSTy.isNull()) {
-          LHSTy = lex->getType();
+          LHSTy = lex.get()->getType();
           if (LHSTy->isPromotableIntegerType())
             LHSTy = Context.getPromotedIntegerType(LHSTy);
         }
@@ -6485,28 +6573,30 @@ QualType Sema::CheckAdditionOperands( // C99 6.5.6
 }
 
 // C99 6.5.6
-QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
+QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
                                         SourceLocation Loc, QualType* CompLHSTy) {
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
     QualType compType = CheckVectorOperands(Loc, lex, rex);
     if (CompLHSTy) *CompLHSTy = compType;
     return compType;
   }
 
   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
+  if (lex.isInvalid() || rex.isInvalid())
+    return QualType();
 
   // Enforce type constraints: C99 6.5.6p3.
 
   // Handle the common case first (both operands are arithmetic).
-  if (lex->getType()->isArithmeticType()
-      && rex->getType()->isArithmeticType()) {
+  if (lex.get()->getType()->isArithmeticType() &&
+      rex.get()->getType()->isArithmeticType()) {
     if (CompLHSTy) *CompLHSTy = compType;
     return compType;
   }
 
   // Either ptr - int   or   ptr - ptr.
-  if (lex->getType()->isAnyPointerType()) {
-    QualType lpointee = lex->getType()->getPointeeType();
+  if (lex.get()->getType()->isAnyPointerType()) {
+    QualType lpointee = lex.get()->getType()->getPointeeType();
 
     // The LHS must be an completely-defined object type.
 
@@ -6515,7 +6605,7 @@ QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
     if (lpointee->isVoidType()) {
       if (getLangOptions().CPlusPlus) {
         Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
         return QualType();
       }
 
@@ -6524,42 +6614,42 @@ QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
     } else if (lpointee->isFunctionType()) {
       if (getLangOptions().CPlusPlus) {
         Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
-          << lex->getType() << lex->getSourceRange();
+          << lex.get()->getType() << lex.get()->getSourceRange();
         return QualType();
       }
 
       // GNU C extension: arithmetic on pointer to function
-      ComplainAboutFunc = lex;
+      ComplainAboutFunc = lex.get();
     } else if (!lpointee->isDependentType() &&
                RequireCompleteType(Loc, lpointee,
                                    PDiag(diag::err_typecheck_sub_ptr_object)
-                                     << lex->getSourceRange()
-                                     << lex->getType()))
+                                     << lex.get()->getSourceRange()
+                                     << lex.get()->getType()))
       return QualType();
 
     // Diagnose bad cases where we step over interface counts.
     if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
       Diag(Loc, diag::err_arithmetic_nonfragile_interface)
-        << lpointee << lex->getSourceRange();
+        << lpointee << lex.get()->getSourceRange();
       return QualType();
     }
 
     // The result type of a pointer-int computation is the pointer type.
-    if (rex->getType()->isIntegerType()) {
+    if (rex.get()->getType()->isIntegerType()) {
       if (ComplainAboutVoid)
         Diag(Loc, diag::ext_gnu_void_ptr)
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       if (ComplainAboutFunc)
         Diag(Loc, diag::ext_gnu_ptr_func_arith)
           << ComplainAboutFunc->getType()
           << ComplainAboutFunc->getSourceRange();
 
-      if (CompLHSTy) *CompLHSTy = lex->getType();
-      return lex->getType();
+      if (CompLHSTy) *CompLHSTy = lex.get()->getType();
+      return lex.get()->getType();
     }
 
     // Handle pointer-pointer subtractions.
-    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
+    if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
       QualType rpointee = RHSPTy->getPointeeType();
 
       // RHS must be a completely-type object type.
@@ -6567,7 +6657,7 @@ QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
       if (rpointee->isVoidType()) {
         if (getLangOptions().CPlusPlus) {
           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
-            << lex->getSourceRange() << rex->getSourceRange();
+            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
           return QualType();
         }
 
@@ -6575,26 +6665,26 @@ QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
       } else if (rpointee->isFunctionType()) {
         if (getLangOptions().CPlusPlus) {
           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
-            << rex->getType() << rex->getSourceRange();
+            << rex.get()->getType() << rex.get()->getSourceRange();
           return QualType();
         }
 
         // GNU extension: arithmetic on pointer to function
         if (!ComplainAboutFunc)
-          ComplainAboutFunc = rex;
+          ComplainAboutFunc = rex.get();
       } else if (!rpointee->isDependentType() &&
                  RequireCompleteType(Loc, rpointee,
                                      PDiag(diag::err_typecheck_sub_ptr_object)
-                                       << rex->getSourceRange()
-                                       << rex->getType()))
+                                       << rex.get()->getSourceRange()
+                                       << rex.get()->getType()))
         return QualType();
 
       if (getLangOptions().CPlusPlus) {
         // Pointee types must be the same: C++ [expr.add]
         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
-            << lex->getType() << rex->getType()
-            << lex->getSourceRange() << rex->getSourceRange();
+            << lex.get()->getType() << rex.get()->getType()
+            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
           return QualType();
         }
       } else {
@@ -6603,21 +6693,21 @@ QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
-            << lex->getType() << rex->getType()
-            << lex->getSourceRange() << rex->getSourceRange();
+            << lex.get()->getType() << rex.get()->getType()
+            << lex.get()->getSourceRange() << rex.get()->getSourceRange();
           return QualType();
         }
       }
 
       if (ComplainAboutVoid)
         Diag(Loc, diag::ext_gnu_void_ptr)
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       if (ComplainAboutFunc)
         Diag(Loc, diag::ext_gnu_ptr_func_arith)
           << ComplainAboutFunc->getType()
           << ComplainAboutFunc->getSourceRange();
 
-      if (CompLHSTy) *CompLHSTy = lex->getType();
+      if (CompLHSTy) *CompLHSTy = lex.get()->getType();
       return Context.getPointerDiffType();
     }
   }
@@ -6631,26 +6721,26 @@ static bool isScopedEnumerationType(QualType T) {
   return false;
 }
 
-static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
+static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
                                    SourceLocation Loc, unsigned Opc,
                                    QualType LHSTy) {
   llvm::APSInt Right;
   // Check right/shifter operand
-  if (rex->isValueDependent() || !rex->isIntegerConstantExpr(Right, S.Context))
+  if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
     return;
 
   if (Right.isNegative()) {
-    S.DiagRuntimeBehavior(Loc, rex,
+    S.DiagRuntimeBehavior(Loc, rex.get(),
                           S.PDiag(diag::warn_shift_negative)
-                            << rex->getSourceRange());
+                            << rex.get()->getSourceRange());
     return;
   }
   llvm::APInt LeftBits(Right.getBitWidth(),
-                       S.Context.getTypeSize(lex->getType()));
+                       S.Context.getTypeSize(lex.get()->getType()));
   if (Right.uge(LeftBits)) {
-    S.DiagRuntimeBehavior(Loc, rex,
+    S.DiagRuntimeBehavior(Loc, rex.get(),
                           S.PDiag(diag::warn_shift_gt_typewidth)
-                            << rex->getSourceRange());
+                            << rex.get()->getSourceRange());
     return;
   }
   if (Opc != BO_Shl)
@@ -6661,7 +6751,7 @@ static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
   // integers have defined behavior modulo one more than the maximum value
   // representable in the result type, so never warn for those.
   llvm::APSInt Left;
-  if (lex->isValueDependent() || !lex->isIntegerConstantExpr(Left, S.Context) ||
+  if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
       LHSTy->hasUnsignedIntegerRepresentation())
     return;
   llvm::APInt ResultBits =
@@ -6678,32 +6768,32 @@ static void DiagnoseBadShiftValues(Sema& S, Expr *&lex, Expr *&rex,
   if (LeftBits == ResultBits - 1) {
     S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
         << Result.toString(10) << LHSTy
-        << lex->getSourceRange() << rex->getSourceRange();
+        << lex.get()->getSourceRange() << rex.get()->getSourceRange();
     return;
   }
 
   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
     << Result.toString(10) << Result.getMinSignedBits() << LHSTy
-    << Left.getBitWidth() << lex->getSourceRange() << rex->getSourceRange();
+    << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
 }
 
 // C99 6.5.7
-QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
+QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
                                   unsigned Opc, bool isCompAssign) {
   // C99 6.5.7p2: Each of the operands shall have integer type.
-  if (!lex->getType()->hasIntegerRepresentation() || 
-      !rex->getType()->hasIntegerRepresentation())
+  if (!lex.get()->getType()->hasIntegerRepresentation() || 
+      !rex.get()->getType()->hasIntegerRepresentation())
     return InvalidOperands(Loc, lex, rex);
 
   // C++0x: Don't allow scoped enums. FIXME: Use something better than
   // hasIntegerRepresentation() above instead of this.
-  if (isScopedEnumerationType(lex->getType()) ||
-      isScopedEnumerationType(rex->getType())) {
+  if (isScopedEnumerationType(lex.get()->getType()) ||
+      isScopedEnumerationType(rex.get()->getType())) {
     return InvalidOperands(Loc, lex, rex);
   }
 
   // Vector shifts promote their scalar inputs to vector type.
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
     return CheckVectorOperands(Loc, lex, rex);
 
   // Shifts don't perform usual arithmetic conversions, they just do integer
@@ -6711,13 +6801,17 @@ QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
 
   // For the LHS, do usual unary conversions, but then reset them away
   // if this is a compound assignment.
-  Expr *old_lex = lex;
+  ExprResult old_lex = lex;
   UsualUnaryConversions(lex);
-  QualType LHSTy = lex->getType();
+  if (lex.isInvalid())
+    return QualType();
+  QualType LHSTy = lex.get()->getType();
   if (isCompAssign) lex = old_lex;
 
   // The RHS is simpler.
   UsualUnaryConversions(rex);
+  if (rex.isInvalid())
+    return QualType();
 
   // Sanity-check shift operands
   DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
@@ -6737,19 +6831,19 @@ static bool IsWithinTemplateSpecialization(Decl *D) {
 }
 
 // C99 6.5.8, C++ [expr.rel]
-QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
+QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
                                     unsigned OpaqueOpc, bool isRelational) {
   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
 
   // Handle vector comparisons separately.
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
     return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
 
-  QualType lType = lex->getType();
-  QualType rType = rex->getType();
+  QualType lType = lex.get()->getType();
+  QualType rType = rex.get()->getType();
 
-  Expr *LHSStripped = lex->IgnoreParenImpCasts();
-  Expr *RHSStripped = rex->IgnoreParenImpCasts();
+  Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
+  Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
   QualType LHSStrippedType = LHSStripped->getType();
   QualType RHSStrippedType = RHSStripped->getType();
 
@@ -6761,15 +6855,15 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
           !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
         Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
           << LHSStrippedType << RHSStrippedType
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       }
     }
   }
 
   if (!lType->hasFloatingRepresentation() &&
       !(lType->isBlockPointerType() && isRelational) &&
-      !lex->getLocStart().isMacroID() &&
-      !rex->getLocStart().isMacroID()) {
+      !lex.get()->getLocStart().isMacroID() &&
+      !rex.get()->getLocStart().isMacroID()) {
     // For non-floating point types, check for self-comparisons of the form
     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
     // often indicate logic errors in the program.
@@ -6825,13 +6919,13 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
         !RHSStripped->isNullPointerConstant(Context,
                                             Expr::NPC_ValueDependentIsNull)) {
-      literalString = lex;
+      literalString = lex.get();
       literalStringStripped = LHSStripped;
     } else if ((isa<StringLiteral>(RHSStripped) ||
                 isa<ObjCEncodeExpr>(RHSStripped)) &&
                !LHSStripped->isNullPointerConstant(Context,
                                             Expr::NPC_ValueDependentIsNull)) {
-      literalString = rex;
+      literalString = rex.get();
       literalStringStripped = RHSStripped;
     }
 
@@ -6855,15 +6949,23 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
   }
 
   // C99 6.5.8p3 / C99 6.5.9p4
-  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
+  if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
     UsualArithmeticConversions(lex, rex);
+    if (lex.isInvalid() || rex.isInvalid())
+      return QualType();
+  }
   else {
     UsualUnaryConversions(lex);
+    if (lex.isInvalid())
+      return QualType();
+
     UsualUnaryConversions(rex);
+    if (rex.isInvalid())
+      return QualType();
   }
 
-  lType = lex->getType();
-  rType = rex->getType();
+  lType = lex.get()->getType();
+  rType = rex.get()->getType();
 
   // The result of comparisons is 'bool' in C++, 'int' in C.
   QualType ResultTy = Context.getLogicalOperationType();
@@ -6874,15 +6976,15 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
   } else {
     // Check for comparisons of floating point operands using != and ==.
     if (lType->hasFloatingRepresentation())
-      CheckFloatComparison(Loc,lex,rex);
+      CheckFloatComparison(Loc, lex.get(), rex.get());
 
     if (lType->isArithmeticType() && rType->isArithmeticType())
       return ResultTy;
   }
 
-  bool LHSIsNull = lex->isNullPointerConstant(Context,
+  bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
                                               Expr::NPC_ValueDependentIsNull);
-  bool RHSIsNull = rex->isNullPointerConstant(Context,
+  bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
                                               Expr::NPC_ValueDependentIsNull);
 
   // All of the following pointer-related warnings are GCC extensions, except
@@ -6908,7 +7010,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
                isSFINAEContext()? 
                    diag::err_typecheck_comparison_of_fptr_to_void
                  : diag::ext_typecheck_comparison_of_fptr_to_void)
-            << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+            << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
           
           if (isSFINAEContext())
             return QualType();
@@ -6931,13 +7033,13 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
                               isSFINAEContext()? 0 : &NonStandardCompositeType);
       if (T.isNull()) {
         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
         return QualType();
       } else if (NonStandardCompositeType) {
         Diag(Loc,
              diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
           << lType << rType << T
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       }
 
       ImpCastExprToType(lex, T, CK_BitCast);
@@ -6950,7 +7052,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
       // Valid unless a relational comparison of function pointers
       if (isRelational && LCanPointeeTy->isFunctionType()) {
         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       }
     } else if (!isRelational &&
                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
@@ -6958,12 +7060,12 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
           && !LHSIsNull && !RHSIsNull) {
         Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       }
     } else {
       // Invalid
       Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
-        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
     }
     if (LCanPointeeTy != RCanPointeeTy)
       ImpCastExprToType(rex, lType, CK_BitCast);
@@ -7014,13 +7116,13 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
                               isSFINAEContext()? 0 : &NonStandardCompositeType);
       if (T.isNull()) {
         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
         return QualType();
       } else if (NonStandardCompositeType) {
         Diag(Loc,
              diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
           << lType << rType << T
-          << lex->getSourceRange() << rex->getSourceRange();
+          << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       }
 
       ImpCastExprToType(lex, T, CK_BitCast);
@@ -7030,8 +7132,8 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
 
     // Handle scoped enumeration types specifically, since they don't promote
     // to integers.
-    if (lex->getType()->isEnumeralType() &&
-        Context.hasSameUnqualifiedType(lex->getType(), rex->getType()))
+    if (lex.get()->getType()->isEnumeralType() &&
+        Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
       return ResultTy;
   }
 
@@ -7043,11 +7145,12 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
     if (!LHSIsNull && !RHSIsNull &&
         !Context.typesAreCompatible(lpointee, rpointee)) {
       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
-        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
     }
     ImpCastExprToType(rex, lType, CK_BitCast);
     return ResultTy;
   }
+
   // Allow block pointers to be compared with null pointer constants.
   if (!isRelational
       && ((lType->isBlockPointerType() && rType->isPointerType())
@@ -7058,7 +7161,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
             || (lType->isPointerType() && lType->getAs<PointerType>()
                 ->getPointeeType()->isVoidType())))
         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
     }
     ImpCastExprToType(rex, lType, CK_BitCast);
     return ResultTy;
@@ -7076,7 +7179,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
       if (!LPtrToVoid && !RPtrToVoid &&
           !Context.typesAreCompatible(lType, rType)) {
         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       }
       ImpCastExprToType(rex, lType, CK_BitCast);
       return ResultTy;
@@ -7084,7 +7187,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
     if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
       if (!Context.areComparableObjCPointerTypes(lType, rType))
         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
-          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+          << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       ImpCastExprToType(rex, lType, CK_BitCast);
       return ResultTy;
     }
@@ -7107,7 +7210,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
 
     if (DiagID) {
       Diag(Loc, DiagID)
-        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
+        << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
       if (isError)
         return QualType();
     }
@@ -7140,7 +7243,7 @@ QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
 /// operates on extended vector types.  Instead of producing an IntTy result,
 /// like a scalar comparison, a vector comparison produces a vector of integer
 /// types.
-QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
+QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
                                           SourceLocation Loc,
                                           bool isRelational) {
   // Check to make sure we're operating on vectors of the same type and width,
@@ -7154,15 +7257,15 @@ QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
   if (getLangOptions().AltiVec)
     return Context.getLogicalOperationType();
 
-  QualType lType = lex->getType();
-  QualType rType = rex->getType();
+  QualType lType = lex.get()->getType();
+  QualType rType = rex.get()->getType();
 
   // For non-floating point types, check for self-comparisons of the form
   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
   // often indicate logic errors in the program.
   if (!lType->hasFloatingRepresentation()) {
-    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
-      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
+    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
+      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
         if (DRL->getDecl() == DRR->getDecl())
           DiagRuntimeBehavior(Loc, 0,
                               PDiag(diag::warn_comparison_always)
@@ -7174,7 +7277,7 @@ QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
   // Check for comparisons of floating point operands using != and ==.
   if (!isRelational && lType->hasFloatingRepresentation()) {
     assert (rType->hasFloatingRepresentation());
-    CheckFloatComparison(Loc,lex,rex);
+    CheckFloatComparison(Loc, lex.get(), rex.get());
   }
 
   // Return the type for the comparison, which is the same as vector type for
@@ -7196,41 +7299,46 @@ QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
 }
 
 inline QualType Sema::CheckBitwiseOperands(
-  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
-  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
-    if (lex->getType()->hasIntegerRepresentation() &&
-        rex->getType()->hasIntegerRepresentation())
+  ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
+  if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
+    if (lex.get()->getType()->hasIntegerRepresentation() &&
+        rex.get()->getType()->hasIntegerRepresentation())
       return CheckVectorOperands(Loc, lex, rex);
     
     return InvalidOperands(Loc, lex, rex);
   }
 
-  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
+  ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
+  QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
+  if (lexResult.isInvalid() || rexResult.isInvalid())
+    return QualType();
+  lex = lexResult.take();
+  rex = rexResult.take();
 
-  if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
-      rex->getType()->isIntegralOrUnscopedEnumerationType())
+  if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
+      rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
     return compType;
   return InvalidOperands(Loc, lex, rex);
 }
 
 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
-  Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
+  ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
   
   // Diagnose cases where the user write a logical and/or but probably meant a
   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
   // is a constant.
-  if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
-      rex->getType()->isIntegerType() && !rex->isValueDependent() &&
+  if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
+      rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
       // Don't warn in macros.
       !Loc.isMacroID()) {
     // If the RHS can be constant folded, and if it constant folds to something
     // that isn't 0 or 1 (which indicate a potential logical operation that
     // happened to fold to true/false) then warn.
     Expr::EvalResult Result;
-    if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
+    if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
         Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
       Diag(Loc, diag::warn_logical_instead_of_bitwise)
-       << rex->getSourceRange()
+       << rex.get()->getSourceRange()
         << (Opc == BO_LAnd ? "&&" : "||")
         << (Opc == BO_LAnd ? "&" : "|");
     }
@@ -7238,9 +7346,14 @@ inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
   
   if (!Context.getLangOptions().CPlusPlus) {
     UsualUnaryConversions(lex);
+    if (lex.isInvalid())
+      return QualType();
+
     UsualUnaryConversions(rex);
+    if (rex.isInvalid())
+      return QualType();
 
-    if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
+    if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
       return InvalidOperands(Loc, lex, rex);
 
     return Context.IntTy;
@@ -7353,7 +7466,7 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
 
 
 // C99 6.5.16.1
-QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
+QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
                                        SourceLocation Loc,
                                        QualType CompoundType) {
   // Verify that LHS is a modifiable lvalue, and emit error if not.
@@ -7361,14 +7474,21 @@ QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
     return QualType();
 
   QualType LHSType = LHS->getType();
-  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
+  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
   AssignConvertType ConvTy;
   if (CompoundType.isNull()) {
     QualType LHSTy(LHSType);
     // Simple assignment "x = y".
-    if (LHS->getObjectKind() == OK_ObjCProperty)
-      ConvertPropertyForLValue(LHS, RHS, LHSTy);
+    if (LHS->getObjectKind() == OK_ObjCProperty) {
+      ExprResult LHSResult = Owned(LHS);
+      ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
+      if (LHSResult.isInvalid())
+        return QualType();
+      LHS = LHSResult.take();
+    }
     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
+    if (RHS.isInvalid())
+      return QualType();
     // Special case of NSObject attributes on c-style pointer types.
     if (ConvTy == IncompatiblePointer &&
         ((Context.isObjCNSObjectType(LHSType) &&
@@ -7386,7 +7506,7 @@ QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
     // If the RHS is a unary plus or minus, check to see if they = and + are
     // right next to each other.  If so, the user may have typo'd "x =+ 4"
     // instead of "x += 4".
-    Expr *RHSCheck = RHS;
+    Expr *RHSCheck = RHS.get();
     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
       RHSCheck = ICE->getSubExpr();
     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
@@ -7410,7 +7530,7 @@ QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
   }
 
   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
-                               RHS, AA_Assigning))
+                               RHS.get(), AA_Assigning))
     return QualType();
 
   
@@ -7447,19 +7567,15 @@ QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
 }
 
 // C99 6.5.17
-static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
+static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
                                    SourceLocation Loc) {
-  S.DiagnoseUnusedExprResult(LHS);
+  S.DiagnoseUnusedExprResult(LHS.get());
 
-  ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
-  if (LHSResult.isInvalid()) 
+  LHS = S.CheckPlaceholderExpr(LHS.take(), Loc);
+  RHS = S.CheckPlaceholderExpr(RHS.take(), Loc);
+  if (LHS.isInvalid() || RHS.isInvalid())
     return QualType();
 
-  ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
-  if (RHSResult.isInvalid())
-    return QualType();
-  RHS = RHSResult.take();
-
   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
   // operands, but not unary promotions.
   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
@@ -7467,14 +7583,18 @@ static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
   // So we treat the LHS as a ignored value, and in C++ we allow the
   // containing site to determine what should be done with the RHS.
   S.IgnoredValueConversions(LHS);
+  if (LHS.isInvalid())
+    return QualType();
 
   if (!S.getLangOptions().CPlusPlus) {
     S.DefaultFunctionArrayLvalueConversion(RHS);
-    if (!RHS->getType()->isVoidType())
-      S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
+    if (RHS.isInvalid())
+      return QualType();
+    if (!RHS.get()->getType()->isVoidType())
+      S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
   }
 
-  return RHS->getType();
+  return RHS.get()->getType();
 }
 
 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
@@ -7564,10 +7684,10 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
   }
 }
 
-void Sema::ConvertPropertyForRValue(Expr *&E) {
-  assert(E->getValueKind() == VK_LValue &&
-         E->getObjectKind() == OK_ObjCProperty);
-  const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
+void Sema::ConvertPropertyForRValue(ExprResult &E) {
+  assert(E.get()->getValueKind() == VK_LValue &&
+         E.get()->getObjectKind() == OK_ObjCProperty);
+  const ObjCPropertyRefExpr *PRE = E.get()->getObjCProperty();
 
   ExprValueKind VK = VK_RValue;
   if (PRE->isImplicitProperty()) {
@@ -7582,47 +7702,45 @@ void Sema::ConvertPropertyForRValue(Expr *&E) {
     }
   }
 
-  E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
-                               E, 0, VK);
+  E = ImplicitCastExpr::Create(Context, E.get()->getType(), CK_GetObjCProperty,
+                               E.take(), 0, VK);
   
-  ExprResult Result = MaybeBindToTemporary(E);
+  ExprResult Result = MaybeBindToTemporary(E.take());
   if (!Result.isInvalid())
     E = Result.take();
 }
 
-void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
-  assert(LHS->getValueKind() == VK_LValue &&
-         LHS->getObjectKind() == OK_ObjCProperty);
-  const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
+void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
+  assert(LHS.get()->getValueKind() == VK_LValue &&
+         LHS.get()->getObjectKind() == OK_ObjCProperty);
+  const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
 
-  if (PRE->isImplicitProperty()) {
+  if (PropRef->isImplicitProperty()) {
     // If using property-dot syntax notation for assignment, and there is a
     // setter, RHS expression is being passed to the setter argument. So,
     // type conversion (and comparison) is RHS to setter's argument type.
-    if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
+    if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
       ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
       LHSTy = (*P)->getType();
 
     // Otherwise, if the getter returns an l-value, just call that.
     } else {
-      QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
+      QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
       ExprValueKind VK = Expr::getValueKindForType(Result);
       if (VK == VK_LValue) {
-        LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
-                                       CK_GetObjCProperty, LHS, 0, VK);
+        LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
+                                        CK_GetObjCProperty, LHS.take(), 0, VK);
         return;
       }
     }
   }
 
   if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
-    InitializedEntity Entity = 
-    InitializedEntity::InitializeParameter(Context, LHSTy);
-    Expr *Arg = RHS;
-    ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
-                                                Owned(Arg));
+    InitializedEntity Entity =
+      InitializedEntity::InitializeParameter(Context, LHSTy);
+    ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
     if (!ArgE.isInvalid())
-      RHS = ArgE.takeAs<Expr>(); 
+      RHS = ArgE;
   }
 }
   
@@ -7835,7 +7953,11 @@ static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
   if (Op->isTypeDependent())
     return S.Context.DependentTy;
 
-  S.UsualUnaryConversions(Op);
+  ExprResult ConvResult = S.Owned(Op);
+  S.UsualUnaryConversions(ConvResult);
+  if (ConvResult.isInvalid())
+    return QualType();
+  Op = ConvResult.take();
   QualType OpTy = Op->getType();
   QualType Result;
   
@@ -7972,7 +8094,8 @@ static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
 /// built-in operations; ActOnBinOp handles overloaded operators.
 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
                                     BinaryOperatorKind Opc,
-                                    Expr *lhs, Expr *rhs) {
+                                    Expr *lhsExpr, Expr *rhsExpr) {
+  ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
   QualType ResultTy;     // Result type of the binary operator.
   // The following two variables are used for compound assignment operators
   QualType CompLHSTy;    // Type of LHS after promotions for computation
@@ -7982,14 +8105,14 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
 
   switch (Opc) {
   case BO_Assign:
-    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
+    ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
     if (getLangOptions().CPlusPlus &&
-        lhs->getObjectKind() != OK_ObjCProperty) {
-      VK = lhs->getValueKind();
-      OK = lhs->getObjectKind();
+        lhs.get()->getObjectKind() != OK_ObjCProperty) {
+      VK = lhs.get()->getValueKind();
+      OK = lhs.get()->getObjectKind();
     }
     if (!ResultTy.isNull())
-      DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
+      DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
     break;
   case BO_PtrMemD:
   case BO_PtrMemI:
@@ -8038,60 +8161,59 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
     CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
                                                Opc == BO_DivAssign);
     CompLHSTy = CompResultTy;
-    if (!CompResultTy.isNull())
-      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
+    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
+      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
     break;
   case BO_RemAssign:
     CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
     CompLHSTy = CompResultTy;
-    if (!CompResultTy.isNull())
-      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
+    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
+      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
     break;
   case BO_AddAssign:
     CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
-    if (!CompResultTy.isNull())
-      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
+    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
+      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
     break;
   case BO_SubAssign:
     CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
-    if (!CompResultTy.isNull())
-      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
+    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
+      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
     break;
   case BO_ShlAssign:
   case BO_ShrAssign:
     CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
     CompLHSTy = CompResultTy;
-    if (!CompResultTy.isNull())
-      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
+    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
+      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
     break;
   case BO_AndAssign:
   case BO_XorAssign:
   case BO_OrAssign:
     CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
     CompLHSTy = CompResultTy;
-    if (!CompResultTy.isNull())
-      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
+    if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
+      ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
     break;
   case BO_Comma:
     ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
-    if (getLangOptions().CPlusPlus) {
-      VK = rhs->getValueKind();
-      OK = rhs->getObjectKind();
+    if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
+      VK = rhs.get()->getValueKind();
+      OK = rhs.get()->getObjectKind();
     }
     break;
   }
-  if (ResultTy.isNull())
+  if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
     return ExprError();
   if (CompResultTy.isNull())
-    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
-                                              VK, OK, OpLoc));
-
-  if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
+    return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
+                                              ResultTy, VK, OK, OpLoc));
+  if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
     VK = VK_LValue;
-    OK = lhs->getObjectKind();
+    OK = lhs.get()->getObjectKind();
   }
-  return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
-                                                    VK, OK, CompLHSTy,
+  return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
+                                                    ResultTy, VK, OK, CompLHSTy,
                                                     CompResultTy, OpLoc));
 }
 
@@ -8318,7 +8440,8 @@ ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
 
 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
                                       UnaryOperatorKind Opc,
-                                      Expr *Input) {
+                                      Expr *InputExpr) {
+  ExprResult Input = Owned(InputExpr);
   ExprValueKind VK = VK_RValue;
   ExprObjectKind OK = OK_Ordinary;
   QualType resultType;
@@ -8327,23 +8450,26 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
   case UO_PreDec:
   case UO_PostInc:
   case UO_PostDec:
-    resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
+    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
                                                 Opc == UO_PreInc ||
                                                 Opc == UO_PostInc,
                                                 Opc == UO_PreInc ||
                                                 Opc == UO_PreDec);
     break;
   case UO_AddrOf:
-    resultType = CheckAddressOfOperand(*this, Input, OpLoc);
+    resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
     break;
-  case UO_Deref:
+  case UO_Deref: {
     DefaultFunctionArrayLvalueConversion(Input);
-    resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
+    if (Input.isInvalid()) return ExprError();
+    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
+    }
     break;
   case UO_Plus:
   case UO_Minus:
     UsualUnaryConversions(Input);
-    resultType = Input->getType();
+    if (Input.isInvalid()) return ExprError();
+    resultType = Input.get()->getType();
     if (resultType->isDependentType())
       break;
     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
@@ -8357,49 +8483,53 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
              resultType->isPointerType())
       break;
     else if (resultType->isPlaceholderType()) {
-      ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
-      if (PR.isInvalid()) return ExprError();
-      return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
+      Input = CheckPlaceholderExpr(Input.take(), OpLoc);
+      if (Input.isInvalid()) return ExprError();
+      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
     }
 
     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
-      << resultType << Input->getSourceRange());
+      << resultType << Input.get()->getSourceRange());
+
   case UO_Not: // bitwise complement
     UsualUnaryConversions(Input);
-    resultType = Input->getType();
+    if (Input.isInvalid()) return ExprError();
+    resultType = Input.get()->getType();
     if (resultType->isDependentType())
       break;
     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
     if (resultType->isComplexType() || resultType->isComplexIntegerType())
       // C99 does not support '~' for complex conjugation.
       Diag(OpLoc, diag::ext_integer_complement_complex)
-        << resultType << Input->getSourceRange();
+        << resultType << Input.get()->getSourceRange();
     else if (resultType->hasIntegerRepresentation())
       break;
     else if (resultType->isPlaceholderType()) {
-      ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
-      if (PR.isInvalid()) return ExprError();
-      return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
+      Input = CheckPlaceholderExpr(Input.take(), OpLoc);
+      if (Input.isInvalid()) return ExprError();
+      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
     } else {
       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
-        << resultType << Input->getSourceRange());
+        << resultType << Input.get()->getSourceRange());
     }
     break;
+
   case UO_LNot: // logical negation
     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
     DefaultFunctionArrayLvalueConversion(Input);
-    resultType = Input->getType();
+    if (Input.isInvalid()) return ExprError();
+    resultType = Input.get()->getType();
     if (resultType->isDependentType())
       break;
     if (resultType->isScalarType()) { // C99 6.5.3.3p1
       // ok, fallthrough
     } else if (resultType->isPlaceholderType()) {
-      ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
-      if (PR.isInvalid()) return ExprError();
-      return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
+      Input = CheckPlaceholderExpr(Input.take(), OpLoc);
+      if (Input.isInvalid()) return ExprError();
+      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
     } else {
       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
-        << resultType << Input->getSourceRange());
+        << resultType << Input.get()->getSourceRange());
     }
     
     // LNot always has type int. C99 6.5.3.3p5.
@@ -8410,20 +8540,21 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
   case UO_Imag:
     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
     // _Real and _Imag map ordinary l-values into ordinary l-values.
-    if (Input->getValueKind() != VK_RValue &&
-        Input->getObjectKind() == OK_Ordinary)
-      VK = Input->getValueKind();
+    if (Input.isInvalid()) return ExprError();
+    if (Input.get()->getValueKind() != VK_RValue &&
+        Input.get()->getObjectKind() == OK_Ordinary)
+      VK = Input.get()->getValueKind();
     break;
   case UO_Extension:
-    resultType = Input->getType();
-    VK = Input->getValueKind();
-    OK = Input->getObjectKind();
+    resultType = Input.get()->getType();
+    VK = Input.get()->getValueKind();
+    OK = Input.get()->getObjectKind();
     break;
   }
-  if (resultType.isNull())
+  if (resultType.isNull() || Input.isInvalid())
     return ExprError();
 
-  return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
+  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
                                            VK, OK, OpLoc));
 }
 
@@ -8490,26 +8621,29 @@ Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
       LastLabelStmt = Label;
       LastStmt = Label->getSubStmt();
     }
-    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
+    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
       // Do function/array conversion on the last expression, but not
       // lvalue-to-rvalue.  However, initialize an unqualified type.
+      ExprResult LastExpr = Owned(LastE);
       DefaultFunctionArrayConversion(LastExpr);
-      Ty = LastExpr->getType().getUnqualifiedType();
+      if (LastExpr.isInvalid())
+        return ExprError();
+      Ty = LastExpr.get()->getType().getUnqualifiedType();
 
-      if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
-        ExprResult Res = PerformCopyInitialization(
+      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
+        LastExpr = PerformCopyInitialization(
                             InitializedEntity::InitializeResult(LPLoc, 
                                                                 Ty,
                                                                 false),
-                                                   SourceLocation(),
-                                                   Owned(LastExpr));
-        if (Res.isInvalid())
+                                             SourceLocation(),
+                                             LastExpr);
+        if (LastExpr.isInvalid())
           return ExprError();
-        if ((LastExpr = Res.takeAs<Expr>())) {
+        if (LastExpr.get() != 0) {
           if (!LastLabelStmt)
-            Compound->setLastStmt(LastExpr);
+            Compound->setLastStmt(LastExpr.take());
           else
-            LastLabelStmt->setSubStmt(LastExpr);
+            LastLabelStmt->setSubStmt(LastExpr.take());
           StmtExprMayBindToTemp = true;
         }
       }
@@ -8986,7 +9120,11 @@ ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
     // a pointer for va_arg.
     VaListType = Context.getArrayDecayedType(VaListType);
     // Make sure the input expression also decays appropriately.
-    UsualUnaryConversions(E);
+    ExprResult Result = Owned(E);
+    UsualUnaryConversions(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    E = Result.take();
   } else {
     // Otherwise, the va_list argument must be an l-value because
     // it is modified by va_arg.
@@ -9668,39 +9806,42 @@ void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
     }
 }
 
-bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
-  DiagnoseAssignmentAsCondition(E);
-  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
+bool Sema::CheckBooleanCondition(ExprResult &E, SourceLocation Loc) {
+  DiagnoseAssignmentAsCondition(E.get());
+  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E.get()))
     DiagnoseEqualityWithExtraParens(parenE);
 
-  if (!E->isTypeDependent()) {
-    if (E->isBoundMemberFunction(Context))
-      return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
-        << E->getSourceRange();
+  if (!E.get()->isTypeDependent()) {
+    if (E.get()->isBoundMemberFunction(Context))
+      return Diag(E.get()->getLocStart(), diag::err_invalid_use_of_bound_member_func)
+        << E.get()->getSourceRange();
 
     if (getLangOptions().CPlusPlus)
       return CheckCXXBooleanCondition(E); // C++ 6.4p4
 
     DefaultFunctionArrayLvalueConversion(E);
+    if (E.isInvalid())
+      return true;
 
-    QualType T = E->getType();
+    QualType T = E.get()->getType();
     if (!T->isScalarType()) // C99 6.8.4.1p1
       return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
-               << T << E->getSourceRange();
+               << T << E.get()->getSourceRange();
   }
 
   return false;
 }
 
 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
-                                       Expr *Sub) {
-  if (!Sub)
+                                       Expr *SubE) {
+  if (!SubE)
     return ExprError();
   
+  ExprResult Sub = Owned(SubE);
   if (CheckBooleanCondition(Sub, Loc))
     return ExprError();
   
-  return Owned(Sub);
+  return Sub;
 }
 
 /// Check for operands with placeholder types and complain if found.
diff --git a/lib/Sema/SemaExprCXX.cpp b/lib/Sema/SemaExprCXX.cpp
index 7d029cb..5a7ea51 100644
--- a/lib/Sema/SemaExprCXX.cpp
+++ b/lib/Sema/SemaExprCXX.cpp
@@ -467,34 +467,39 @@ Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
 
 /// ActOnCXXThrow - Parse throw expressions.
 ExprResult
-Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
+Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *ExE) {
+  ExprResult Ex = Owned(ExE);
   // Don't report an error if 'throw' is used in system headers.
   if (!getLangOptions().CXXExceptions &&
       !getSourceManager().isInSystemHeader(OpLoc))
     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
 
-  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
+  if (Ex.get() && !Ex.get()->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
     return ExprError();
-  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
+  if (Ex.isInvalid())
+    return ExprError();
+  return Owned(new (Context) CXXThrowExpr(Ex.take(), Context.VoidTy, OpLoc));
 }
 
 /// CheckCXXThrowOperand - Validate the operand of a throw.
-bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
+bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, ExprResult &E) {
   // C++ [except.throw]p3:
   //   A throw-expression initializes a temporary object, called the exception
   //   object, the type of which is determined by removing any top-level
   //   cv-qualifiers from the static type of the operand of throw and adjusting
   //   the type from "array of T" or "function returning T" to "pointer to T"
   //   or "pointer to function returning T", [...]
-  if (E->getType().hasQualifiers())
-    ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
-                      CastCategory(E));
+  if (E.get()->getType().hasQualifiers())
+    ImpCastExprToType(E, E.get()->getType().getUnqualifiedType(), CK_NoOp,
+                      CastCategory(E.get()));
 
   DefaultFunctionArrayConversion(E);
+  if (E.isInvalid())
+    return true;
 
   //   If the type of the exception would be an incomplete type or a pointer
   //   to an incomplete type other than (cv) void the program is ill-formed.
-  QualType Ty = E->getType();
+  QualType Ty = E.get()->getType();
   bool isPointer = false;
   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
     Ty = Ptr->getPointeeType();
@@ -504,28 +509,28 @@ bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
     if (RequireCompleteType(ThrowLoc, Ty,
                             PDiag(isPointer ? diag::err_throw_incomplete_ptr
                                             : diag::err_throw_incomplete)
-                              << E->getSourceRange()))
+                              << E.get()->getSourceRange()))
       return true;
 
-    if (RequireNonAbstractType(ThrowLoc, E->getType(),
+    if (RequireNonAbstractType(ThrowLoc, E.get()->getType(),
                                PDiag(diag::err_throw_abstract_type)
-                                 << E->getSourceRange()))
+                                 << E.get()->getSourceRange()))
       return true;
   }
 
   // Initialize the exception result.  This implicitly weeds out
   // abstract types or types with inaccessible copy constructors.
-  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
+  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E.get(), false);
 
   // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
   InitializedEntity Entity =
-      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
+      InitializedEntity::InitializeException(ThrowLoc, E.get()->getType(),
                                              /*NRVO=*/false);
   ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
-                                                   QualType(), E);
+                                                   QualType(), E.take());
   if (Res.isInvalid())
     return true;
-  E = Res.takeAs<Expr>();
+  E = Res;
 
   // If the exception has class type, we need additional handling.
   const RecordType *RecordTy = Ty->getAs<RecordType>();
@@ -550,8 +555,8 @@ bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
   if (!Destructor)
     return false;
 
-  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
-  CheckDestructorAccess(E->getExprLoc(), Destructor,
+  MarkDeclarationReferenced(E.get()->getExprLoc(), Destructor);
+  CheckDestructorAccess(E.get()->getExprLoc(), Destructor,
                         PDiag(diag::err_access_dtor_exception) << Ty);
   return false;
 }
@@ -658,10 +663,12 @@ Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
     CastKind Kind = CK_Invalid;
     ExprValueKind VK = VK_RValue;
     CXXCastPath BasePath;
-    if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
+    ExprResult CastExpr = Owned(Exprs[0]);
+    if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, CastExpr,
                        Kind, VK, BasePath,
-                       /*FunctionalStyle=*/true))
+                       /*FunctionalStyle=*/true) || CastExpr.isInvalid())
       return ExprError();
+    Exprs[0] = CastExpr.take();
 
     exprs.release();
 
@@ -1600,19 +1607,20 @@ bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
 /// @code delete [] ptr; @endcode
 ExprResult
 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
-                     bool ArrayForm, Expr *Ex) {
+                     bool ArrayForm, Expr *ExE) {
   // C++ [expr.delete]p1:
   //   The operand shall have a pointer type, or a class type having a single
   //   conversion function to a pointer type. The result has type void.
   //
   // DR599 amends "pointer type" to "pointer to object type" in both cases.
 
+  ExprResult Ex = Owned(ExE);
   FunctionDecl *OperatorDelete = 0;
   bool ArrayFormAsWritten = ArrayForm;
   bool UsualArrayDeleteWantsSize = false;
 
-  if (!Ex->isTypeDependent()) {
-    QualType Type = Ex->getType();
+  if (!Ex.get()->isTypeDependent()) {
+    QualType Type = Ex.get()->getType();
 
     if (const RecordType *Record = Type->getAs<RecordType>()) {
       if (RequireCompleteType(StartLoc, Type,
@@ -1647,12 +1655,14 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
         if (!PerformImplicitConversion(Ex,
                             ObjectPtrConversions.front()->getConversionType(),
                                       AA_Converting)) {
-          Type = Ex->getType();
+          if (Ex.isInvalid())
+            return ExprError();
+          Type = Ex.get()->getType();
         }
       }
       else if (ObjectPtrConversions.size() > 1) {
         Diag(StartLoc, diag::err_ambiguous_delete_operand)
-              << Type << Ex->getSourceRange();
+              << Type << Ex.get()->getSourceRange();
         for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
           NoteOverloadCandidate(ObjectPtrConversions[i]);
         return ExprError();
@@ -1661,7 +1671,7 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
 
     if (!Type->isPointerType())
       return ExprError(Diag(StartLoc, diag::err_delete_operand)
-        << Type << Ex->getSourceRange());
+        << Type << Ex.get()->getSourceRange());
 
     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
     if (Pointee->isVoidType() && !isSFINAEContext()) {
@@ -1669,14 +1679,14 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
       // effectively bans deletion of "void*". However, most compilers support
       // this, so we treat it as a warning unless we're in a SFINAE context.
       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
-        << Type << Ex->getSourceRange();
+        << Type << Ex.get()->getSourceRange();
     } else if (Pointee->isFunctionType() || Pointee->isVoidType())
       return ExprError(Diag(StartLoc, diag::err_delete_operand)
-        << Type << Ex->getSourceRange());
+        << Type << Ex.get()->getSourceRange());
     else if (!Pointee->isDependentType() &&
              RequireCompleteType(StartLoc, Pointee,
                                  PDiag(diag::warn_delete_incomplete)
-                                   << Ex->getSourceRange()))
+                                   << Ex.get()->getSourceRange()))
       return ExprError();
 
     // C++ [expr.delete]p2:
@@ -1689,7 +1699,7 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
 
     if (Pointee->isArrayType() && !ArrayForm) {
       Diag(StartLoc, diag::warn_delete_array_type)
-          << Type << Ex->getSourceRange()
+          << Type << Ex.get()->getSourceRange()
           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
       ArrayForm = true;
     }
@@ -1732,8 +1742,9 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
       // Look for a global declaration.
       DeclareGlobalNewDelete();
       DeclContext *TUDecl = Context.getTranslationUnitDecl();
+      Expr *Arg = Ex.get();
       if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
-                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
+                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
                                  OperatorDelete))
         return ExprError();
     }
@@ -1744,7 +1755,7 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
     if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
       CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
       if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
-          CheckDestructorAccess(Ex->getExprLoc(), Dtor, 
+          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 
                       PDiag(diag::err_access_dtor) << PointeeElem);
       }
     }
@@ -1754,7 +1765,7 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
                                            ArrayFormAsWritten,
                                            UsualArrayDeleteWantsSize,
-                                           OperatorDelete, Ex, StartLoc));
+                                           OperatorDelete, Ex.take(), StartLoc));
 }
 
 /// \brief Check the use of the given variable as a C++ condition in an if,
@@ -1775,19 +1786,23 @@ ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
                           diag::err_invalid_use_of_array_type)
                      << ConditionVar->getSourceRange());
 
-  Expr *Condition = DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 
-                                        ConditionVar,
-                                        ConditionVar->getLocation(),
-                            ConditionVar->getType().getNonReferenceType(),
-                                        VK_LValue);
+  ExprResult Condition =
+    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 
+                              ConditionVar,
+                              ConditionVar->getLocation(),
+                              ConditionVar->getType().getNonReferenceType(),
+                              VK_LValue));
   if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
     return ExprError();
 
-  return Owned(Condition);
+  if (Condition.isInvalid())
+    return ExprError();
+
+  return move(Condition);
 }
 
 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
-bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
+bool Sema::CheckCXXBooleanCondition(ExprResult &CondExpr) {
   // C++ 6.4p4:
   // The value of a condition that is an initialized declaration in a statement
   // other than a switch statement is the value of the declared variable
@@ -1878,7 +1893,7 @@ static ExprResult BuildCXXCastArgument(Sema &S,
 /// expression. Action is the kind of conversion we're performing,
 /// used in the error message.
 bool
-Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
+Sema::PerformImplicitConversion(ExprResult &From, QualType ToType,
                                 const ImplicitConversionSequence &ICS,
                                 AssignmentAction Action, bool CStyle) {
   switch (ICS.getKind()) {
@@ -1921,25 +1936,25 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
 
       ExprResult CastArg
         = BuildCXXCastArgument(*this,
-                               From->getLocStart(),
+                               From.get()->getLocStart(),
                                ToType.getNonReferenceType(),
                                CastKind, cast<CXXMethodDecl>(FD),
                                ICS.UserDefined.FoundConversionFunction,
-                               From);
+                               From.get());
 
       if (CastArg.isInvalid())
         return true;
 
-      From = CastArg.takeAs<Expr>();
+      From = CastArg;
 
       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
                                        AA_Converting, CStyle);
   }
 
   case ImplicitConversionSequence::AmbiguousConversion:
-    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
+    ICS.DiagnoseAmbiguousConversion(*this, From.get()->getExprLoc(),
                           PDiag(diag::err_typecheck_ambiguous_condition)
-                            << From->getSourceRange());
+                            << From.get()->getSourceRange());
      return true;
 
   case ImplicitConversionSequence::EllipsisConversion:
@@ -1961,22 +1976,23 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
 /// expression. Flavor is the context in which we're performing this
 /// conversion, for use in error messages.
 bool
-Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
+Sema::PerformImplicitConversion(ExprResult &From, QualType ToType,
                                 const StandardConversionSequence& SCS,
                                 AssignmentAction Action, bool CStyle) {
   // Overall FIXME: we are recomputing too many types here and doing far too
   // much extra work. What this means is that we need to keep track of more
   // information that is computed when we try the implicit conversion initially,
   // so that we don't need to recompute anything here.
-  QualType FromType = From->getType();
+  QualType FromType = From.get()->getType();
 
   if (SCS.CopyConstructor) {
     // FIXME: When can ToType be a reference type?
     assert(!ToType->isReferenceType());
     if (SCS.Second == ICK_Derived_To_Base) {
+      Expr *Arg = From.get();
       ASTOwningVector<Expr*> ConstructorArgs(*this);
       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
-                                  MultiExprArg(*this, &From, 1),
+                                  MultiExprArg(*this, &Arg, 1),
                                   /*FIXME:ConstructLoc*/SourceLocation(),
                                   ConstructorArgs))
         return true;
@@ -1992,10 +2008,11 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
       From = FromResult.takeAs<Expr>();
       return false;
     }
+    Expr *Arg = From.get();
     ExprResult FromResult =
       BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
                             ToType, SCS.CopyConstructor,
-                            MultiExprArg(*this, &From, 1),
+                            MultiExprArg(*this, &Arg, 1),
                             /*ZeroInit*/ false,
                             CXXConstructExpr::CK_Complete,
                             SourceRange());
@@ -2003,23 +2020,23 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
     if (FromResult.isInvalid())
       return true;
 
-    From = FromResult.takeAs<Expr>();
+    From = FromResult;
     return false;
   }
 
   // Resolve overloaded function references.
   if (Context.hasSameType(FromType, Context.OverloadTy)) {
     DeclAccessPair Found;
-    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
+    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From.get(), ToType,
                                                           true, Found);
     if (!Fn)
       return true;
 
-    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
+    if (DiagnoseUseOfDecl(Fn, From.get()->getSourceRange().getBegin()))
       return true;
 
     From = FixOverloadedFunctionReference(From, Found, Fn);
-    FromType = From->getType();
+    FromType = From.get()->getType();
   }
 
   // Perform the first implicit conversion.
@@ -2030,17 +2047,17 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
 
   case ICK_Lvalue_To_Rvalue:
     // Should this get its own ICK?
-    if (From->getObjectKind() == OK_ObjCProperty) {
+    if (From.get()->getObjectKind() == OK_ObjCProperty) {
       ConvertPropertyForRValue(From);
-      if (!From->isGLValue()) break;
+      if (!From.get()->isGLValue()) break;
     }
 
     // Check for trivial buffer overflows.
-    CheckArrayAccess(From);
+    CheckArrayAccess(From.get());
 
     FromType = FromType.getUnqualifiedType();
     From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
-                                    From, 0, VK_RValue);
+                                    From.take(), 0, VK_RValue);
     break;
 
   case ICK_Array_To_Pointer:
@@ -2063,7 +2080,7 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
   case ICK_Identity:
     // If both sides are functions (or pointers/references to them), there could
     // be incompatible exception declarations.
-    if (CheckExceptionSpecCompatibility(From, ToType))
+    if (CheckExceptionSpecCompatibility(From.get(), ToType))
       return true;
     // Nothing else to do.
     break;
@@ -2071,7 +2088,7 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
   case ICK_NoReturn_Adjustment:
     // If both sides are functions (or pointers/references to them), there could
     // be incompatible exception declarations.
-    if (CheckExceptionSpecCompatibility(From, ToType))
+    if (CheckExceptionSpecCompatibility(From.get(), ToType))
       return true;
 
     ImpCastExprToType(From, ToType, CK_NoOp);
@@ -2089,7 +2106,7 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
 
   case ICK_Complex_Promotion:
   case ICK_Complex_Conversion: {
-    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
+    QualType FromEl = From.get()->getType()->getAs<ComplexType>()->getElementType();
     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
     CastKind CK;
     if (FromEl->isRealFloatingType()) {
@@ -2120,15 +2137,15 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
   case ICK_Pointer_Conversion: {
     if (SCS.IncompatibleObjC && Action != AA_Casting) {
       // Diagnose incompatible Objective-C conversions
-      Diag(From->getSourceRange().getBegin(),
+      Diag(From.get()->getSourceRange().getBegin(),
            diag::ext_typecheck_convert_incompatible_pointer)
-        << From->getType() << ToType << Action
-        << From->getSourceRange();
+        << From.get()->getType() << ToType << Action
+        << From.get()->getSourceRange();
     }
 
     CastKind Kind = CK_Invalid;
     CXXCastPath BasePath;
-    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
+    if (CheckPointerConversion(From.get(), ToType, Kind, BasePath, CStyle))
       return true;
     ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
     break;
@@ -2137,9 +2154,9 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
   case ICK_Pointer_Member: {
     CastKind Kind = CK_Invalid;
     CXXCastPath BasePath;
-    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
+    if (CheckMemberPointerConversion(From.get(), ToType, Kind, BasePath, CStyle))
       return true;
-    if (CheckExceptionSpecCompatibility(From, ToType))
+    if (CheckExceptionSpecCompatibility(From.get(), ToType))
       return true;
     ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
     break;
@@ -2162,16 +2179,16 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
 
   case ICK_Derived_To_Base: {
     CXXCastPath BasePath;
-    if (CheckDerivedToBaseConversion(From->getType(),
+    if (CheckDerivedToBaseConversion(From.get()->getType(),
                                      ToType.getNonReferenceType(),
-                                     From->getLocStart(),
-                                     From->getSourceRange(),
+                                     From.get()->getLocStart(),
+                                     From.get()->getSourceRange(),
                                      &BasePath,
                                      CStyle))
       return true;
 
     ImpCastExprToType(From, ToType.getNonReferenceType(),
-                      CK_DerivedToBase, CastCategory(From),
+                      CK_DerivedToBase, CastCategory(From.get()),
                       &BasePath);
     break;
   }
@@ -2191,13 +2208,13 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
       bool isFloatingComplex = ElType->isRealFloatingType();
 
       // x -> y
-      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
+      if (Context.hasSameUnqualifiedType(ElType, From.get()->getType())) {
         // do nothing
-      } else if (From->getType()->isRealFloatingType()) {
+      } else if (From.get()->getType()->isRealFloatingType()) {
         ImpCastExprToType(From, ElType,
                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
       } else {
-        assert(From->getType()->isIntegerType());
+        assert(From.get()->getType()->isIntegerType());
         ImpCastExprToType(From, ElType,
                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
       }
@@ -2208,7 +2225,7 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
 
     // Case 2.  _Complex x -> y
     } else {
-      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
+      const ComplexType *FromComplex = From.get()->getType()->getAs<ComplexType>();
       assert(FromComplex);
 
       QualType ElType = FromComplex->getElementType();
@@ -2256,12 +2273,12 @@ Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
     // The qualification keeps the category of the inner expression, unless the
     // target type isn't a reference.
     ExprValueKind VK = ToType->isReferenceType() ?
-                                  CastCategory(From) : VK_RValue;
+                                  CastCategory(From.get()) : VK_RValue;
     ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
                       CK_NoOp, VK);
 
     if (SCS.DeprecatedStringLiteralToCharPtr)
-      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
+      Diag(From.get()->getLocStart(), diag::warn_deprecated_string_literal_conversion)
         << ToType.getNonReferenceType();
 
     break;
@@ -2674,7 +2691,7 @@ ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
                                                  ResultType));
 }
 
-QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
+QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
                                             ExprValueKind &VK,
                                             SourceLocation Loc,
                                             bool isIndirect) {
@@ -2683,11 +2700,11 @@ QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
   //   The binary operator .* [p3: ->*] binds its second operand, which shall
   //   be of type "pointer to member of T" (where T is a completely-defined
   //   class type) [...]
-  QualType RType = rex->getType();
+  QualType RType = rex.get()->getType();
   const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
   if (!MemPtr) {
     Diag(Loc, diag::err_bad_memptr_rhs)
-      << OpSpelling << RType << rex->getSourceRange();
+      << OpSpelling << RType << rex.get()->getSourceRange();
     return QualType();
   }
 
@@ -2703,7 +2720,7 @@ QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
   //   [...] to its first operand, which shall be of class T or of a class of
   //   which T is an unambiguous and accessible base class. [p3: a pointer to
   //   such a class]
-  QualType LType = lex->getType();
+  QualType LType = lex.get()->getType();
   if (isIndirect) {
     if (const PointerType *Ptr = LType->getAs<PointerType>())
       LType = Ptr->getPointeeType();
@@ -2728,20 +2745,20 @@ QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
     if (!IsDerivedFrom(LType, Class, Paths) ||
         Paths.isAmbiguous(Context.getCanonicalType(Class))) {
       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
-        << (int)isIndirect << lex->getType();
+        << (int)isIndirect << lex.get()->getType();
       return QualType();
     }
     // Cast LHS to type of use.
     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
     ExprValueKind VK =
-        isIndirect ? VK_RValue : CastCategory(lex);
+        isIndirect ? VK_RValue : CastCategory(lex.get());
 
     CXXCastPath BasePath;
     BuildBasePathArray(Paths, BasePath);
     ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
   }
 
-  if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
+  if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
     // Diagnose use of pointer-to-member type which when used as
     // the functional cast in a pointer-to-member expression.
     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
@@ -2776,15 +2793,15 @@ QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
       break;
 
     case RQ_LValue:
-      if (!isIndirect && !lex->Classify(Context).isLValue())
+      if (!isIndirect && !lex.get()->Classify(Context).isLValue())
         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
-          << RType << 1 << lex->getSourceRange();
+          << RType << 1 << lex.get()->getSourceRange();
       break;
 
     case RQ_RValue:
-      if (isIndirect || !lex->Classify(Context).isRValue())
+      if (isIndirect || !lex.get()->Classify(Context).isRValue())
         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
-          << RType << 0 << lex->getSourceRange();
+          << RType << 0 << lex.get()->getSourceRange();
       break;
     }
   }
@@ -2801,7 +2818,7 @@ QualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
   else if (isIndirect)
     VK = VK_LValue;
   else
-    VK = lex->getValueKind();
+    VK = lex.get()->getValueKind();
 
   return Result;
 }
@@ -2902,9 +2919,9 @@ static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
 /// This is part of the parameter validation for the ? operator. If either
 /// value operand is a class type, overload resolution is used to find a
 /// conversion to a common type.
-static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
+static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
                                     SourceLocation QuestionLoc) {
-  Expr *Args[2] = { LHS, RHS };
+  Expr *Args[2] = { LHS.get(), RHS.get() };
   OverloadCandidateSet CandidateSet(QuestionLoc);
   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
                                     CandidateSet);
@@ -2927,18 +2944,18 @@ static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
       // Emit a better diagnostic if one of the expressions is a null pointer
       // constant and the other is a pointer type. In this case, the user most
       // likely forgot to take the address of the other expression.
-      if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
+      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
         return true;
 
       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
-        << LHS->getType() << RHS->getType()
-        << LHS->getSourceRange() << RHS->getSourceRange();
+        << LHS.get()->getType() << RHS.get()->getType()
+        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       return true;
 
     case OR_Ambiguous:
       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
-        << LHS->getType() << RHS->getType()
-        << LHS->getSourceRange() << RHS->getSourceRange();
+        << LHS.get()->getType() << RHS.get()->getType()
+        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       // FIXME: Print the possible common types by printing the return types of
       // the viable candidates.
       break;
@@ -2952,16 +2969,17 @@ static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
 
 /// \brief Perform an "extended" implicit conversion as returned by
 /// TryClassUnification.
-static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
+static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
-  InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
+  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
                                                            SourceLocation());
-  InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
-  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
+  Expr *Arg = E.take();
+  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
+  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
   if (Result.isInvalid())
     return true;
 
-  E = Result.takeAs<Expr>();
+  E = Result;
   return false;
 }
 
@@ -2969,7 +2987,7 @@ static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
 ///
 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
 /// extension. In this case, LHS == Cond. (But they're not aliases.)
-QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
+QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
                                            ExprValueKind &VK, ExprObjectKind &OK,
                                            SourceLocation QuestionLoc) {
   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
@@ -2977,7 +2995,7 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
 
   // C++0x 5.16p1
   //   The first expression is contextually converted to bool.
-  if (!Cond->isTypeDependent()) {
+  if (!Cond.get()->isTypeDependent()) {
     if (CheckCXXBooleanCondition(Cond))
       return QualType();
   }
@@ -2987,13 +3005,13 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   OK = OK_Ordinary;
 
   // Either of the arguments dependent?
-  if (LHS->isTypeDependent() || RHS->isTypeDependent())
+  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
     return Context.DependentTy;
 
   // C++0x 5.16p2
   //   If either the second or the third operand has type (cv) void, ...
-  QualType LTy = LHS->getType();
-  QualType RTy = RHS->getType();
+  QualType LTy = LHS.get()->getType();
+  QualType RTy = RHS.get()->getType();
   bool LVoid = LTy->isVoidType();
   bool RVoid = RTy->isVoidType();
   if (LVoid || RVoid) {
@@ -3001,14 +3019,16 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     //   operands ...
     DefaultFunctionArrayLvalueConversion(LHS);
     DefaultFunctionArrayLvalueConversion(RHS);
-    LTy = LHS->getType();
-    RTy = RHS->getType();
+    if (LHS.isInvalid() || RHS.isInvalid())
+      return QualType();
+    LTy = LHS.get()->getType();
+    RTy = RHS.get()->getType();
 
     //   ... and one of the following shall hold:
     //   -- The second or the third operand (but not both) is a throw-
     //      expression; the result is of the type of the other and is an rvalue.
-    bool LThrow = isa<CXXThrowExpr>(LHS);
-    bool RThrow = isa<CXXThrowExpr>(RHS);
+    bool LThrow = isa<CXXThrowExpr>(LHS.get());
+    bool RThrow = isa<CXXThrowExpr>(RHS.get());
     if (LThrow && !RThrow)
       return RTy;
     if (RThrow && !LThrow)
@@ -3022,7 +3042,7 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     // Neither holds, error.
     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
-      << LHS->getSourceRange() << RHS->getSourceRange();
+      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
     return QualType();
   }
 
@@ -3038,15 +3058,15 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     // These return true if a single direction is already ambiguous.
     QualType L2RType, R2LType;
     bool HaveL2R, HaveR2L;
-    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
+    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
       return QualType();
-    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
+    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
       return QualType();
 
     //   If both can be converted, [...] the program is ill-formed.
     if (HaveL2R && HaveR2L) {
       Diag(QuestionLoc, diag::err_conditional_ambiguous)
-        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
+        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
       return QualType();
     }
 
@@ -3054,13 +3074,13 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     //   the chosen operand and the converted operands are used in place of the
     //   original operands for the remainder of this section.
     if (HaveL2R) {
-      if (ConvertForConditional(*this, LHS, L2RType))
+      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
         return QualType();
-      LTy = LHS->getType();
+      LTy = LHS.get()->getType();
     } else if (HaveR2L) {
-      if (ConvertForConditional(*this, RHS, R2LType))
+      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
         return QualType();
-      RTy = RHS->getType();
+      RTy = RHS.get()->getType();
     }
   }
 
@@ -3073,13 +3093,13 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   // l-values.
   bool Same = Context.hasSameType(LTy, RTy);
   if (Same &&
-      LHS->isGLValue() &&
-      LHS->getValueKind() == RHS->getValueKind() &&
-      LHS->isOrdinaryOrBitFieldObject() &&
-      RHS->isOrdinaryOrBitFieldObject()) {
-    VK = LHS->getValueKind();
-    if (LHS->getObjectKind() == OK_BitField ||
-        RHS->getObjectKind() == OK_BitField)
+      LHS.get()->isGLValue() &&
+      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
+      LHS.get()->isOrdinaryOrBitFieldObject() &&
+      RHS.get()->isOrdinaryOrBitFieldObject()) {
+    VK = LHS.get()->getValueKind();
+    if (LHS.get()->getObjectKind() == OK_BitField ||
+        RHS.get()->getObjectKind() == OK_BitField)
       OK = OK_BitField;
     return LTy;
   }
@@ -3100,8 +3120,10 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   //   conversions are performed on the second and third operands.
   DefaultFunctionArrayLvalueConversion(LHS);
   DefaultFunctionArrayLvalueConversion(RHS);
-  LTy = LHS->getType();
-  RTy = RHS->getType();
+  if (LHS.isInvalid() || RHS.isInvalid())
+    return QualType();
+  LTy = LHS.get()->getType();
+  RTy = RHS.get()->getType();
 
   //   After those conversions, one of the following shall hold:
   //   -- The second and third operands have the same type; the result
@@ -3115,18 +3137,18 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
       ExprResult LHSCopy = PerformCopyInitialization(Entity,
                                                      SourceLocation(),
-                                                     Owned(LHS));
+                                                     LHS);
       if (LHSCopy.isInvalid())
         return QualType();
 
       ExprResult RHSCopy = PerformCopyInitialization(Entity,
                                                      SourceLocation(),
-                                                     Owned(RHS));
+                                                     RHS);
       if (RHSCopy.isInvalid())
         return QualType();
 
-      LHS = LHSCopy.takeAs<Expr>();
-      RHS = RHSCopy.takeAs<Expr>();
+      LHS = LHSCopy;
+      RHS = RHSCopy;
     }
 
     return LTy;
@@ -3141,7 +3163,9 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
   //      common type, and the result is of that type.
   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
     UsualArithmeticConversions(LHS, RHS);
-    return LHS->getType();
+    if (LHS.isInvalid() || RHS.isInvalid())
+      return QualType();
+    return LHS.get()->getType();
   }
 
   //   -- The second and third operands have pointer type, or one has pointer
@@ -3162,7 +3186,7 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
       Diag(QuestionLoc,
            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
         << LTy << RTy << Composite
-        << LHS->getSourceRange() << RHS->getSourceRange();
+        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
 
     return Composite;
   }
@@ -3173,12 +3197,12 @@ QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
     return Composite;
 
   // Check if we are using a null with a non-pointer type.
-  if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
+  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
     return QualType();
 
   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
-    << LHS->getType() << RHS->getType()
-    << LHS->getSourceRange() << RHS->getSourceRange();
+    << LHS.get()->getType() << RHS.get()->getType()
+    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   return QualType();
 }
 
@@ -3828,24 +3852,26 @@ ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
                                    Destructed, HasTrailingLParen);
 }
 
-ExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
+ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
                                         CXXMethodDecl *Method) {
+  ExprResult Exp = Owned(E);
   if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
-                                          FoundDecl, Method))
+                                          FoundDecl, Method) ||
+      Exp.isInvalid())
     return true;
 
   MemberExpr *ME =
-      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
+      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
                                SourceLocation(), Method->getType(),
                                VK_RValue, OK_Ordinary);
   QualType ResultType = Method->getResultType();
   ExprValueKind VK = Expr::getValueKindForType(ResultType);
   ResultType = ResultType.getNonLValueExprType(Context);
 
-  MarkDeclarationReferenced(Exp->getLocStart(), Method);
+  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
   CXXMemberCallExpr *CE =
     new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
-                                    Exp->getLocEnd());
+                                    Exp.get()->getLocEnd());
   return CE;
 }
 
@@ -3863,24 +3889,24 @@ ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
 
 /// Perform the conversions required for an expression used in a
 /// context that ignores the result.
-void Sema::IgnoredValueConversions(Expr *&E) {
+void Sema::IgnoredValueConversions(ExprResult &E) {
   // C99 6.3.2.1:
   //   [Except in specific positions,] an lvalue that does not have
   //   array type is converted to the value stored in the
   //   designated object (and is no longer an lvalue).
-  if (E->isRValue()) return;
+  if (E.get()->isRValue()) return;
 
   // We always want to do this on ObjC property references.
-  if (E->getObjectKind() == OK_ObjCProperty) {
+  if (E.get()->getObjectKind() == OK_ObjCProperty) {
     ConvertPropertyForRValue(E);
-    if (E->isRValue()) return;
+    if (E.get()->isRValue()) return;
   }
 
   // Otherwise, this rule does not apply in C++, at least not for the moment.
   if (getLangOptions().CPlusPlus) return;
 
   // GCC seems to also exclude expressions of incomplete enum type.
-  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
+  if (const EnumType *T = E.get()->getType()->getAs<EnumType>()) {
     if (!T->getDecl()->isComplete()) {
       // FIXME: stupid workaround for a codegen bug!
       ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
@@ -3889,20 +3915,28 @@ void Sema::IgnoredValueConversions(Expr *&E) {
   }
 
   DefaultFunctionArrayLvalueConversion(E);
-  if (!E->getType()->isVoidType())
-    RequireCompleteType(E->getExprLoc(), E->getType(),
+  if (E.isInvalid())
+    return;
+
+  if (!E.get()->getType()->isVoidType())
+    RequireCompleteType(E.get()->getExprLoc(), E.get()->getType(),
                         diag::err_incomplete_type);
 }
 
-ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
-  if (!FullExpr)
+ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
+  ExprResult FullExpr = Owned(FE);
+
+  if (!FullExpr.get())
     return ExprError();
 
-  if (DiagnoseUnexpandedParameterPack(FullExpr))
+  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
     return ExprError();
 
   IgnoredValueConversions(FullExpr);
-  CheckImplicitConversions(FullExpr);
+  if (FullExpr.isInvalid())
+    return ExprError();
+
+  CheckImplicitConversions(FullExpr.get());
   return MaybeCreateExprWithCleanups(FullExpr);
 }
 
diff --git a/lib/Sema/SemaExprObjC.cpp b/lib/Sema/SemaExprObjC.cpp
index 4d03b06..d063d96 100644
--- a/lib/Sema/SemaExprObjC.cpp
+++ b/lib/Sema/SemaExprObjC.cpp
@@ -246,7 +246,11 @@ bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
       if (Args[i]->isTypeDependent())
         continue;
 
-      DefaultArgumentPromotion(Args[i]);
+      ExprResult Result = Owned(Args[i]);
+      DefaultArgumentPromotion(Result);
+      if (Result.isInvalid())
+        return true;
+      Args[i] = Result.take();
     }
 
     unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
@@ -305,7 +309,11 @@ bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
       if (Args[i]->isTypeDependent())
         continue;
 
-      IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
+      ExprResult Arg = Owned(Args[i]);
+      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
+      if (Arg.isInvalid())
+        return true;
+      Args[i] = Arg.take();
     }
   } else {
     // Check for extra arguments to non-variadic methods.
@@ -1007,7 +1015,11 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
 
     // If necessary, apply function/array conversion to the receiver.
     // C99 6.7.5.3p[7,8].
-    DefaultFunctionArrayLvalueConversion(Receiver);
+    ExprResult Result = Owned(Receiver);
+    DefaultFunctionArrayLvalueConversion(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Receiver = Result.take();
     ReceiverType = Receiver->getType();
   }
 
@@ -1136,26 +1148,32 @@ ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
         }
         ReceiverType = Receiver->getType();
       } 
-      else if (getLangOptions().CPlusPlus &&
-               !PerformContextuallyConvertToObjCId(Receiver)) {
-        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
-          Receiver = ICE->getSubExpr();
-          ReceiverType = Receiver->getType();
+      else {
+        ExprResult ReceiverRes = Owned(Receiver);
+        if (getLangOptions().CPlusPlus &&
+               !PerformContextuallyConvertToObjCId(ReceiverRes)) {
+          if (ReceiverRes.isInvalid())
+            return ExprError();
+          Receiver = ReceiverRes.take();
+          if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
+            Receiver = ICE->getSubExpr();
+            ReceiverType = Receiver->getType();
+          }
+          return BuildInstanceMessage(Receiver,
+                                      ReceiverType,
+                                      SuperLoc,
+                                      Sel,
+                                      Method,
+                                      LBracLoc,
+                                      SelectorLoc,
+                                      RBracLoc,
+                                      move(ArgsIn));
+        } else {
+          // Reject other random receiver types (e.g. structs).
+          Diag(Loc, diag::err_bad_receiver_type)
+            << ReceiverType << Receiver->getSourceRange();
+          return ExprError();
         }
-        return BuildInstanceMessage(Receiver,
-                                    ReceiverType,
-                                    SuperLoc,
-                                    Sel,
-                                    Method,
-                                    LBracLoc,
-                                    SelectorLoc,
-                                    RBracLoc,
-                                    move(ArgsIn));
-      } else {
-        // Reject other random receiver types (e.g. structs).
-        Diag(Loc, diag::err_bad_receiver_type)
-          << ReceiverType << Receiver->getSourceRange();
-        return ExprError();
       }
     }
   }
diff --git a/lib/Sema/SemaInit.cpp b/lib/Sema/SemaInit.cpp
index 358e5fb..9a66a5b 100644
--- a/lib/Sema/SemaInit.cpp
+++ b/lib/Sema/SemaInit.cpp
@@ -713,15 +713,23 @@ void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
     //   compatible structure or union type. In the latter case, the
     //   initial value of the object, including unnamed members, is
     //   that of the expression.
+    ExprResult ExprRes = SemaRef.Owned(expr);
     if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
-        SemaRef.CheckSingleAssignmentConstraints(ElemType, expr)
+        SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
           == Sema::Compatible) {
-      SemaRef.DefaultFunctionArrayLvalueConversion(expr);
-      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
+      if (ExprRes.isInvalid())
+        hadError = true;
+      else {
+        SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes);
+	      if (ExprRes.isInvalid())
+	        hadError = true;
+      }
+      UpdateStructuredListElement(StructuredList, StructuredIndex,
+                                  ExprRes.takeAs<Expr>());
       ++Index;
       return;
     }
-
+    ExprRes.release();
     // Fall through for subaggregate initialization
   }
 
@@ -2104,6 +2112,7 @@ bool InitializationSequence::isAmbiguous() const {
   case FK_ReferenceInitDropsQualifiers:
   case FK_ReferenceInitFailed:
   case FK_ConversionFailed:
+  case FK_ConversionFromPropertyFailed:
   case FK_TooManyInitsForScalar:
   case FK_ReferenceBindingToInitList:
   case FK_InitListBadDestinationType:
@@ -3129,8 +3138,15 @@ InitializationSequence::InitializationSequence(Sema &S,
   }
 
   for (unsigned I = 0; I != NumArgs; ++I)
-    if (Args[I]->getObjectKind() == OK_ObjCProperty)
-      S.ConvertPropertyForRValue(Args[I]);
+    if (Args[I]->getObjectKind() == OK_ObjCProperty) {
+      ExprResult Result = S.Owned(Args[I]);
+      S.ConvertPropertyForRValue(Result);
+      if (Result.isInvalid()) {
+        SetFailed(FK_ConversionFromPropertyFailed);
+        return;
+      }
+      Args[I] = Result.take();
+    }
 
   QualType SourceType;
   Expr *Initializer = 0;
@@ -3693,14 +3709,15 @@ InitializationSequence::Perform(Sema &S,
   case SK_ObjCObjectConversion:
   case SK_ArrayInit: {
     assert(Args.size() == 1);
-    Expr *CurInitExpr = Args.get()[0];
-    if (!CurInitExpr) return ExprError();
+    CurInit = Args.get()[0];
+    if (!CurInit.get()) return ExprError();
 
     // Read from a property when initializing something with it.
-    if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
-      S.ConvertPropertyForRValue(CurInitExpr);
-
-    CurInit = ExprResult(CurInitExpr);
+    if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
+      S.ConvertPropertyForRValue(CurInit);
+      if (CurInit.isInvalid())
+        return ExprError();
+    }
     break;
   }
 
@@ -3717,14 +3734,13 @@ InitializationSequence::Perform(Sema &S,
     if (CurInit.isInvalid())
       return ExprError();
 
-    Expr *CurInitExpr = CurInit.get();
-    QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
+    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
 
     switch (Step->Kind) {
     case SK_ResolveAddressOfOverloadedFunction:
       // Overload resolution determined which function invoke; update the
       // initializer to reflect that choice.
-      S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
+      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
       S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
       CurInit = S.FixOverloadedFunctionReference(move(CurInit),
                                                  Step->Function.FoundDecl,
@@ -3742,8 +3758,8 @@ InitializationSequence::Perform(Sema &S,
       // Casts to inaccessible base classes are allowed with C-style casts.
       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
-                                         CurInitExpr->getLocStart(),
-                                         CurInitExpr->getSourceRange(),
+                                         CurInit.get()->getLocStart(),
+                                         CurInit.get()->getSourceRange(),
                                          &BasePath, IgnoreBaseAccess))
         return ExprError();
 
@@ -3752,7 +3768,7 @@ InitializationSequence::Perform(Sema &S,
         if (const PointerType *Pointer = T->getAs<PointerType>())
           T = Pointer->getPointeeType();
         if (const RecordType *RecordTy = T->getAs<RecordType>())
-          S.MarkVTableUsed(CurInitExpr->getLocStart(),
+          S.MarkVTableUsed(CurInit.get()->getLocStart(),
                            cast<CXXRecordDecl>(RecordTy->getDecl()));
       }
 
@@ -3771,21 +3787,21 @@ InitializationSequence::Perform(Sema &S,
     }
 
     case SK_BindReference:
-      if (FieldDecl *BitField = CurInitExpr->getBitField()) {
+      if (FieldDecl *BitField = CurInit.get()->getBitField()) {
         // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
           << Entity.getType().isVolatileQualified()
           << BitField->getDeclName()
-          << CurInitExpr->getSourceRange();
+          << CurInit.get()->getSourceRange();
         S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
         return ExprError();
       }
 
-      if (CurInitExpr->refersToVectorElement()) {
+      if (CurInit.get()->refersToVectorElement()) {
         // References cannot bind to vector elements.
         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
           << Entity.getType().isVolatileQualified()
-          << CurInitExpr->getSourceRange();
+          << CurInit.get()->getSourceRange();
         PrintInitLocationNote(S, Entity);
         return ExprError();
       }
@@ -3793,7 +3809,7 @@ InitializationSequence::Perform(Sema &S,
       // Reference binding does not have any corresponding ASTs.
 
       // Check exception specifications
-      if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
+      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
         return ExprError();
 
       break;
@@ -3802,7 +3818,7 @@ InitializationSequence::Perform(Sema &S,
       // Reference binding does not have any corresponding ASTs.
 
       // Check exception specifications
-      if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
+      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
         return ExprError();
 
       break;
@@ -3824,13 +3840,14 @@ InitializationSequence::Perform(Sema &S,
       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
         // Build a call to the selected constructor.
         ASTOwningVector<Expr*> ConstructorArgs(S);
-        SourceLocation Loc = CurInitExpr->getLocStart();
+        SourceLocation Loc = CurInit.get()->getLocStart();
         CurInit.release(); // Ownership transferred into MultiExprArg, below.
 
         // Determine the arguments required to actually perform the constructor
         // call.
+        Expr *Arg = CurInit.get();
         if (S.CompleteConstructorCall(Constructor,
-                                      MultiExprArg(&CurInitExpr, 1),
+                                      MultiExprArg(&Arg, 1),
                                       Loc, ConstructorArgs))
           return ExprError();
 
@@ -3858,23 +3875,22 @@ InitializationSequence::Perform(Sema &S,
         // Build a call to the conversion function.
         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
         IsLvalue = Conversion->getResultType()->isLValueReferenceType();
-        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
+        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
                                     FoundFn);
         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
 
         // FIXME: Should we move this initialization into a separate
         // derived-to-base conversion? I believe the answer is "no", because
         // we don't want to turn off access control here for c-style casts.
-        if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
-                                                  FoundFn, Conversion))
+        ExprResult CurInitExprRes = move(CurInit);
+        if (S.PerformObjectArgumentInitialization(CurInitExprRes, /*Qualifier=*/0,
+                                                  FoundFn, Conversion) ||
+            CurInitExprRes.isInvalid())
           return ExprError();
-
-        // Do a little dance to make sure that CurInit has the proper
-        // pointer.
-        CurInit.release();
+        CurInit = move(CurInitExprRes);
 
         // Build the actual call to the conversion function.
-        CurInit = S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, Conversion);
+        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
         if (CurInit.isInvalid() || !CurInit.get())
           return ExprError();
 
@@ -3888,23 +3904,21 @@ InitializationSequence::Perform(Sema &S,
       if (RequiresCopy || shouldBindAsTemporary(Entity))
         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
       else if (CreatedObject && shouldDestroyTemporary(Entity)) {
-        CurInitExpr = static_cast<Expr *>(CurInit.get());
-        QualType T = CurInitExpr->getType();
+        QualType T = CurInit.get()->getType();
         if (const RecordType *Record = T->getAs<RecordType>()) {
           CXXDestructorDecl *Destructor
             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
-          S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
+          S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
                                   S.PDiag(diag::err_access_dtor_temp) << T);
-          S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
-          S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
+          S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
+          S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
         }
       }
 
-      CurInitExpr = CurInit.takeAs<Expr>();
       // FIXME: xvalues
       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
-                                                 CurInitExpr->getType(),
-                                                 CastKind, CurInitExpr, 0,
+                                                 CurInit.get()->getType(),
+                                                 CastKind, CurInit.get(), 0,
                                            IsLvalue ? VK_LValue : VK_RValue));
 
       if (RequiresCopy)
@@ -3924,25 +3938,20 @@ InitializationSequence::Perform(Sema &S,
               (Step->Kind == SK_QualificationConversionXValue ?
                    VK_XValue :
                    VK_RValue);
-      S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
-      CurInit.release();
-      CurInit = S.Owned(CurInitExpr);
+      S.ImpCastExprToType(CurInit, Step->Type, CK_NoOp, VK);
       break;
     }
 
     case SK_ConversionSequence: {
-      if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
+      if (S.PerformImplicitConversion(CurInit, Step->Type, *Step->ICS,
                                       getAssignmentAction(Entity),
                                       Kind.isCStyleOrFunctionalCast()))
         return ExprError();
-
-      CurInit.release();
-      CurInit = S.Owned(CurInitExpr);
       break;
     }
 
     case SK_ListInitialization: {
-      InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
+      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
       QualType Ty = Step->Type;
       if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
         return ExprError();
@@ -4075,54 +4084,57 @@ InitializationSequence::Perform(Sema &S,
     }
 
     case SK_CAssignment: {
-      QualType SourceType = CurInitExpr->getType();
+      QualType SourceType = CurInit.get()->getType();
+      ExprResult Result = move(CurInit);
       Sema::AssignConvertType ConvTy =
-        S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
+        S.CheckSingleAssignmentConstraints(Step->Type, Result);
+      if (Result.isInvalid())
+        return ExprError();
+      CurInit = move(Result);
 
       // If this is a call, allow conversion to a transparent union.
+      ExprResult CurInitExprRes = move(CurInit);
       if (ConvTy != Sema::Compatible &&
           Entity.getKind() == InitializedEntity::EK_Parameter &&
-          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
+          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
             == Sema::Compatible)
         ConvTy = Sema::Compatible;
+      if (CurInitExprRes.isInvalid())
+        return ExprError();
+      CurInit = move(CurInitExprRes);
 
       bool Complained;
       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
                                      Step->Type, SourceType,
-                                     CurInitExpr,
+                                     CurInit.get(),
                                      getAssignmentAction(Entity),
                                      &Complained)) {
         PrintInitLocationNote(S, Entity);
         return ExprError();
       } else if (Complained)
         PrintInitLocationNote(S, Entity);
-
-      CurInit.release();
-      CurInit = S.Owned(CurInitExpr);
       break;
     }
 
     case SK_StringInit: {
       QualType Ty = Step->Type;
-      CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty,
+      CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
                       S.Context.getAsArrayType(Ty), S);
       break;
     }
 
     case SK_ObjCObjectConversion:
-      S.ImpCastExprToType(CurInitExpr, Step->Type,
+      S.ImpCastExprToType(CurInit, Step->Type,
                           CK_ObjCObjectLValueCast,
-                          S.CastCategory(CurInitExpr));
-      CurInit.release();
-      CurInit = S.Owned(CurInitExpr);
+                          S.CastCategory(CurInit.get()));
       break;
 
     case SK_ArrayInit:
       // Okay: we checked everything before creating this step. Note that
       // this is a GNU extension.
       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
-        << Step->Type << CurInitExpr->getType()
-        << CurInitExpr->getSourceRange();
+        << Step->Type << CurInit.get()->getType()
+        << CurInit.get()->getSourceRange();
 
       // If the destination type is an incomplete array type, update the
       // type accordingly.
@@ -4130,7 +4142,7 @@ InitializationSequence::Perform(Sema &S,
         if (const IncompleteArrayType *IncompleteDest
                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
           if (const ConstantArrayType *ConstantSource
-                 = S.Context.getAsConstantArrayType(CurInitExpr->getType())) {
+                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
             *ResultType = S.Context.getConstantArrayType(
                                              IncompleteDest->getElementType(),
                                              ConstantSource->getSize(),
@@ -4290,6 +4302,11 @@ bool InitializationSequence::Diagnose(Sema &S,
       << Args[0]->getSourceRange();
     break;
   }
+
+  case FK_ConversionFromPropertyFailed:
+    // No-op. This error has already been reported.
+    break;
+
   case FK_TooManyInitsForScalar: {
     SourceRange R;
 
@@ -4489,6 +4506,10 @@ void InitializationSequence::dump(llvm::raw_ostream &OS) const {
       OS << "conversion failed";
       break;
 
+    case FK_ConversionFromPropertyFailed:
+      OS << "conversion from property failed";
+      break;
+
     case FK_TooManyInitsForScalar:
       OS << "too many initializers for scalar";
       break;
diff --git a/lib/Sema/SemaOverload.cpp b/lib/Sema/SemaOverload.cpp
index bf24b74..afcd583 100644
--- a/lib/Sema/SemaOverload.cpp
+++ b/lib/Sema/SemaOverload.cpp
@@ -36,12 +36,14 @@ using namespace sema;
 
 /// A convenience routine for creating a decayed reference to a
 /// function.
-static Expr *
+static ExprResult
 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
                       SourceLocation Loc = SourceLocation()) {
-  Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
+  ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
   S.DefaultFunctionArrayConversion(E);
-  return E;
+  if (E.isInvalid())
+    return ExprError();
+  return move(E);
 }
 
 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
@@ -882,17 +884,17 @@ bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
 /// performing, used in the error message. If @p AllowExplicit,
 /// explicit user-defined conversions are permitted.
 bool
-Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
+Sema::PerformImplicitConversion(ExprResult &From, QualType ToType,
                                 AssignmentAction Action, bool AllowExplicit) {
   ImplicitConversionSequence ICS;
   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
 }
 
 bool
-Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
+Sema::PerformImplicitConversion(ExprResult &From, QualType ToType,
                                 AssignmentAction Action, bool AllowExplicit,
                                 ImplicitConversionSequence& ICS) {
-  ICS = clang::TryImplicitConversion(*this, From, ToType,
+  ICS = clang::TryImplicitConversion(*this, From.get(), ToType,
                                      /*SuppressUserConversions=*/false,
                                      AllowExplicit,
                                      /*InOverloadResolution=*/false,
@@ -3481,7 +3483,7 @@ TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
 /// the implicit object parameter for the given Method with the given
 /// expression.
 bool
-Sema::PerformObjectArgumentInitialization(Expr *&From,
+Sema::PerformObjectArgumentInitialization(ExprResult &From,
                                           NestedNameSpecifier *Qualifier,
                                           NamedDecl *FoundDecl,
                                           CXXMethodDecl *Method) {
@@ -3490,20 +3492,20 @@ Sema::PerformObjectArgumentInitialization(Expr *&From,
     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
 
   Expr::Classification FromClassification;
-  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
+  if (const PointerType *PT = From.get()->getType()->getAs<PointerType>()) {
     FromRecordType = PT->getPointeeType();
     DestType = Method->getThisType(Context);
     FromClassification = Expr::Classification::makeSimpleLValue();
   } else {
-    FromRecordType = From->getType();
+    FromRecordType = From.get()->getType();
     DestType = ImplicitParamRecordType;
-    FromClassification = From->Classify(Context);
+    FromClassification = From.get()->Classify(Context);
   }
 
   // Note that we always use the true parent context when performing
   // the actual argument initialization.
   ImplicitConversionSequence ICS
-    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
+    = TryObjectArgumentInitialization(*this, From.get()->getType(), FromClassification,
                                       Method, Method->getParent());
   if (ICS.isBad()) {
     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
@@ -3511,27 +3513,27 @@ Sema::PerformObjectArgumentInitialization(Expr *&From,
       Qualifiers ToQs = DestType.getQualifiers();
       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
       if (CVR) {
-        Diag(From->getSourceRange().getBegin(),
+        Diag(From.get()->getSourceRange().getBegin(),
              diag::err_member_function_call_bad_cvr)
           << Method->getDeclName() << FromRecordType << (CVR - 1)
-          << From->getSourceRange();
+          << From.get()->getSourceRange();
         Diag(Method->getLocation(), diag::note_previous_decl)
           << Method->getDeclName();
         return true;
       }
     }
 
-    return Diag(From->getSourceRange().getBegin(),
+    return Diag(From.get()->getSourceRange().getBegin(),
                 diag::err_implicit_object_parameter_init)
-       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
+       << ImplicitParamRecordType << FromRecordType << From.get()->getSourceRange();
   }
 
   if (ICS.Standard.Second == ICK_Derived_To_Base)
     return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
 
-  if (!Context.hasSameType(From->getType(), DestType))
+  if (!Context.hasSameType(From.get()->getType(), DestType))
     ImpCastExprToType(From, DestType, CK_NoOp,
-                      From->getType()->isPointerType() ? VK_RValue : VK_LValue);
+                      From.get()->getType()->isPointerType() ? VK_RValue : VK_LValue);
   return false;
 }
 
@@ -3550,15 +3552,15 @@ TryContextuallyConvertToBool(Sema &S, Expr *From) {
 
 /// PerformContextuallyConvertToBool - Perform a contextual conversion
 /// of the expression From to bool (C++0x [conv]p3).
-bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
-  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
+bool Sema::PerformContextuallyConvertToBool(ExprResult &From) {
+  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From.get());
   if (!ICS.isBad())
     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
 
-  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
-    return  Diag(From->getSourceRange().getBegin(),
+  if (!DiagnoseMultipleUserDefinedConversion(From.get(), Context.BoolTy))
+    return  Diag(From.get()->getSourceRange().getBegin(),
                  diag::err_typecheck_bool_condition)
-                  << From->getType() << From->getSourceRange();
+                  << From.get()->getType() << From.get()->getSourceRange();
   return true;
 }
 
@@ -3577,9 +3579,9 @@ TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
 
 /// PerformContextuallyConvertToObjCId - Perform a contextual conversion
 /// of the expression From to 'id'.
-bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
+bool Sema::PerformContextuallyConvertToObjCId(ExprResult &From) {
   QualType Ty = Context.getObjCIdType();
-  ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
+  ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From.get());
   if (!ICS.isBad())
     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
   return true;
@@ -7747,8 +7749,13 @@ Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
   // TODO: provide better source location info.
   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
 
-  if (Input->getObjectKind() == OK_ObjCProperty)
-    ConvertPropertyForRValue(Input);
+  if (Input->getObjectKind() == OK_ObjCProperty) {
+    ExprResult Result = Owned(Input);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Input = Result.take();
+  }
 
   Expr *Args[2] = { Input, 0 };
   unsigned NumArgs = 1;
@@ -7819,9 +7826,12 @@ Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
 
-        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
-                                                Best->FoundDecl, Method))
+        ExprResult InputRes = Owned(Input);
+        if (PerformObjectArgumentInitialization(InputRes, /*Qualifier=*/0,
+                                                Best->FoundDecl, Method) ||
+            InputRes.isInvalid())
           return ExprError();
+        Input = InputRes.take();
       } else {
         // Convert the arguments.
         ExprResult InputInit
@@ -7843,11 +7853,13 @@ Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
       ResultTy = ResultTy.getNonLValueExprType(Context);
 
       // Build the actual expression node.
-      Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
+      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
+      if (FnExpr.isInvalid())
+        return ExprError();
 
       Args[0] = Input;
       CallExpr *TheCall =
-        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
+        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
                                           Args, NumArgs, ResultTy, VK, OpLoc);
 
       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
@@ -7859,12 +7871,14 @@ Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
       // We matched a built-in operator. Convert the arguments, then
       // break out so that we will build the appropriate built-in
       // operator node.
-        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
-                                      Best->Conversions[0], AA_Passing))
-          return ExprError();
-
-        break;
-      }
+      ExprResult InputRes = Owned(Input);
+      if (PerformImplicitConversion(InputRes, Best->BuiltinTypes.ParamTypes[0],
+                                    Best->Conversions[0], AA_Passing) ||
+          InputRes.isInvalid())
+        return ExprError();
+      Input = InputRes.take();
+      break;
+    }
     }
 
     case OR_No_Viable_Function:
@@ -7966,8 +7980,13 @@ Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
   }
 
   // Always do property rvalue conversions on the RHS.
-  if (Args[1]->getObjectKind() == OK_ObjCProperty)
-    ConvertPropertyForRValue(Args[1]);
+  if (Args[1]->getObjectKind() == OK_ObjCProperty) {
+    ExprResult Result = Owned(Args[1]);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Args[1] = Result.take();
+  }
 
   // The LHS is more complicated.
   if (Args[0]->getObjectKind() == OK_ObjCProperty) {
@@ -7995,7 +8014,11 @@ Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
         return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
     }
 
-    ConvertPropertyForRValue(Args[0]);
+    ExprResult Result = Owned(Args[0]);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Args[0] = Result.take();
   }
 
   // If this is the assignment operator, we only perform overload resolution
@@ -8056,10 +8079,12 @@ Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
           if (Arg1.isInvalid())
             return ExprError();
 
-          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
-                                                  Best->FoundDecl, Method))
+          ExprResult Arg0 = Owned(Args[0]);
+          if (PerformObjectArgumentInitialization(Arg0, /*Qualifier=*/0,
+                                                  Best->FoundDecl, Method) ||
+              Arg0.isInvalid())
             return ExprError();
-
+          Args[0] = Arg0.takeAs<Expr>();
           Args[1] = RHS = Arg1.takeAs<Expr>();
         } else {
           // Convert the arguments.
@@ -8089,10 +8114,12 @@ Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
         ResultTy = ResultTy.getNonLValueExprType(Context);
 
         // Build the actual expression node.
-        Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
+        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
+        if (FnExpr.isInvalid())
+          return ExprError();
 
         CXXOperatorCallExpr *TheCall =
-          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
+          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
                                             Args, 2, ResultTy, VK, OpLoc);
 
         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
@@ -8104,12 +8131,15 @@ Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
         // We matched a built-in operator. Convert the arguments, then
         // break out so that we will build the appropriate built-in
         // operator node.
-        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
+        ExprResult ArgsRes[2] = { Owned(Args[0]), Owned(Args[1]) };
+        if (PerformImplicitConversion(ArgsRes[0], Best->BuiltinTypes.ParamTypes[0],
                                       Best->Conversions[0], AA_Passing) ||
-            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
-                                      Best->Conversions[1], AA_Passing))
+            PerformImplicitConversion(ArgsRes[1], Best->BuiltinTypes.ParamTypes[1],
+                                      Best->Conversions[1], AA_Passing) ||
+            ArgsRes[0].isInvalid() || ArgsRes[1].isInvalid())
           return ExprError();
-
+        Args[0] = ArgsRes[0].take();
+        Args[1] = ArgsRes[1].take();
         break;
       }
     }
@@ -8199,10 +8229,20 @@ Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
                                                    RLoc));
   }
 
-  if (Args[0]->getObjectKind() == OK_ObjCProperty)
-    ConvertPropertyForRValue(Args[0]);
-  if (Args[1]->getObjectKind() == OK_ObjCProperty)
-    ConvertPropertyForRValue(Args[1]);
+  if (Args[0]->getObjectKind() == OK_ObjCProperty) {
+    ExprResult Result = Owned(Args[0]);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Args[0] = Result.take();
+  }
+  if (Args[1]->getObjectKind() == OK_ObjCProperty) {
+    ExprResult Result = Owned(Args[1]);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Args[1] = Result.take();
+  }
 
   // Build an empty overload set.
   OverloadCandidateSet CandidateSet(LLoc);
@@ -8233,9 +8273,12 @@ Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
 
         // Convert the arguments.
         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
-        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
-                                                Best->FoundDecl, Method))
+        ExprResult Arg0 = Owned(Args[0]);
+        if (PerformObjectArgumentInitialization(Arg0, /*Qualifier=*/0,
+                                                Best->FoundDecl, Method) ||
+            Arg0.isInvalid())
           return ExprError();
+        Args[0] = Arg0.take();
 
         // Convert the arguments.
         ExprResult InputInit
@@ -8255,11 +8298,13 @@ Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
         ResultTy = ResultTy.getNonLValueExprType(Context);
 
         // Build the actual expression node.
-        Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
+        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
+        if (FnExpr.isInvalid())
+          return ExprError();
 
         CXXOperatorCallExpr *TheCall =
           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
-                                            FnExpr, Args, 2,
+                                            FnExpr.take(), Args, 2,
                                             ResultTy, VK, RLoc);
 
         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
@@ -8271,12 +8316,15 @@ Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
         // We matched a built-in operator. Convert the arguments, then
         // break out so that we will build the appropriate built-in
         // operator node.
-        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
+        ExprResult ArgsRes[2] = { Owned(Args[0]), Owned(Args[1]) };
+        if (PerformImplicitConversion(ArgsRes[0], Best->BuiltinTypes.ParamTypes[0],
                                       Best->Conversions[0], AA_Passing) ||
-            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
-                                      Best->Conversions[1], AA_Passing))
+            PerformImplicitConversion(ArgsRes[1], Best->BuiltinTypes.ParamTypes[1],
+                                      Best->Conversions[1], AA_Passing) ||
+            ArgsRes[0].isInvalid() || ArgsRes[1].isInvalid())
           return ExprError();
-
+        Args[0] = ArgsRes[0].take();
+        Args[1] = ArgsRes[1].take();
         break;
       }
     }
@@ -8463,12 +8511,13 @@ Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
   // Convert the object argument (for a non-static member function call).
   // We only need to do this if there was actually an overload; otherwise
   // it was done at lookup.
-  Expr *ObjectArg = MemExpr->getBase();
+  ExprResult ObjectArg = Owned(MemExpr->getBase());
   if (!Method->isStatic() &&
-      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
-                                          FoundDecl, Method))
+      (PerformObjectArgumentInitialization(ObjectArg, Qualifier,
+                                          FoundDecl, Method)) ||
+       ObjectArg.isInvalid())
     return ExprError();
-  MemExpr->setBase(ObjectArg);
+  MemExpr->setBase(ObjectArg.take());
 
   // Convert the rest of the arguments
   const FunctionProtoType *Proto =
@@ -8488,15 +8537,19 @@ Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
 /// overloaded function call operator (@c operator()) or performing a
 /// user-defined conversion on the object argument.
 ExprResult
-Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
+Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
                                    SourceLocation LParenLoc,
                                    Expr **Args, unsigned NumArgs,
                                    SourceLocation RParenLoc) {
-  if (Object->getObjectKind() == OK_ObjCProperty)
+  ExprResult Object = Owned(Obj);
+  if (Object.get()->getObjectKind() == OK_ObjCProperty) {
     ConvertPropertyForRValue(Object);
+    if (Object.isInvalid())
+      return ExprError();
+  }
 
-  assert(Object->getType()->isRecordType() && "Requires object type argument");
-  const RecordType *Record = Object->getType()->getAs<RecordType>();
+  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
+  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
 
   // C++ [over.call.object]p1:
   //  If the primary-expression E in the function call syntax
@@ -8508,9 +8561,9 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
   OverloadCandidateSet CandidateSet(LParenLoc);
   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
 
-  if (RequireCompleteType(LParenLoc, Object->getType(),
+  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
                           PDiag(diag::err_incomplete_object_call)
-                          << Object->getSourceRange()))
+                          << Object.get()->getSourceRange()))
     return true;
 
   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
@@ -8519,8 +8572,8 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
 
   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
        Oper != OperEnd; ++Oper) {
-    AddMethodCandidate(Oper.getPair(), Object->getType(),
-                       Object->Classify(Context), Args, NumArgs, CandidateSet,
+    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
+                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
                        /*SuppressUserConversions=*/ false);
   }
 
@@ -8565,12 +8618,12 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
 
     if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
       AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
-                            Object, Args, NumArgs, CandidateSet);
+                            Object.get(), Args, NumArgs, CandidateSet);
   }
 
   // Perform overload resolution.
   OverloadCandidateSet::iterator Best;
-  switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
+  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
                              Best)) {
   case OR_Success:
     // Overload resolution succeeded; we'll build the appropriate call
@@ -8579,31 +8632,31 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
 
   case OR_No_Viable_Function:
     if (CandidateSet.empty())
-      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
-        << Object->getType() << /*call*/ 1
-        << Object->getSourceRange();
+      Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
+        << Object.get()->getType() << /*call*/ 1
+        << Object.get()->getSourceRange();
     else
-      Diag(Object->getSourceRange().getBegin(),
+      Diag(Object.get()->getSourceRange().getBegin(),
            diag::err_ovl_no_viable_object_call)
-        << Object->getType() << Object->getSourceRange();
+        << Object.get()->getType() << Object.get()->getSourceRange();
     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
     break;
 
   case OR_Ambiguous:
-    Diag(Object->getSourceRange().getBegin(),
+    Diag(Object.get()->getSourceRange().getBegin(),
          diag::err_ovl_ambiguous_object_call)
-      << Object->getType() << Object->getSourceRange();
+      << Object.get()->getType() << Object.get()->getSourceRange();
     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
     break;
 
   case OR_Deleted:
-    Diag(Object->getSourceRange().getBegin(),
+    Diag(Object.get()->getSourceRange().getBegin(),
          diag::err_ovl_deleted_object_call)
       << Best->Function->isDeleted()
-      << Object->getType() 
+      << Object.get()->getType() 
       << Best->Function->getMessageUnavailableAttr(
            !Best->Function->isDeleted())
-      << Object->getSourceRange();
+      << Object.get()->getSourceRange();
     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
     break;
   }
@@ -8618,7 +8671,7 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
       = cast<CXXConversionDecl>(
                          Best->Conversions[0].UserDefined.ConversionFunction);
 
-    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
+    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
 
     // We selected one of the surrogate functions that converts the
@@ -8627,7 +8680,7 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
 
     // Create an implicit member expr to refer to the conversion operator.
     // and then call it.
-    ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
+    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
     if (Call.isInvalid())
       return ExprError();
 
@@ -8636,7 +8689,7 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
   }
 
   MarkDeclarationReferenced(LParenLoc, Best->Function);
-  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
+  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
 
   // We found an overloaded operator(). Build a CXXOperatorCallExpr
@@ -8659,11 +8712,13 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
   } else {
     MethodArgs = new Expr*[NumArgs + 1];
   }
-  MethodArgs[0] = Object;
+  MethodArgs[0] = Object.get();
   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
 
-  Expr *NewFn = CreateFunctionRefExpr(*this, Method);
+  ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
+  if (NewFn.isInvalid())
+    return true;
 
   // Once we've built TheCall, all of the expressions are properly
   // owned.
@@ -8672,7 +8727,7 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
   ResultTy = ResultTy.getNonLValueExprType(Context);
 
   CXXOperatorCallExpr *TheCall =
-    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
+    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
                                       MethodArgs, NumArgs + 1,
                                       ResultTy, VK, RParenLoc);
   delete [] MethodArgs;
@@ -8693,7 +8748,9 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
   // Initialize the implicit object parameter.
   IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
                                                  Best->FoundDecl, Method);
-  TheCall->setArg(0, Object);
+  if (Object.isInvalid())
+    return true;
+  TheCall->setArg(0, Object.take());
 
 
   // Check the argument types.
@@ -8730,9 +8787,11 @@ Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
   if (Proto->isVariadic()) {
     // Promote the arguments (C99 6.5.2.2p7).
     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
-      Expr *Arg = Args[i];
+      ExprResult Arg = Owned(Args[i]);
       IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
-      TheCall->setArg(i + 1, Arg);
+      if (Arg.isInvalid())
+        return true;
+      TheCall->setArg(i + 1, Arg.take());
     }
   }
 
@@ -8752,8 +8811,13 @@ Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
   assert(Base->getType()->isRecordType() &&
          "left-hand side must have class type");
 
-  if (Base->getObjectKind() == OK_ObjCProperty)
-    ConvertPropertyForRValue(Base);
+  if (Base->getObjectKind() == OK_ObjCProperty) {
+    ExprResult Result = Owned(Base);
+    ConvertPropertyForRValue(Result);
+    if (Result.isInvalid())
+      return ExprError();
+    Base = Result.take();
+  }
 
   SourceLocation Loc = Base->getExprLoc();
 
@@ -8823,18 +8887,23 @@ Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
 
   // Convert the object parameter.
   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
-  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
-                                          Best->FoundDecl, Method))
+  ExprResult BaseResult = Owned(Base);
+  if (PerformObjectArgumentInitialization(BaseResult, /*Qualifier=*/0,
+                                          Best->FoundDecl, Method) ||
+      BaseResult.isInvalid())
     return ExprError();
+  Base = BaseResult.take();
 
   // Build the operator call.
-  Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
+  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
+  if (FnExpr.isInvalid())
+    return ExprError();
 
   QualType ResultTy = Method->getResultType();
   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
   ResultTy = ResultTy.getNonLValueExprType(Context);
   CXXOperatorCallExpr *TheCall =
-    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
+    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
                                       &Base, 1, ResultTy, VK, OpLoc);
 
   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
diff --git a/lib/Sema/SemaStmt.cpp b/lib/Sema/SemaStmt.cpp
index ca37df9..6c67354 100644
--- a/lib/Sema/SemaStmt.cpp
+++ b/lib/Sema/SemaStmt.cpp
@@ -469,7 +469,11 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
       GetTypeBeforeIntegralPromotion(CondExpr);
 
   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
-  UsualUnaryConversions(CondExpr);
+  ExprResult CondResult = Owned(CondExpr);
+  UsualUnaryConversions(CondResult);
+  if (CondResult.isInvalid())
+    return StmtError();
+  CondExpr = CondResult.take();
   QualType CondType = CondExpr->getType();
   SS->setCond(CondExpr);
 
@@ -868,8 +872,10 @@ Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
                   Expr *Cond, SourceLocation CondRParen) {
   assert(Cond && "ActOnDoStmt(): missing expression");
 
-  if (CheckBooleanCondition(Cond, DoLoc))
+  ExprResult CondRes = Owned(Cond);
+  if (CheckBooleanCondition(CondRes, DoLoc) || CondRes.isInvalid())
     return StmtError();
+  Cond = CondRes.take();
 
   CheckImplicitConversions(Cond, DoLoc);
   ExprResult CondResult = MaybeCreateExprWithCleanups(Cond);
@@ -973,7 +979,11 @@ Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
           << FirstType << First->getSourceRange();
   }
   if (Second && !Second->isTypeDependent()) {
-    DefaultFunctionArrayLvalueConversion(Second);
+    ExprResult Result = Owned(Second);
+    DefaultFunctionArrayLvalueConversion(Result);
+    if (Result.isInvalid())
+      return StmtError();
+    Second = Result.take();
     QualType SecondType = Second->getType();
     if (!SecondType->isObjCObjectPointerType())
       Diag(ForLoc, diag::err_collection_expr_type)
@@ -1019,8 +1029,12 @@ Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
   if (!E->isTypeDependent()) {
     QualType ETy = E->getType();
     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
+    ExprResult ExprRes = Owned(E);
     AssignConvertType ConvTy =
-      CheckSingleAssignmentConstraints(DestTy, E);
+      CheckSingleAssignmentConstraints(DestTy, ExprRes);
+    if (ExprRes.isInvalid())
+      return StmtError();
+    E = ExprRes.take();
     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
       return StmtError();
   }
@@ -1187,7 +1201,11 @@ Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
     if (RetValExp) {
       // Don't call UsualUnaryConversions(), since we don't want to do
       // integer promotions here.
-      DefaultFunctionArrayLvalueConversion(RetValExp);
+      ExprResult Result = Owned(RetValExp);
+      DefaultFunctionArrayLvalueConversion(Result);
+      if (Result.isInvalid())
+        return StmtError();
+      RetValExp = Result.take();
       CurBlock->ReturnType = RetValExp->getType();
       if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
         // We have to remove a 'const' added to copied-in variable which was
@@ -1289,7 +1307,11 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
       if (RetValExp->getType()->isVoidType())
         D = diag::ext_return_has_void_expr;
       else {
-        IgnoredValueConversions(RetValExp);
+        ExprResult Result = Owned(RetValExp);
+        IgnoredValueConversions(Result);
+        if (Result.isInvalid())
+          return StmtError();
+        RetValExp = Result.take();
         ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid);
       }
 
@@ -1497,8 +1519,12 @@ StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
       }
     }
 
-    DefaultFunctionArrayLvalueConversion(Exprs[i]);
+    ExprResult Result = Owned(Exprs[i]);
+    DefaultFunctionArrayLvalueConversion(Result);
+    if (Result.isInvalid())
+      return StmtError();
 
+    Exprs[i] = Result.take();
     InputConstraintInfos.push_back(Info);
   }
 
@@ -1662,8 +1688,12 @@ Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
                                                   Expr *Throw) {
   if (Throw) {
-    DefaultLvalueConversion(Throw);
+    ExprResult Result = Owned(Throw);
+    DefaultLvalueConversion(Result);
+    if (Result.isInvalid())
+      return StmtError();
 
+    Throw = Result.take();
     QualType ThrowType = Throw->getType();
     // Make sure the expression type is an ObjC pointer or "void *".
     if (!ThrowType->isDependentType() &&
@@ -1702,8 +1732,12 @@ Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
                                   Stmt *SyncBody) {
   getCurFunction()->setHasBranchProtectedScope();
 
-  DefaultLvalueConversion(SyncExpr);
+  ExprResult Result = Owned(SyncExpr);
+  DefaultLvalueConversion(Result);
+  if (Result.isInvalid())
+    return StmtError();
 
+  SyncExpr = Result.take();
   // Make sure the expression type is an ObjC pointer or "void *".
   if (!SyncExpr->getType()->isDependentType() &&
       !SyncExpr->getType()->isObjCObjectPointerType()) {
diff --git a/lib/Sema/SemaTemplate.cpp b/lib/Sema/SemaTemplate.cpp
index f70efc1..6b54e00 100644
--- a/lib/Sema/SemaTemplate.cpp
+++ b/lib/Sema/SemaTemplate.cpp
@@ -679,10 +679,13 @@ Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
       return Param;
 
     TemplateArgument Converted;
-    if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
+    ExprResult DefaultRes = Owned(Default);
+    if (CheckTemplateArgument(Param, Param->getType(), DefaultRes, Converted) ||
+        DefaultRes.isInvalid()) {
       Param->setInvalidDecl();
       return Param;
     }
+    Default = DefaultRes.take();
 
     Param->setDefaultArgument(Default, false);
   }
@@ -2380,9 +2383,10 @@ bool Sema::CheckTemplateArgument(NamedDecl *Param,
       return true;
 
     case TemplateArgument::Expression: {
-      Expr *E = Arg.getArgument().getAsExpr();
+      ExprResult E = Owned(Arg.getArgument().getAsExpr());
       TemplateArgument Result;
-      if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
+      if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK) ||
+          E.isInvalid())
         return true;
 
       Converted.push_back(Result);
@@ -2413,23 +2417,20 @@ bool Sema::CheckTemplateArgument(NamedDecl *Param,
 
         CXXScopeSpec SS;
         SS.Adopt(Arg.getTemplateQualifierLoc());
-        Expr *E = DependentScopeDeclRefExpr::Create(Context,
+        ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
                                                 SS.getWithLocInContext(Context),
-                                                    NameInfo);
+                                                    NameInfo));
 
         // If we parsed the template argument as a pack expansion, create a
         // pack expansion expression.
         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
-          ExprResult Expansion = ActOnPackExpansion(E,
-                                                  Arg.getTemplateEllipsisLoc());
-          if (Expansion.isInvalid())
+          E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
+          if (E.isInvalid())
             return true;
-
-          E = Expansion.get();
         }
 
         TemplateArgument Result;
-        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
+        if (CheckTemplateArgument(NTTP, NTTPType, E, Result) || E.isInvalid())
           return true;
 
         Converted.push_back(Result);
@@ -3357,16 +3358,16 @@ bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
 ///
 /// If no error was detected, Converted receives the converted template argument.
 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
-                                 QualType InstantiatedParamType, Expr *&Arg,
+                                 QualType InstantiatedParamType, ExprResult &Arg,
                                  TemplateArgument &Converted,
                                  CheckTemplateArgumentKind CTAK) {
-  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
+  SourceLocation StartLoc = Arg.get()->getSourceRange().getBegin();
 
   // If either the parameter has a dependent type or the argument is
   // type-dependent, there's nothing we can check now.
-  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
+  if (InstantiatedParamType->isDependentType() || Arg.get()->isTypeDependent()) {
     // FIXME: Produce a cloned, canonical expression?
-    Converted = TemplateArgument(Arg);
+    Converted = TemplateArgument(Arg.get());
     return false;
   }
 
@@ -3381,7 +3382,7 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
   //        enumeration type, integral promotions (4.5) and integral
   //        conversions (4.7) are applied.
   QualType ParamType = InstantiatedParamType;
-  QualType ArgType = Arg->getType();
+  QualType ArgType = Arg.get()->getType();
   if (ParamType->isIntegralOrEnumerationType()) {
     // C++ [temp.arg.nontype]p1:
     //   A template-argument for a non-type, non-template
@@ -3393,15 +3394,15 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
     SourceLocation NonConstantLoc;
     llvm::APSInt Value;
     if (!ArgType->isIntegralOrEnumerationType()) {
-      Diag(Arg->getSourceRange().getBegin(),
+      Diag(Arg.get()->getSourceRange().getBegin(),
            diag::err_template_arg_not_integral_or_enumeral)
-        << ArgType << Arg->getSourceRange();
+        << ArgType << Arg.get()->getSourceRange();
       Diag(Param->getLocation(), diag::note_template_param_here);
       return true;
-    } else if (!Arg->isValueDependent() &&
-               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
+    } else if (!Arg.get()->isValueDependent() &&
+               !Arg.get()->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
       Diag(NonConstantLoc, diag::err_template_arg_not_ice)
-        << ArgType << Arg->getSourceRange();
+        << ArgType << Arg.get()->getSourceRange();
       return true;
     }
 
@@ -3429,15 +3430,15 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
     } else if (ParamType->isBooleanType()) {
       // This is an integral-to-boolean conversion.
       ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
-    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
+    } else if (IsIntegralPromotion(Arg.get(), ArgType, ParamType) ||
                !ParamType->isEnumeralType()) {
       // This is an integral promotion or conversion.
       ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
     } else {
       // We can't perform this conversion.
-      Diag(Arg->getSourceRange().getBegin(),
+      Diag(Arg.get()->getSourceRange().getBegin(),
            diag::err_template_arg_not_convertible)
-        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
+        << Arg.get()->getType() << InstantiatedParamType << Arg.get()->getSourceRange();
       Diag(Param->getLocation(), diag::note_template_param_here);
       return true;
     }
@@ -3446,7 +3447,7 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
 
-    if (!Arg->isValueDependent()) {
+    if (!Arg.get()->isValueDependent()) {
       llvm::APSInt OldValue = Value;
 
       // Coerce the template argument's value to the value it will have
@@ -3459,9 +3460,9 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
       // Complain if an unsigned parameter received a negative value.
       if (IntegerType->isUnsignedIntegerType()
           && (OldValue.isSigned() && OldValue.isNegative())) {
-        Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
+        Diag(Arg.get()->getSourceRange().getBegin(), diag::warn_template_arg_negative)
           << OldValue.toString(10) << Value.toString(10) << Param->getType()
-          << Arg->getSourceRange();
+          << Arg.get()->getSourceRange();
         Diag(Param->getLocation(), diag::note_template_param_here);
       }
 
@@ -3474,10 +3475,10 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
       else
         RequiredBits = OldValue.getMinSignedBits();
       if (RequiredBits > AllowedBits) {
-        Diag(Arg->getSourceRange().getBegin(),
+        Diag(Arg.get()->getSourceRange().getBegin(),
              diag::warn_template_arg_too_large)
           << OldValue.toString(10) << Value.toString(10) << Param->getType()
-          << Arg->getSourceRange();
+          << Arg.get()->getSourceRange();
         Diag(Param->getLocation(), diag::note_template_param_here);
       }
     }
@@ -3485,10 +3486,10 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
     // Add the value of this argument to the list of converted
     // arguments. We use the bitwidth and signedness of the template
     // parameter.
-    if (Arg->isValueDependent()) {
+    if (Arg.get()->isValueDependent()) {
       // The argument is value-dependent. Create a new
       // TemplateArgument with the converted expression.
-      Converted = TemplateArgument(Arg);
+      Converted = TemplateArgument(Arg.get());
       return false;
     }
 
@@ -3534,15 +3535,15 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
        ParamType->getAs<MemberPointerType>()->getPointeeType()
          ->isFunctionType())) {
 
-    if (Arg->getType() == Context.OverloadTy) {
-      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
+    if (Arg.get()->getType() == Context.OverloadTy) {
+      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg.get(), ParamType,
                                                                 true,
                                                                 FoundResult)) {
-        if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
+        if (DiagnoseUseOfDecl(Fn, Arg.get()->getSourceRange().getBegin()))
           return true;
 
         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
-        ArgType = Arg->getType();
+        ArgType = Arg.get()->getType();
       } else
         return true;
     }
@@ -3550,22 +3551,22 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
     if (!ParamType->isMemberPointerType())
       return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
                                                             ParamType,
-                                                            Arg, Converted);
+                                                            Arg.get(), Converted);
 
     if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
                                   false)) {
-      ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
+      ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg.get()));
     } else if (!Context.hasSameUnqualifiedType(ArgType,
                                            ParamType.getNonReferenceType())) {
       // We can't perform this conversion.
-      Diag(Arg->getSourceRange().getBegin(),
+      Diag(Arg.get()->getSourceRange().getBegin(),
            diag::err_template_arg_not_convertible)
-        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
+        << Arg.get()->getType() << InstantiatedParamType << Arg.get()->getSourceRange();
       Diag(Param->getLocation(), diag::note_template_param_here);
       return true;
     }
 
-    return CheckTemplateArgumentPointerToMember(Arg, Converted);
+    return CheckTemplateArgumentPointerToMember(Arg.get(), Converted);
   }
 
   if (ParamType->isPointerType()) {
@@ -3578,7 +3579,7 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
 
     return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
                                                           ParamType,
-                                                          Arg, Converted);
+                                                          Arg.get(), Converted);
   }
 
   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
@@ -3591,23 +3592,23 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
            "Only object references allowed here");
 
-    if (Arg->getType() == Context.OverloadTy) {
-      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
+    if (Arg.get()->getType() == Context.OverloadTy) {
+      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg.get(),
                                                  ParamRefType->getPointeeType(),
                                                                 true,
                                                                 FoundResult)) {
-        if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
+        if (DiagnoseUseOfDecl(Fn, Arg.get()->getSourceRange().getBegin()))
           return true;
 
         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
-        ArgType = Arg->getType();
+        ArgType = Arg.get()->getType();
       } else
         return true;
     }
 
     return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
                                                           ParamType,
-                                                          Arg, Converted);
+                                                          Arg.get(), Converted);
   }
 
   //     -- For a non-type template-parameter of type pointer to data
@@ -3617,17 +3618,17 @@ bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
   if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
     // Types match exactly: nothing more to do here.
   } else if (IsQualificationConversion(ArgType, ParamType, false)) {
-    ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
+    ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg.get()));
   } else {
     // We can't perform this conversion.
-    Diag(Arg->getSourceRange().getBegin(),
+    Diag(Arg.get()->getSourceRange().getBegin(),
          diag::err_template_arg_not_convertible)
-      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
+      << Arg.get()->getType() << InstantiatedParamType << Arg.get()->getSourceRange();
     Diag(Param->getLocation(), diag::note_template_param_here);
     return true;
   }
 
-  return CheckTemplateArgumentPointerToMember(Arg, Converted);
+  return CheckTemplateArgumentPointerToMember(Arg.get(), Converted);
 }
 
 /// \brief Check a template argument against its corresponding
@@ -3744,12 +3745,9 @@ Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
 
     if (T->isFunctionType() || T->isArrayType()) {
       // Decay functions and arrays.
-      Expr *RefE = (Expr *)RefExpr.get();
-      DefaultFunctionArrayConversion(RefE);
-      if (RefE != RefExpr.get()) {
-        RefExpr.release();
-        RefExpr = Owned(RefE);
-      }
+      DefaultFunctionArrayConversion(RefExpr);
+      if (RefExpr.isInvalid())
+        return ExprError();
 
       return move(RefExpr);
     }
diff --git a/lib/Sema/SemaType.cpp b/lib/Sema/SemaType.cpp
index a9e6392..69e41d0 100644
--- a/lib/Sema/SemaType.cpp
+++ b/lib/Sema/SemaType.cpp
@@ -1108,8 +1108,14 @@ QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
   }
 
   // Do lvalue-to-rvalue conversions on the array size expression.
-  if (ArraySize && !ArraySize->isRValue())
-    DefaultLvalueConversion(ArraySize);
+  if (ArraySize && !ArraySize->isRValue()) {
+    ExprResult Result = Owned(ArraySize);
+    DefaultLvalueConversion(Result);
+    if (Result.isInvalid())
+      return QualType();
+
+    ArraySize = Result.take();
+  }
 
   // C99 6.7.5.2p1: The size expression shall have integer type.
   // TODO: in theory, if we were insane, we could allow contextual
diff --git a/lib/Sema/TreeTransform.h b/lib/Sema/TreeTransform.h
index 9eb7d63..13bec2d 100644
--- a/lib/Sema/TreeTransform.h
+++ b/lib/Sema/TreeTransform.h
@@ -1367,11 +1367,13 @@ public:
       assert(Member->getType()->isRecordType() &&
              "unnamed member not of record type?");
 
-      if (getSema().PerformObjectMemberConversion(Base, 
+      ExprResult BaseResult = getSema().Owned(Base);
+      if (getSema().PerformObjectMemberConversion(BaseResult, 
                                         QualifierLoc.getNestedNameSpecifier(),
-                                                  FoundDecl, Member))
+                                                  FoundDecl, Member) ||
+          BaseResult.isInvalid())
         return ExprError();
-
+      Base = BaseResult.take();
       ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
       MemberExpr *ME =
         new (getSema().Context) MemberExpr(Base, isArrow,
@@ -1384,7 +1386,11 @@ public:
     CXXScopeSpec SS;
     SS.Adopt(QualifierLoc);
 
-    getSema().DefaultFunctionArrayConversion(Base);
+    ExprResult BaseResult = getSema().Owned(Base);
+    getSema().DefaultFunctionArrayConversion(BaseResult);
+    if (BaseResult.isInvalid())
+      return ExprError();
+    Base = BaseResult.take();
     QualType BaseType = Base->getType();
 
     // FIXME: this involves duplicating earlier analysis in a lot of
@@ -2054,20 +2060,20 @@ public:
                                           bool IsArrow, bool IsFreeIvar) {
     // FIXME: We lose track of the IsFreeIvar bit.
     CXXScopeSpec SS;
-    Expr *Base = BaseArg;
+    ExprResult Base = getSema().Owned(BaseArg);
     LookupResult R(getSema(), Ivar->getDeclName(), IvarLoc,
                    Sema::LookupMemberName);
     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
                                                          /*FIME:*/IvarLoc,
                                                          SS, 0,
                                                          false);
-    if (Result.isInvalid())
+    if (Result.isInvalid() || Base.isInvalid())
       return ExprError();
     
     if (Result.get())
       return move(Result);
     
-    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
+    return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
                                               /*FIXME:*/IvarLoc, IsArrow, SS, 
                                               /*FirstQualifierInScope=*/0,
                                               R, 
@@ -2082,20 +2088,20 @@ public:
                                               ObjCPropertyDecl *Property,
                                               SourceLocation PropertyLoc) {
     CXXScopeSpec SS;
-    Expr *Base = BaseArg;
+    ExprResult Base = getSema().Owned(BaseArg);
     LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
                    Sema::LookupMemberName);
     bool IsArrow = false;
     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
                                                          /*FIME:*/PropertyLoc,
                                                          SS, 0, false);
-    if (Result.isInvalid())
+    if (Result.isInvalid() || Base.isInvalid())
       return ExprError();
     
     if (Result.get())
       return move(Result);
     
-    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
+    return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
                                               /*FIXME:*/PropertyLoc, IsArrow, 
                                               SS, 
                                               /*FirstQualifierInScope=*/0,
@@ -2126,19 +2132,19 @@ public:
   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
                                       bool IsArrow) {
     CXXScopeSpec SS;
-    Expr *Base = BaseArg;
+    ExprResult Base = getSema().Owned(BaseArg);
     LookupResult R(getSema(), &getSema().Context.Idents.get("isa"), IsaLoc,
                    Sema::LookupMemberName);
     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
                                                          /*FIME:*/IsaLoc,
                                                          SS, 0, false);
-    if (Result.isInvalid())
+    if (Result.isInvalid() || Base.isInvalid())
       return ExprError();
     
     if (Result.get())
       return move(Result);
     
-    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
+    return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
                                               /*FIXME:*/IsaLoc, IsArrow, SS, 
                                               /*FirstQualifierInScope=*/0,
                                               R, 
@@ -2161,28 +2167,25 @@ public:
 
     // Build a reference to the __builtin_shufflevector builtin
     FunctionDecl *Builtin = cast<FunctionDecl>(*Lookup.first);
-    Expr *Callee
-      = new (SemaRef.Context) DeclRefExpr(Builtin, Builtin->getType(),
-                                          VK_LValue, BuiltinLoc);
+    ExprResult Callee
+      = SemaRef.Owned(new (SemaRef.Context) DeclRefExpr(Builtin, Builtin->getType(),
+                                                        VK_LValue, BuiltinLoc));
     SemaRef.UsualUnaryConversions(Callee);
+    if (Callee.isInvalid())
+      return ExprError();
 
     // Build the CallExpr
     unsigned NumSubExprs = SubExprs.size();
     Expr **Subs = (Expr **)SubExprs.release();
-    CallExpr *TheCall = new (SemaRef.Context) CallExpr(SemaRef.Context, Callee,
+    ExprResult TheCall = SemaRef.Owned(
+      new (SemaRef.Context) CallExpr(SemaRef.Context, Callee.take(),
                                                        Subs, NumSubExprs,
                                                    Builtin->getCallResultType(),
                             Expr::getValueKindForType(Builtin->getResultType()),
-                                                       RParenLoc);
-    ExprResult OwnedCall(SemaRef.Owned(TheCall));
+                                     RParenLoc));
 
     // Type-check the __builtin_shufflevector expression.
-    ExprResult Result = SemaRef.SemaBuiltinShuffleVector(TheCall);
-    if (Result.isInvalid())
-      return ExprError();
-
-    OwnedCall.release();
-    return move(Result);
+    return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.take()));
   }
 
   /// \brief Build a new template argument pack expansion.
-- 
1.7.4.1




More information about the cfe-commits mailing list