Add checks and diagnostics for many of the cases which C++11 considers to not
be constant expressions.

llvm-svn: 146479
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3a897ab..dd1110a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -293,11 +293,15 @@
     /// declaration whose initializer is being evaluated, if any.
     APValue *EvaluatingDeclValue;
 
+    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
+    /// notes attached to it will also be stored, otherwise they will not be.
+    bool HasActiveDiagnostic;
+
 
     EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
       : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
         CallStackDepth(0), BottomFrame(*this, 0, 0), EvaluatingDecl(0),
-        EvaluatingDeclValue(0) {}
+        EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
 
     const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
       MapTy::const_iterator i = OpaqueValues.find(e);
@@ -312,33 +316,55 @@
 
     const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
 
-    bool atCallLimit() const {
-      return CallStackDepth > getLangOpts().ConstexprCallDepth;
+    bool CheckCallLimit(SourceLocation Loc) {
+      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
+        return true;
+      Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
+        << getLangOpts().ConstexprCallDepth;
+      return false;
     }
 
+  private:
+    /// Add a diagnostic to the diagnostics list.
+    PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
+      PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
+      EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
+      return EvalStatus.Diag->back().second;
+    }
+
+  public:
     /// Diagnose that the evaluation cannot be folded.
-    OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId) {
+    OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
+                            unsigned ExtraNotes = 0) {
       // If we have a prior diagnostic, it will be noting that the expression
       // isn't a constant expression. This diagnostic is more important.
       // FIXME: We might want to show both diagnostics to the user.
       if (EvalStatus.Diag) {
+        HasActiveDiagnostic = true;
         EvalStatus.Diag->clear();
-        EvalStatus.Diag->reserve(1);
-        PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
-        EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
+        EvalStatus.Diag->reserve(1 + ExtraNotes);
         // FIXME: Add a call stack for constexpr evaluation.
-        return OptionalDiagnostic(&EvalStatus.Diag->back().second);
+        return OptionalDiagnostic(&addDiag(Loc, DiagId));
       }
+      HasActiveDiagnostic = false;
       return OptionalDiagnostic();
     }
 
     /// Diagnose that the evaluation does not produce a C++11 core constant
     /// expression.
-    OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId) {
+    OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
+                               unsigned ExtraNotes = 0) {
       // Don't override a previous diagnostic.
       if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
         return OptionalDiagnostic();
-      return Diag(Loc, DiagId);
+      return Diag(Loc, DiagId, ExtraNotes);
+    }
+
+    /// Add a note to a prior diagnostic.
+    OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
+      if (!HasActiveDiagnostic)
+        return OptionalDiagnostic();
+      return OptionalDiagnostic(&addDiag(Loc, DiagId));
     }
   };
 
@@ -515,11 +541,20 @@
       return castBack(Base);
     }
   };
+
+  /// Kinds of constant expression checking, for diagnostics.
+  enum CheckConstantExpressionKind {
+    CCEK_Constant,    ///< A normal constant.
+    CCEK_ReturnValue, ///< A constexpr function return value.
+    CCEK_MemberInit   ///< A constexpr constructor mem-initializer.
+  };
 }
 
 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
-                                       const LValue &This, const Expr *E);
+                                       const LValue &This, const Expr *E,
+                                       CheckConstantExpressionKind CCEK
+                                        = CCEK_Constant);
 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
@@ -586,22 +621,53 @@
 /// value for a constant expression. Type T should be either LValue or CCValue.
 template<typename T>
 static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
-                                          const T &LVal, APValue &Value) {
-  if (!IsGlobalLValue(LVal.getLValueBase())) {
-    Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
+                                          const T &LVal, APValue &Value,
+                                          CheckConstantExpressionKind CCEK) {
+  APValue::LValueBase Base = LVal.getLValueBase();
+  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
+
+  if (!IsGlobalLValue(Base)) {
+    if (Info.getLangOpts().CPlusPlus0x) {
+      const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
+      Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
+        << E->isGLValue() << !Designator.Entries.empty()
+        << !!VD << CCEK << VD;
+      if (VD)
+        Info.Note(VD->getLocation(), diag::note_declared_at);
+      else
+        Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
+                  diag::note_constexpr_temporary_here);
+    } else {
+      Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
+    }
     return false;
   }
 
-  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
   // A constant expression must refer to an object or be a null pointer.
   if (Designator.Invalid ||
       (!LVal.getLValueBase() && !Designator.Entries.empty())) {
-    // FIXME: This is not a constant expression.
+    // FIXME: This is not a core constant expression. We should have already
+    // produced a CCE diagnostic.
     Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
                     APValue::NoLValuePath());
     return true;
   }
 
+  // Does this refer one past the end of some object?
+  // This is technically not an address constant expression nor a reference
+  // constant expression, but we allow it for address constant expressions.
+  if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
+    const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
+    Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
+      << !Designator.Entries.empty() << !!VD << VD;
+    if (VD)
+      Info.Note(VD->getLocation(), diag::note_declared_at);
+    else
+      Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
+                diag::note_constexpr_temporary_here);
+    return false;
+  }
+
   Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
                   Designator.Entries, Designator.OnePastTheEnd);
   return true;
@@ -611,12 +677,14 @@
 /// constant expression, and if it is, produce the corresponding constant value.
 /// If not, report an appropriate diagnostic.
 static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
-                                    const CCValue &CCValue, APValue &Value) {
+                                    const CCValue &CCValue, APValue &Value,
+                                    CheckConstantExpressionKind CCEK
+                                      = CCEK_Constant) {
   if (!CCValue.isLValue()) {
     Value = CCValue;
     return true;
   }
-  return CheckLValueConstantExpression(Info, E, CCValue, Value);
+  return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
 }
 
 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
@@ -693,26 +761,41 @@
   return HandleConversionToBool(Val, Result);
 }
 
-static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
-                                   APFloat &Value, const ASTContext &Ctx) {
-  unsigned DestWidth = Ctx.getIntWidth(DestType);
+template<typename T>
+static bool HandleOverflow(EvalInfo &Info, const Expr *E,
+                           const T &SrcValue, QualType DestType) {
+  llvm::SmallVector<char, 32> Buffer;
+  SrcValue.toString(Buffer);
+  Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
+    << StringRef(Buffer.data(), Buffer.size()) << DestType;
+  return false;
+}
+
+static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
+                                 QualType SrcType, const APFloat &Value,
+                                 QualType DestType, APSInt &Result) {
+  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
   // Determine whether we are converting to unsigned or signed.
   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
 
-  // FIXME: Warning for overflow.
-  APSInt Result(DestWidth, !DestSigned);
+  Result = APSInt(DestWidth, !DestSigned);
   bool ignored;
-  (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
-  return Result;
+  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
+      & APFloat::opInvalidOp)
+    return HandleOverflow(Info, E, Value, DestType);
+  return true;
 }
 
-static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
-                                      APFloat &Value, const ASTContext &Ctx) {
+static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
+                                   QualType SrcType, QualType DestType,
+                                   APFloat &Result) {
+  APFloat Value = Result;
   bool ignored;
-  APFloat Result = Value;
-  Result.convert(Ctx.getFloatTypeSemantics(DestType),
-                 APFloat::rmNearestTiesToEven, &ignored);
-  return Result;
+  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
+                     APFloat::rmNearestTiesToEven, &ignored)
+      & APFloat::opOverflow)
+    return HandleOverflow(Info, E, Value, DestType);
+  return true;
 }
 
 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
@@ -726,13 +809,15 @@
   return Result;
 }
 
-static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
-                                    APSInt &Value, const ASTContext &Ctx) {
-
-  APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
-  Result.convertFromAPInt(Value, Value.isSigned(),
-                          APFloat::rmNearestTiesToEven);
-  return Result;
+static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
+                                 QualType SrcType, const APSInt &Value,
+                                 QualType DestType, APFloat &Result) {
+  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
+  if (Result.convertFromAPInt(Value, Value.isSigned(),
+                              APFloat::rmNearestTiesToEven)
+      & APFloat::opOverflow)
+    return HandleOverflow(Info, E, Value, DestType);
+  return true;
 }
 
 static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
@@ -1311,7 +1396,7 @@
 }
 
 // Evaluate a statement.
-static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
+static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
                                    const Stmt *S) {
   switch (S->getStmtClass()) {
   default:
@@ -1321,10 +1406,15 @@
   case Stmt::DeclStmtClass:
     return ESR_Succeeded;
 
-  case Stmt::ReturnStmtClass:
-    if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
-      return ESR_Returned;
-    return ESR_Failed;
+  case Stmt::ReturnStmtClass: {
+    CCValue CCResult;
+    const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
+    if (!Evaluate(CCResult, Info, RetExpr) ||
+        !CheckConstantExpression(Info, RetExpr, CCResult, Result,
+                                 CCEK_ReturnValue))
+      return ESR_Failed;
+    return ESR_Returned;
+  }
 
   case Stmt::CompoundStmtClass: {
     const CompoundStmt *CS = cast<CompoundStmt>(S);
@@ -1339,6 +1429,27 @@
   }
 }
 
+/// CheckConstexprFunction - Check that a function can be called in a constant
+/// expression.
+static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
+                                   const FunctionDecl *Declaration,
+                                   const FunctionDecl *Definition) {
+  // Can we evaluate this function call?
+  if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
+    return true;
+
+  if (Info.getLangOpts().CPlusPlus0x) {
+    const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
+    Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
+      << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
+      << DiagDecl;
+    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
+  } else {
+    Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
+  }
+  return false;
+}
+
 namespace {
 typedef SmallVector<CCValue, 8> ArgVector;
 }
@@ -1356,12 +1467,9 @@
 /// Evaluate a function call.
 static bool HandleFunctionCall(const Expr *CallExpr, const LValue *This,
                                ArrayRef<const Expr*> Args, const Stmt *Body,
-                               EvalInfo &Info, CCValue &Result) {
-  if (Info.atCallLimit()) {
-    // FIXME: Add a specific proper diagnostic for this.
-    Info.Diag(CallExpr->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
+                               EvalInfo &Info, APValue &Result) {
+  if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
     return false;
-  }
 
   ArgVector ArgValues(Args.size());
   if (!EvaluateArgs(Args, ArgValues, Info))
@@ -1377,11 +1485,8 @@
                                   const CXXConstructorDecl *Definition,
                                   EvalInfo &Info,
                                   APValue &Result) {
-  if (Info.atCallLimit()) {
-    // FIXME: Add a specific diagnostic for this.
-    Info.Diag(CallExpr->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
+  if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
     return false;
-  }
 
   ArgVector ArgValues(Args.size());
   if (!EvaluateArgs(Args, ArgValues, Info))
@@ -1430,12 +1535,12 @@
       HandleLValueMember(Info, Subobject, FD, &Layout);
       if (RD->isUnion()) {
         Result = APValue(FD);
-        if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
-                                        Subobject, (*I)->getInit()))
+        if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
+                                        (*I)->getInit(), CCEK_MemberInit))
           return false;
       } else if (!EvaluateConstantExpression(
                    Result.getStructField(FD->getFieldIndex()),
-                   Info, Subobject, (*I)->getInit()))
+                   Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
         return false;
     } else {
       // FIXME: handle indirect field initializers
@@ -1745,16 +1850,12 @@
     } else
       return Error(E);
 
-    const FunctionDecl *Definition;
+    const FunctionDecl *Definition = 0;
     Stmt *Body = FD->getBody(Definition);
-    CCValue CCResult;
     APValue Result;
 
-    if (!Body || !Definition->isConstexpr() || Definition->isInvalidDecl())
-      return Error(E);
-
-    if (!HandleFunctionCall(E, This, Args, Body, Info, CCResult) ||
-        !CheckConstantExpression(Info, E, CCResult, Result))
+    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
+        !HandleFunctionCall(E, This, Args, Body, Info, Result))
       return false;
 
     return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
@@ -1878,6 +1979,10 @@
       if (!EvaluatePointer(E->getBase(), Result, this->Info))
         return false;
       BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
+    } else if (E->getBase()->isRValue()) {
+      if (!EvaluateTemporary(E->getBase(), Result, this->Info))
+        return false;
+      BaseTy = E->getBase()->getType();
     } else {
       if (!this->Visit(E->getBase()))
         return false;
@@ -2516,8 +2621,8 @@
   const FunctionDecl *Definition = 0;
   FD->getBody(Definition);
 
-  if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
-    return Error(E);
+  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
+    return false;
 
   // FIXME: Elide the copy/move construction wherever we can.
   if (E->isElidable())
@@ -2837,8 +2942,8 @@
   const FunctionDecl *Definition = 0;
   FD->getBody(Definition);
 
-  if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
-    return Error(E);
+  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
+    return false;
 
   // FIXME: The Subobject here isn't necessarily right. This rarely matters,
   // but sometimes does:
@@ -3881,7 +3986,10 @@
     if (!EvaluateFloat(SubExpr, F, Info))
       return false;
 
-    return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
+    APSInt Value;
+    if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
+      return false;
+    return Success(Value, E);
   }
   }
 
@@ -4130,19 +4238,16 @@
 
   case CK_IntegralToFloating: {
     APSInt IntResult;
-    if (!EvaluateInteger(SubExpr, IntResult, Info))
-      return false;
-    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
-                                  IntResult, Info.Ctx);
-    return true;
+    return EvaluateInteger(SubExpr, IntResult, Info) &&
+           HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
+                                E->getType(), Result);
   }
 
   case CK_FloatingCast: {
     if (!Visit(SubExpr))
       return false;
-    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
-                                    Result, Info.Ctx);
-    return true;
+    return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
+                                  Result);
   }
 
   case CK_FloatingComplexToReal: {
@@ -4289,11 +4394,8 @@
     QualType From
       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
 
-    Result.FloatReal
-      = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
-    Result.FloatImag
-      = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
-    return true;
+    return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
+           HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
   }
 
   case CK_FloatingComplexToIntegralComplex: {
@@ -4304,9 +4406,10 @@
     QualType From
       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
     Result.makeComplexInt();
-    Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
-    Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
-    return true;
+    return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
+                                To, Result.IntReal) &&
+           HandleFloatToIntCast(Info, E, From, Result.FloatImag,
+                                To, Result.IntImag);
   }
 
   case CK_IntegralRealToComplex: {
@@ -4340,9 +4443,10 @@
     QualType From
       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
     Result.makeComplexFloat();
-    Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
-    Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
-    return true;
+    return HandleIntToFloatCast(Info, E, From, Result.IntReal,
+                                To, Result.FloatReal) &&
+           HandleIntToFloatCast(Info, E, From, Result.IntImag,
+                                To, Result.FloatImag);
   }
   }
 
@@ -4581,8 +4685,16 @@
       return false;
     Result = Info.CurrentCall->Temporaries[E];
   } else if (E->getType()->isVoidType()) {
+    if (Info.getLangOpts().CPlusPlus0x)
+      Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
+        << E->getType();
+    else
+      Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
     if (!EvaluateVoid(E, Info))
       return false;
+  } else if (Info.getLangOpts().CPlusPlus0x) {
+    Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
+    return false;
   } else {
     Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
     return false;
@@ -4596,7 +4708,8 @@
 /// since later initializers for an object can indirectly refer to subobjects
 /// which were initialized earlier.
 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
-                                       const LValue &This, const Expr *E) {
+                                       const LValue &This, const Expr *E,
+                                       CheckConstantExpressionKind CCEK) {
   if (E->isRValue() && E->getType()->isLiteralType()) {
     // Evaluate arrays and record types in-place, so that later initializers can
     // refer to earlier-initialized members of the object.
@@ -4609,7 +4722,7 @@
   // For any other type, in-place evaluation is unimportant.
   CCValue CoreConstResult;
   return Evaluate(CoreConstResult, Info, E) &&
-         CheckConstantExpression(Info, E, CoreConstResult, Result);
+         CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
 }
 
 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
@@ -4681,7 +4794,8 @@
 
   LValue LV;
   return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
-         CheckLValueConstantExpression(Info, this, LV, Result.Val);
+         CheckLValueConstantExpression(Info, this, LV, Result.Val,
+                                       CCEK_Constant);
 }
 
 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be