<div dir="ltr">It's pretty easy to make this crash<div><br></div><div>$ cat memcpy.c</div><div><div>void foo() {</div><div>  int a[1], b;</div><div>  memcpy((char*)a, (const char*)&b, (unsigned long)4);</div><div>}</div></div><div><br></div><div>$ clang memcpy.c</div><div><div>llvm/include/llvm/ADT/SmallVector.h:178: const_reference llvm::SmallVectorTemplateCommon<clang::APValue::LValuePathEntry, void>::back() const [T = clang::APValue::LValue</div><div>PathEntry]: Assertion `!empty()' failed.</div></div></div><br><div class="gmail_quote"><div dir="ltr">On Wed, Aug 1, 2018 at 1:35 AM Richard Smith via cfe-commits <<a href="mailto:cfe-commits@lists.llvm.org">cfe-commits@lists.llvm.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Author: rsmith<br>
Date: Tue Jul 31 16:35:09 2018<br>
New Revision: 338455<br>
<br>
URL: <a href="http://llvm.org/viewvc/llvm-project?rev=338455&view=rev" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project?rev=338455&view=rev</a><br>
Log:<br>
[constexpr] Support for constant evaluation of __builtin_memcpy and<br>
__builtin_memmove (in non-type-punning cases).<br>
<br>
This is intended to permit libc++ to make std::copy etc constexpr<br>
without sacrificing the optimization that uses memcpy on<br>
trivially-copyable types.<br>
<br>
__builtin_strcpy and __builtin_wcscpy are not handled by this change.<br>
They'd be straightforward to add, but we haven't encountered a need for<br>
them just yet.<br>
<br>
Modified:<br>
    cfe/trunk/include/clang/Basic/Builtins.def<br>
    cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td<br>
    cfe/trunk/lib/AST/ExprConstant.cpp<br>
    cfe/trunk/test/CodeGen/builtin-memfns.c<br>
    cfe/trunk/test/SemaCXX/constexpr-string.cpp<br>
<br>
Modified: cfe/trunk/include/clang/Basic/Builtins.def<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338455&r1=338454&r2=338455&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338455&r1=338454&r2=338455&view=diff</a><br>
==============================================================================<br>
--- cfe/trunk/include/clang/Basic/Builtins.def (original)<br>
+++ cfe/trunk/include/clang/Basic/Builtins.def Tue Jul 31 16:35:09 2018<br>
@@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")<br>
 BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")<br>
 BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")<br>
 BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")<br>
+BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")<br>
+BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")<br>
 BUILTIN(__builtin_return_address, "v*IUi", "n")<br>
 BUILTIN(__builtin_extract_return_addr, "v*v*", "n")<br>
 BUILTIN(__builtin_frame_address, "v*IUi", "n")<br>
@@ -908,6 +910,8 @@ LIBBUILTIN(wcslen,  "zwC*",     "f", "wc<br>
 LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)<br>
 LIBBUILTIN(wmemchr, "w*wC*wz",  "f", "wchar.h", ALL_LANGUAGES)<br>
 LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)<br>
+LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)<br>
+LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)<br>
<br>
 // C99<br>
 // In some systems setjmp is a macro that expands to _setjmp. We undefine<br>
<br>
Modified: cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td?rev=338455&r1=338454&r2=338455&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td?rev=338455&r1=338454&r2=338455&view=diff</a><br>
==============================================================================<br>
--- cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td (original)<br>
+++ cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td Tue Jul 31 16:35:09 2018<br>
@@ -163,6 +163,20 @@ def note_constexpr_unsupported_unsized_a<br>
 def note_constexpr_unsized_array_indexed : Note<<br>
   "indexing of array without known bound is not allowed "<br>
   "in a constant expression">;<br>
+def note_constexpr_memcpy_type_pun : Note<<br>
+  "cannot constant evaluate '%select{memcpy|memmove}0' from object of "<br>
+  "type %1 to object of type %2">;<br>
+def note_constexpr_memcpy_nontrivial : Note<<br>
+  "cannot constant evaluate '%select{memcpy|memmove}0' between objects of "<br>
+  "non-trivially-copyable type %1">;<br>
+def note_constexpr_memcpy_overlap : Note<<br>
+  "'%select{memcpy|wmemcpy}0' between overlapping memory regions">;<br>
+def note_constexpr_memcpy_unsupported : Note<<br>
+  "'%select{%select{memcpy|wmemcpy}1|%select{memmove|wmemmove}1}0' "<br>
+  "not supported: %select{"<br>
+  "size to copy (%4) is not a multiple of size of element type %3 (%5)|"<br>
+  "source is not a contiguous array of at least %4 elements of type %3|"<br>
+  "destination is not a contiguous array of at least %4 elements of type %3}2">;<br>
<br>
 def warn_integer_constant_overflow : Warning<<br>
   "overflow in expression; result is %0 with type %1">,<br>
<br>
Modified: cfe/trunk/lib/AST/ExprConstant.cpp<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=338455&r1=338454&r2=338455&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=338455&r1=338454&r2=338455&view=diff</a><br>
==============================================================================<br>
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)<br>
+++ cfe/trunk/lib/AST/ExprConstant.cpp Tue Jul 31 16:35:09 2018<br>
@@ -319,6 +319,25 @@ namespace {<br>
       return false;<br>
     }<br>
<br>
+    /// Get the range of valid index adjustments in the form<br>
+    ///   {maximum value that can be subtracted from this pointer,<br>
+    ///    maximum value that can be added to this pointer}<br>
+    std::pair<uint64_t, uint64_t> validIndexAdjustments() {<br>
+      if (Invalid || isMostDerivedAnUnsizedArray())<br>
+        return {0, 0};<br>
+<br>
+      // [expr.add]p4: For the purposes of these operators, a pointer to a<br>
+      // nonarray object behaves the same as a pointer to the first element of<br>
+      // an array of length one with the type of the object as its element type.<br>
+      bool IsArray = MostDerivedPathLength == Entries.size() &&<br>
+                     MostDerivedIsArrayElement;<br>
+      uint64_t ArrayIndex =<br>
+          IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;<br>
+      uint64_t ArraySize =<br>
+          IsArray ? getMostDerivedArraySize() : (uint64_t)1;<br>
+      return {ArrayIndex, ArraySize - ArrayIndex};<br>
+    }<br>
+<br>
     /// Check that this refers to a valid subobject.<br>
     bool isValidSubobject() const {<br>
       if (Invalid)<br>
@@ -329,6 +348,13 @@ namespace {<br>
     /// relevant diagnostic and set the designator as invalid.<br>
     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);<br>
<br>
+    /// Get the type of the designated object.<br>
+    QualType getType(ASTContext &Ctx) const {<br>
+      return MostDerivedPathLength == Entries.size()<br>
+                 ? MostDerivedType<br>
+                 : Ctx.getRecordType(getAsBaseClass(Entries.back()));<br>
+    }<br>
+<br>
     /// Update this designator to refer to the first element within this array.<br>
     void addArrayUnchecked(const ConstantArrayType *CAT) {<br>
       PathEntry Entry;<br>
@@ -1706,6 +1732,54 @@ static bool IsGlobalLValue(APValue::LVal<br>
   }<br>
 }<br>
<br>
+static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {<br>
+  return LVal.Base.dyn_cast<const ValueDecl*>();<br>
+}<br>
+<br>
+static bool IsLiteralLValue(const LValue &Value) {<br>
+  if (Value.getLValueCallIndex())<br>
+    return false;<br>
+  const Expr *E = Value.Base.dyn_cast<const Expr*>();<br>
+  return E && !isa<MaterializeTemporaryExpr>(E);<br>
+}<br>
+<br>
+static bool IsWeakLValue(const LValue &Value) {<br>
+  const ValueDecl *Decl = GetLValueBaseDecl(Value);<br>
+  return Decl && Decl->isWeak();<br>
+}<br>
+<br>
+static bool isZeroSized(const LValue &Value) {<br>
+  const ValueDecl *Decl = GetLValueBaseDecl(Value);<br>
+  if (Decl && isa<VarDecl>(Decl)) {<br>
+    QualType Ty = Decl->getType();<br>
+    if (Ty->isArrayType())<br>
+      return Ty->isIncompleteType() ||<br>
+             Decl->getASTContext().getTypeSize(Ty) == 0;<br>
+  }<br>
+  return false;<br>
+}<br>
+<br>
+static bool HasSameBase(const LValue &A, const LValue &B) {<br>
+  if (!A.getLValueBase())<br>
+    return !B.getLValueBase();<br>
+  if (!B.getLValueBase())<br>
+    return false;<br>
+<br>
+  if (A.getLValueBase().getOpaqueValue() !=<br>
+      B.getLValueBase().getOpaqueValue()) {<br>
+    const Decl *ADecl = GetLValueBaseDecl(A);<br>
+    if (!ADecl)<br>
+      return false;<br>
+    const Decl *BDecl = GetLValueBaseDecl(B);<br>
+    if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())<br>
+      return false;<br>
+  }<br>
+<br>
+  return IsGlobalLValue(A.getLValueBase()) ||<br>
+         (A.getLValueCallIndex() == B.getLValueCallIndex() &&<br>
+          A.getLValueVersion() == B.getLValueVersion());<br>
+}<br>
+<br>
 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {<br>
   assert(Base && "no location for a null lvalue");<br>
   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();<br>
@@ -1917,33 +1991,6 @@ CheckConstantExpression(EvalInfo &Info,<br>
   return true;<br>
 }<br>
<br>
-static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {<br>
-  return LVal.Base.dyn_cast<const ValueDecl*>();<br>
-}<br>
-<br>
-static bool IsLiteralLValue(const LValue &Value) {<br>
-  if (Value.getLValueCallIndex())<br>
-    return false;<br>
-  const Expr *E = Value.Base.dyn_cast<const Expr*>();<br>
-  return E && !isa<MaterializeTemporaryExpr>(E);<br>
-}<br>
-<br>
-static bool IsWeakLValue(const LValue &Value) {<br>
-  const ValueDecl *Decl = GetLValueBaseDecl(Value);<br>
-  return Decl && Decl->isWeak();<br>
-}<br>
-<br>
-static bool isZeroSized(const LValue &Value) {<br>
-  const ValueDecl *Decl = GetLValueBaseDecl(Value);<br>
-  if (Decl && isa<VarDecl>(Decl)) {<br>
-    QualType Ty = Decl->getType();<br>
-    if (Ty->isArrayType())<br>
-      return Ty->isIncompleteType() ||<br>
-             Decl->getASTContext().getTypeSize(Ty) == 0;<br>
-  }<br>
-  return false;<br>
-}<br>
-<br>
 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {<br>
   // A null base expression indicates a null pointer.  These are always<br>
   // evaluatable, and they are false unless the offset is zero.<br>
@@ -6117,6 +6164,130 @@ bool PointerExprEvaluator::VisitBuiltinC<br>
     return ZeroInitialization(E);<br>
   }<br>
<br>
+  case Builtin::BImemcpy:<br>
+  case Builtin::BImemmove:<br>
+  case Builtin::BIwmemcpy:<br>
+  case Builtin::BIwmemmove:<br>
+    if (Info.getLangOpts().CPlusPlus11)<br>
+      Info.CCEDiag(E, diag::note_constexpr_invalid_function)<br>
+        << /*isConstexpr*/0 << /*isConstructor*/0<br>
+        << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");<br>
+    else<br>
+      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);<br>
+    LLVM_FALLTHROUGH;<br>
+  case Builtin::BI__builtin_memcpy:<br>
+  case Builtin::BI__builtin_memmove:<br>
+  case Builtin::BI__builtin_wmemcpy:<br>
+  case Builtin::BI__builtin_wmemmove: {<br>
+    bool WChar = BuiltinOp == Builtin::BIwmemcpy ||<br>
+                 BuiltinOp == Builtin::BIwmemmove ||<br>
+                 BuiltinOp == Builtin::BI__builtin_wmemcpy ||<br>
+                 BuiltinOp == Builtin::BI__builtin_wmemmove;<br>
+    bool Move = BuiltinOp == Builtin::BImemmove ||<br>
+                BuiltinOp == Builtin::BIwmemmove ||<br>
+                BuiltinOp == Builtin::BI__builtin_memmove ||<br>
+                BuiltinOp == Builtin::BI__builtin_wmemmove;<br>
+<br>
+    // The result of mem* is the first argument.<br>
+    if (!Visit(E->getArg(0)))<br>
+      return false;<br>
+    LValue Dest = Result;<br>
+<br>
+    LValue Src;<br>
+    if (!EvaluatePointer(E->getArg(1), Src, Info))<br>
+      return false;<br>
+<br>
+    APSInt N;<br>
+    if (!EvaluateInteger(E->getArg(2), N, Info))<br>
+      return false;<br>
+    assert(!N.isSigned() && "memcpy and friends take an unsigned size");<br>
+<br>
+    // If the size is zero, we treat this as always being a valid no-op.<br>
+    // (Even if one of the src and dest pointers is null.)<br>
+    if (!N)<br>
+      return true;<br>
+<br>
+    // We require that Src and Dest are both pointers to arrays of<br>
+    // trivially-copyable type. (For the wide version, the designator will be<br>
+    // invalid if the designated object is not a wchar_t.)<br>
+    QualType T = Dest.Designator.getType(Info.Ctx);<br>
+    QualType SrcT = Src.Designator.getType(Info.Ctx);<br>
+    if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {<br>
+      Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;<br>
+      return false;<br>
+    }<br>
+    if (!T.isTriviallyCopyableType(Info.Ctx)) {<br>
+      Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;<br>
+      return false;<br>
+    }<br>
+<br>
+    // Figure out how many T's we're copying.<br>
+    uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();<br>
+    if (!WChar) {<br>
+      uint64_t Remainder;<br>
+      llvm::APInt OrigN = N;<br>
+      llvm::APInt::udivrem(OrigN, TSize, N, Remainder);<br>
+      if (Remainder) {<br>
+        Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)<br>
+            << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)<br>
+            << (unsigned)TSize;<br>
+        return false;<br>
+      }<br>
+    }<br>
+<br>
+    // Check that the copying will remain within the arrays, just so that we<br>
+    // can give a more meaningful diagnostic. This implicitly also checks that<br>
+    // N fits into 64 bits.<br>
+    uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;<br>
+    uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;<br>
+    if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {<br>
+      Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)<br>
+          << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T<br>
+          << N.toString(10, /*Signed*/false);<br>
+      return false;<br>
+    }<br>
+    uint64_t NElems = N.getZExtValue();<br>
+    uint64_t NBytes = NElems * TSize;<br>
+<br>
+    // Check for overlap.<br>
+    int Direction = 1;<br>
+    if (HasSameBase(Src, Dest)) {<br>
+      uint64_t SrcOffset = Src.getLValueOffset().getQuantity();<br>
+      uint64_t DestOffset = Dest.getLValueOffset().getQuantity();<br>
+      if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {<br>
+        // Dest is inside the source region.<br>
+        if (!Move) {<br>
+          Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;<br>
+          return false;<br>
+        }<br>
+        // For memmove and friends, copy backwards.<br>
+        if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||<br>
+            !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))<br>
+          return false;<br>
+        Direction = -1;<br>
+      } else if (!Move && SrcOffset >= DestOffset &&<br>
+                 SrcOffset - DestOffset < NBytes) {<br>
+        // Src is inside the destination region for memcpy: invalid.<br>
+        Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;<br>
+        return false;<br>
+      }<br>
+    }<br>
+<br>
+    while (true) {<br>
+      APValue Val;<br>
+      if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||<br>
+          !handleAssignment(Info, E, Dest, T, Val))<br>
+        return false;<br>
+      // Do not iterate past the last element; if we're copying backwards, that<br>
+      // might take us off the start of the array.<br>
+      if (--NElems == 0)<br>
+        return true;<br>
+      if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||<br>
+          !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))<br>
+        return false;<br>
+    }<br>
+  }<br>
+<br>
   default:<br>
     return visitNonBuiltinCallExpr(E);<br>
   }<br>
@@ -8357,27 +8528,6 @@ bool IntExprEvaluator::VisitBuiltinCallE<br>
   }<br>
 }<br>
<br>
-static bool HasSameBase(const LValue &A, const LValue &B) {<br>
-  if (!A.getLValueBase())<br>
-    return !B.getLValueBase();<br>
-  if (!B.getLValueBase())<br>
-    return false;<br>
-<br>
-  if (A.getLValueBase().getOpaqueValue() !=<br>
-      B.getLValueBase().getOpaqueValue()) {<br>
-    const Decl *ADecl = GetLValueBaseDecl(A);<br>
-    if (!ADecl)<br>
-      return false;<br>
-    const Decl *BDecl = GetLValueBaseDecl(B);<br>
-    if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())<br>
-      return false;<br>
-  }<br>
-<br>
-  return IsGlobalLValue(A.getLValueBase()) ||<br>
-         (A.getLValueCallIndex() == B.getLValueCallIndex() &&<br>
-          A.getLValueVersion() == B.getLValueVersion());<br>
-}<br>
-<br>
 /// Determine whether this is a pointer past the end of the complete<br>
 /// object referred to by the lvalue.<br>
 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,<br>
<br>
Modified: cfe/trunk/test/CodeGen/builtin-memfns.c<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtin-memfns.c?rev=338455&r1=338454&r2=338455&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtin-memfns.c?rev=338455&r1=338454&r2=338455&view=diff</a><br>
==============================================================================<br>
--- cfe/trunk/test/CodeGen/builtin-memfns.c (original)<br>
+++ cfe/trunk/test/CodeGen/builtin-memfns.c Tue Jul 31 16:35:09 2018<br>
@@ -1,5 +1,8 @@<br>
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm < %s| FileCheck %s<br>
<br>
+typedef __WCHAR_TYPE__ wchar_t;<br>
+typedef __SIZE_TYPE__ size_t;<br>
+<br>
 // CHECK: @test1<br>
 // CHECK: call void @llvm.memset.p0i8.i32<br>
 // CHECK: call void @llvm.memset.p0i8.i32<br>
@@ -83,3 +86,17 @@ void test9() {<br>
   // CHECK: call void @llvm.memcpy{{.*}} align 16 {{.*}} align 16 {{.*}} 16, i1 false)<br>
   __builtin_memcpy(x, y, sizeof(y));<br>
 }<br>
+<br>
+wchar_t dest;<br>
+wchar_t src;<br>
+<br>
+// CHECK-LABEL: @test10<br>
+// FIXME: Consider lowering these to llvm.memcpy / llvm.memmove.<br>
+void test10() {<br>
+  // CHECK: call i32* @wmemcpy(i32* @dest, i32* @src, i32 4)<br>
+  __builtin_wmemcpy(&dest, &src, 4);<br>
+<br>
+  // CHECK: call i32* @wmemmove(i32* @dest, i32* @src, i32 4)<br>
+  __builtin_wmemmove(&dest, &src, 4);<br>
+}<br>
+<br>
<br>
Modified: cfe/trunk/test/SemaCXX/constexpr-string.cpp<br>
URL: <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/constexpr-string.cpp?rev=338455&r1=338454&r2=338455&view=diff" rel="noreferrer" target="_blank">http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/constexpr-string.cpp?rev=338455&r1=338454&r2=338455&view=diff</a><br>
==============================================================================<br>
--- cfe/trunk/test/SemaCXX/constexpr-string.cpp (original)<br>
+++ cfe/trunk/test/SemaCXX/constexpr-string.cpp Tue Jul 31 16:35:09 2018<br>
@@ -1,6 +1,6 @@<br>
-// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic<br>
-// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -fno-signed-char<br>
-// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -fno-wchar -Dwchar_t=__WCHAR_TYPE__<br>
+// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic<br>
+// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic -fno-signed-char<br>
+// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic -fno-wchar -Dwchar_t=__WCHAR_TYPE__<br>
<br>
 # 6 "/usr/include/string.h" 1 3 4<br>
 extern "C" {<br>
@@ -14,10 +14,13 @@ extern "C" {<br>
<br>
   extern char *strchr(const char *s, int c);<br>
   extern void *memchr(const void *s, int c, size_t n);<br>
+<br>
+  extern void *memcpy(void *d, const void *s, size_t n);<br>
+  extern void *memmove(void *d, const void *s, size_t n);<br>
 }<br>
-# 19 "SemaCXX/constexpr-string.cpp" 2<br>
+# 22 "SemaCXX/constexpr-string.cpp" 2<br>
<br>
-# 21 "/usr/include/wchar.h" 1 3 4<br>
+# 24 "/usr/include/wchar.h" 1 3 4<br>
 extern "C" {<br>
   extern size_t wcslen(const wchar_t *p);<br>
<br>
@@ -27,9 +30,12 @@ extern "C" {<br>
<br>
   extern wchar_t *wcschr(const wchar_t *s, wchar_t c);<br>
   extern wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n);<br>
+<br>
+  extern wchar_t *wmemcpy(wchar_t *d, const wchar_t *s, size_t n);<br>
+  extern wchar_t *wmemmove(wchar_t *d, const wchar_t *s, size_t n);<br>
 }<br>
<br>
-# 33 "SemaCXX/constexpr-string.cpp" 2<br>
+# 39 "SemaCXX/constexpr-string.cpp" 2<br>
 namespace Strlen {<br>
   constexpr int n = __builtin_strlen("hello"); // ok<br>
   static_assert(n == 5);<br>
@@ -235,3 +241,133 @@ namespace WcschrEtc {<br>
   constexpr bool a = !wcschr(L"hello", L'h'); // expected-error {{constant expression}} expected-note {{non-constexpr function 'wcschr' cannot be used in a constant expression}}<br>
   constexpr bool b = !wmemchr(L"hello", L'h', 3); // expected-error {{constant expression}} expected-note {{non-constexpr function 'wmemchr' cannot be used in a constant expression}}<br>
 }<br>
+<br>
+namespace MemcpyEtc {<br>
+  template<typename T><br>
+  constexpr T result(T (&arr)[4]) {<br>
+    return arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];<br>
+  }<br>
+<br>
+  constexpr int test_memcpy(int a, int b, int n) {<br>
+    int arr[4] = {1, 2, 3, 4};<br>
+    __builtin_memcpy(arr + a, arr + b, n);<br>
+    // expected-note@-1 2{{overlapping memory regions}}<br>
+    // expected-note@-2 {{size to copy (1) is not a multiple of size of element type 'int'}}<br>
+    // expected-note@-3 {{source is not a contiguous array of at least 2 elements of type 'int'}}<br>
+    // expected-note@-4 {{destination is not a contiguous array of at least 3 elements of type 'int'}}<br>
+    return result(arr);<br>
+  }<br>
+  constexpr int test_memmove(int a, int b, int n) {<br>
+    int arr[4] = {1, 2, 3, 4};<br>
+    __builtin_memmove(arr + a, arr + b, n);<br>
+    // expected-note@-1 {{size to copy (1) is not a multiple of size of element type 'int'}}<br>
+    // expected-note@-2 {{source is not a contiguous array of at least 2 elements of type 'int'}}<br>
+    // expected-note@-3 {{destination is not a contiguous array of at least 3 elements of type 'int'}}<br>
+    return result(arr);<br>
+  }<br>
+  constexpr int test_wmemcpy(int a, int b, int n) {<br>
+    wchar_t arr[4] = {1, 2, 3, 4};<br>
+    __builtin_wmemcpy(arr + a, arr + b, n);<br>
+    // expected-note@-1 2{{overlapping memory regions}}<br>
+    // expected-note-re@-2 {{source is not a contiguous array of at least 2 elements of type '{{wchar_t|int}}'}}<br>
+    // expected-note-re@-3 {{destination is not a contiguous array of at least 3 elements of type '{{wchar_t|int}}'}}<br>
+    return result(arr);<br>
+  }<br>
+  constexpr int test_wmemmove(int a, int b, int n) {<br>
+    wchar_t arr[4] = {1, 2, 3, 4};<br>
+    __builtin_wmemmove(arr + a, arr + b, n);<br>
+    // expected-note-re@-1 {{source is not a contiguous array of at least 2 elements of type '{{wchar_t|int}}'}}<br>
+    // expected-note-re@-2 {{destination is not a contiguous array of at least 3 elements of type '{{wchar_t|int}}'}}<br>
+    return result(arr);<br>
+  }<br>
+<br>
+  static_assert(test_memcpy(1, 2, 4) == 1334);<br>
+  static_assert(test_memcpy(2, 1, 4) == 1224);<br>
+  static_assert(test_memcpy(0, 1, 8) == 2334); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_memcpy(1, 0, 8) == 1124); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_memcpy(1, 2, 1) == 1334); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_memcpy(0, 3, 4) == 4234);<br>
+  static_assert(test_memcpy(0, 3, 8) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_memcpy(2, 0, 12) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+<br>
+  static_assert(test_memmove(1, 2, 4) == 1334);<br>
+  static_assert(test_memmove(2, 1, 4) == 1224);<br>
+  static_assert(test_memmove(0, 1, 8) == 2334);<br>
+  static_assert(test_memmove(1, 0, 8) == 1124);<br>
+  static_assert(test_memmove(1, 2, 1) == 1334); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_memmove(0, 3, 4) == 4234);<br>
+  static_assert(test_memmove(0, 3, 8) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_memmove(2, 0, 12) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+<br>
+  static_assert(test_wmemcpy(1, 2, 1) == 1334);<br>
+  static_assert(test_wmemcpy(2, 1, 1) == 1224);<br>
+  static_assert(test_wmemcpy(0, 1, 2) == 2334); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_wmemcpy(1, 0, 2) == 1124); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_wmemcpy(1, 2, 1) == 1334);<br>
+  static_assert(test_wmemcpy(0, 3, 1) == 4234);<br>
+  static_assert(test_wmemcpy(0, 3, 2) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_wmemcpy(2, 0, 3) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+<br>
+  static_assert(test_wmemmove(1, 2, 1) == 1334);<br>
+  static_assert(test_wmemmove(2, 1, 1) == 1224);<br>
+  static_assert(test_wmemmove(0, 1, 2) == 2334);<br>
+  static_assert(test_wmemmove(1, 0, 2) == 1124);<br>
+  static_assert(test_wmemmove(1, 2, 1) == 1334);<br>
+  static_assert(test_wmemmove(0, 3, 1) == 4234);<br>
+  static_assert(test_wmemmove(0, 3, 2) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+  static_assert(test_wmemmove(2, 0, 3) == 4234); // expected-error {{constant}} expected-note {{in call}}<br>
+<br>
+  // Copying is permitted for any trivially-copyable type.<br>
+  struct Trivial { char k; short s; constexpr bool ok() { return k == 3 && s == 4; } };<br>
+  constexpr bool test_trivial() {<br>
+    Trivial arr[3] = {{1, 2}, {3, 4}, {5, 6}};<br>
+    __builtin_memcpy(arr, arr+1, sizeof(Trivial));<br>
+    __builtin_memmove(arr+1, arr, 2 * sizeof(Trivial));<br>
+    return arr[0].ok() && arr[1].ok() && arr[2].ok();<br>
+  }<br>
+  static_assert(test_trivial());<br>
+<br>
+  // But not for a non-trivially-copyable type.<br>
+  struct NonTrivial {<br>
+    constexpr NonTrivial() : n(0) {}<br>
+    constexpr NonTrivial(const NonTrivial &) : n(1) {}<br>
+    int n;<br>
+  };<br>
+  constexpr bool test_nontrivial_memcpy() { // expected-error {{never produces a constant}}<br>
+    NonTrivial arr[3] = {};<br>
+    __builtin_memcpy(arr, arr + 1, sizeof(NonTrivial)); // expected-note 2{{non-trivially-copyable}}<br>
+    return true;<br>
+  }<br>
+  static_assert(test_nontrivial_memcpy()); // expected-error {{constant}} expected-note {{in call}}<br>
+  constexpr bool test_nontrivial_memmove() { // expected-error {{never produces a constant}}<br>
+    NonTrivial arr[3] = {};<br>
+    __builtin_memcpy(arr, arr + 1, sizeof(NonTrivial)); // expected-note 2{{non-trivially-copyable}}<br>
+    return true;<br>
+  }<br>
+  static_assert(test_nontrivial_memmove()); // expected-error {{constant}} expected-note {{in call}}<br>
+<br>
+  // Type puns via constant evaluated memcpy are not supported yet.<br>
+  constexpr float type_pun(const unsigned &n) {<br>
+    float f = 0.0f;<br>
+    __builtin_memcpy(&f, &n, 4); // expected-note {{cannot constant evaluate 'memcpy' from object of type 'const unsigned int' to object of type 'float'}}<br>
+    return f;<br>
+  }<br>
+  static_assert(type_pun(0x3f800000) == 1.0f); // expected-error {{constant}} expected-note {{in call}}<br>
+<br>
+  // Make sure we're not confused by derived-to-base conversions.<br>
+  struct Base { int a; };<br>
+  struct Derived : Base { int b; };<br>
+  constexpr int test_derived_to_base(int n) {<br>
+    Derived arr[2] = {1, 2, 3, 4};<br>
+    Base *p = &arr[0];<br>
+    Base *q = &arr[1];<br>
+    __builtin_memcpy(p, q, sizeof(Base) * n); // expected-note {{source is not a contiguous array of at least 2 elements of type 'MemcpyEtc::Base'}}<br>
+    return arr[0].a * 1000 + arr[0].b * 100 + arr[1].a * 10 + arr[1].b;<br>
+  }<br>
+  static_assert(test_derived_to_base(0) == 1234);<br>
+  static_assert(test_derived_to_base(1) == 3234);<br>
+  // FIXME: We could consider making this work by stripping elements off both<br>
+  // designators until we have a long enough matching size, if both designators<br>
+  // point to the start of their respective final elements.<br>
+  static_assert(test_derived_to_base(2) == 3434); // expected-error {{constant}} expected-note {{in call}}<br>
+}<br>
<br>
<br>
_______________________________________________<br>
cfe-commits mailing list<br>
<a href="mailto:cfe-commits@lists.llvm.org" target="_blank">cfe-commits@lists.llvm.org</a><br>
<a href="http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits" rel="noreferrer" target="_blank">http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits</a><br>
</blockquote></div>