Skip to content

Commit 8880060

Browse files
committed
DR1213: element access on an array xvalue or prvalue produces an xvalue. In the
latter case, a temporary array object is materialized, and can be lifetime-extended by binding a reference to the member access. Likewise, in an array-to-pointer decay, an rvalue array is materialized before being converted into a pointer. This caused IR generation to stop treating file-scope array compound literals as having static storage duration in some cases in C++; that has been rectified by modeling such a compound literal as an lvalue. This also improves clang's compatibility with GCC for those cases. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@288654 91177308-0d34-0410-b5e6-96231b3b80d8
1 parent 7bf57eb commit 8880060

File tree

13 files changed

+147
-42
lines changed

13 files changed

+147
-42
lines changed

lib/AST/ExprClassification.cpp

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,9 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
141141
return Cl::CL_LValue;
142142

143143
// C99 6.5.2.5p5 says that compound literals are lvalues.
144-
// In C++, they're prvalue temporaries.
144+
// In C++, they're prvalue temporaries, except for file-scope arrays.
145145
case Expr::CompoundLiteralExprClass:
146-
return Ctx.getLangOpts().CPlusPlus ? ClassifyTemporary(E->getType())
147-
: Cl::CL_LValue;
146+
return !E->isLValue() ? ClassifyTemporary(E->getType()) : Cl::CL_LValue;
148147

149148
// Expressions that are prvalues.
150149
case Expr::CXXBoolLiteralExprClass:
@@ -196,11 +195,20 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
196195
return ClassifyInternal(Ctx,
197196
cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
198197

199-
// C++ [expr.sub]p1: The result is an lvalue of type "T".
200-
// However, subscripting vector types is more like member access.
198+
// C, C++98 [expr.sub]p1: The result is an lvalue of type "T".
199+
// C++11 (DR1213): in the case of an array operand, the result is an lvalue
200+
// if that operand is an lvalue and an xvalue otherwise.
201+
// Subscripting vector types is more like member access.
201202
case Expr::ArraySubscriptExprClass:
202203
if (cast<ArraySubscriptExpr>(E)->getBase()->getType()->isVectorType())
203204
return ClassifyInternal(Ctx, cast<ArraySubscriptExpr>(E)->getBase());
205+
if (Lang.CPlusPlus11) {
206+
// Step over the array-to-pointer decay if present, but not over the
207+
// temporary materialization.
208+
auto *Base = cast<ArraySubscriptExpr>(E)->getBase()->IgnoreImpCasts();
209+
if (Base->getType()->isArrayType())
210+
return ClassifyInternal(Ctx, Base);
211+
}
204212
return Cl::CL_LValue;
205213

206214
// C++ [expr.prim.general]p3: The result is an lvalue if the entity is a

lib/AST/ExprConstant.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2907,7 +2907,6 @@ static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
29072907
// In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
29082908
// initializer until now for such expressions. Such an expression can't be
29092909
// an ICE in C, so this only matters for fold.
2910-
assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
29112910
if (Type.isVolatileQualified()) {
29122911
Info.FFDiag(Conv);
29132912
return false;
@@ -4711,7 +4710,7 @@ class LValueExprEvaluatorBase
47114710
// * VarDecl
47124711
// * FunctionDecl
47134712
// - Literals
4714-
// * CompoundLiteralExpr in C
4713+
// * CompoundLiteralExpr in C (and in global scope in C++)
47154714
// * StringLiteral
47164715
// * CXXTypeidExpr
47174716
// * PredefinedExpr
@@ -4906,7 +4905,8 @@ bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
49064905

49074906
bool
49084907
LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4909-
assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4908+
assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
4909+
"lvalue compound literal in c++?");
49104910
// Defer visiting the literal until the lvalue-to-rvalue conversion. We can
49114911
// only see this when folding in C, so there's no standard to follow here.
49124912
return Success(E);

lib/Sema/Sema.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,18 @@ ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
390390
if (ExprTy == TypeTy)
391391
return E;
392392

393+
// C++1z [conv.array]: The temporary materialization conversion is applied.
394+
// We also use this to fuel C++ DR1213, which applies to C++11 onwards.
395+
if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
396+
E->getValueKind() == VK_RValue) {
397+
// The temporary is an lvalue in C++98 and an xvalue otherwise.
398+
ExprResult Materialized = CreateMaterializeTemporaryExpr(
399+
E->getType(), E, !getLangOpts().CPlusPlus11);
400+
if (Materialized.isInvalid())
401+
return ExprError();
402+
E = Materialized.get();
403+
}
404+
393405
if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
394406
if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
395407
ImpCast->setType(Ty);

lib/Sema/SemaExpr.cpp

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4376,6 +4376,16 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
43764376
Expr *LHSExp = Base;
43774377
Expr *RHSExp = Idx;
43784378

4379+
ExprValueKind VK = VK_LValue;
4380+
ExprObjectKind OK = OK_Ordinary;
4381+
4382+
// Per C++ core issue 1213, the result is an xvalue if either operand is
4383+
// a non-lvalue array, and an lvalue otherwise.
4384+
if (getLangOpts().CPlusPlus11 &&
4385+
((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4386+
(RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4387+
VK = VK_XValue;
4388+
43794389
// Perform default conversions.
43804390
if (!LHSExp->getType()->getAs<VectorType>()) {
43814391
ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
@@ -4389,8 +4399,6 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
43894399
RHSExp = Result.get();
43904400

43914401
QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4392-
ExprValueKind VK = VK_LValue;
4393-
ExprObjectKind OK = OK_Ordinary;
43944402

43954403
// C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
43964404
// to the expression *((e1)+(e2)). This means the array "Base" may actually be
@@ -5587,11 +5595,31 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
55875595
}
55885596

55895597
// In C, compound literals are l-values for some reason.
5590-
ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5598+
// For GCC compatibility, in C++, file-scope array compound literals with
5599+
// constant initializers are also l-values, and compound literals are
5600+
// otherwise prvalues.
5601+
//
5602+
// (GCC also treats C++ list-initialized file-scope array prvalues with
5603+
// constant initializers as l-values, but that's non-conforming, so we don't
5604+
// follow it there.)
5605+
//
5606+
// FIXME: It would be better to handle the lvalue cases as materializing and
5607+
// lifetime-extending a temporary object, but our materialized temporaries
5608+
// representation only supports lifetime extension from a variable, not "out
5609+
// of thin air".
5610+
// FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5611+
// is bound to the result of applying array-to-pointer decay to the compound
5612+
// literal.
5613+
// FIXME: GCC supports compound literals of reference type, which should
5614+
// obviously have a value kind derived from the kind of reference involved.
5615+
ExprValueKind VK =
5616+
(getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5617+
? VK_RValue
5618+
: VK_LValue;
55915619

55925620
return MaybeBindToTemporary(
5593-
new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5594-
VK, LiteralExpr, isFileScope));
5621+
new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5622+
VK, LiteralExpr, isFileScope));
55955623
}
55965624

55975625
ExprResult

lib/Sema/SemaInit.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5971,9 +5971,10 @@ performReferenceExtension(Expr *Init,
59715971
if (CE->getSubExpr()->isGLValue())
59725972
Init = CE->getSubExpr();
59735973

5974-
// FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5975-
// It's unclear if binding a reference to that xvalue extends the array
5976-
// temporary.
5974+
// Per the current approach for DR1299, look through array element access
5975+
// when performing lifetime extension.
5976+
if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
5977+
Init = ASE->getBase();
59775978
} while (Init != Old);
59785979

59795980
if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {

lib/StaticAnalyzer/Core/ExprEngineC.cpp

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -480,15 +480,7 @@ void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
480480
Loc CLLoc = State->getLValue(CL, LCtx);
481481
State = State->bindLoc(CLLoc, V);
482482

483-
// Compound literal expressions are a GNU extension in C++.
484-
// Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
485-
// and like temporary objects created by the functional notation T()
486-
// CLs are destroyed at the end of the containing full-expression.
487-
// HOWEVER, an rvalue of array type is not something the analyzer can
488-
// reason about, since we expect all regions to be wrapped in Locs.
489-
// So we treat array CLs as lvalues as well, knowing that they will decay
490-
// to pointers as soon as they are used.
491-
if (CL->isGLValue() || CL->getType()->isArrayType())
483+
if (CL->isGLValue())
492484
V = CLLoc;
493485
}
494486

test/Analysis/explain-svals.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ void test_4(int x, int y) {
7676
clang_analyzer_explain(&stat); // expected-warning-re{{{{^pointer to static local variable 'stat'$}}}}
7777
clang_analyzer_explain(stat_glob); // expected-warning-re{{{{^initial value of global variable 'stat_glob'$}}}}
7878
clang_analyzer_explain(&stat_glob); // expected-warning-re{{{{^pointer to global variable 'stat_glob'$}}}}
79-
clang_analyzer_explain((int[]){1, 2, 3}); // expected-warning-re{{{{^pointer to element of type 'int' with index 0 of compound literal \(int \[3\]\)\{1, 2, 3\}$}}}}
79+
clang_analyzer_explain((int[]){1, 2, 3}); // expected-warning-re{{{{^pointer to element of type 'int' with index 0 of temporary object constructed at statement '\(int \[3\]\)\{1, 2, 3\}'$}}}}
8080
}
8181

8282
namespace {

test/CXX/drs/dr12xx.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@
55

66
// expected-no-diagnostics
77

8+
namespace dr1213 { // dr1213: 4.0
9+
#if __cplusplus >= 201103L
10+
using T = int[3];
11+
int &&r = T{}[1];
12+
13+
using T = decltype((T{}));
14+
using U = decltype((T{}[2]));
15+
using U = int &&;
16+
#endif
17+
}
18+
819
namespace dr1250 { // dr1250: 3.9
920
struct Incomplete;
1021

test/CodeGenCXX/compound-literals.cpp

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ struct Y {
1212
X x;
1313
};
1414

15+
// CHECK: @.compoundliteral = internal global [5 x i32] [i32 1, i32 2, i32 3, i32 4, i32 5], align 4
16+
// CHECK: @q = global i32* getelementptr inbounds ([5 x i32], [5 x i32]* @.compoundliteral, i32 0, i32 0), align 4
17+
1518
// CHECK-LABEL: define i32 @_Z1fv()
1619
int f() {
1720
// CHECK: [[LVALUE:%[a-z0-9.]+]] = alloca
@@ -51,20 +54,27 @@ int *p = (Z){ {1, 2, 3} }.i;
5154
// CHECK: store i32* %{{.*}}, i32** @p
5255

5356
int *q = (int [5]){1, 2, 3, 4, 5};
57+
// (constant initialization, checked above)
58+
59+
extern int n;
60+
int *r = (int [5]){1, 2, 3, 4, 5} + n;
5461
// CHECK-LABEL: define {{.*}}__cxx_global_var_init.1()
55-
// CHECK: store i32* getelementptr inbounds ([5 x i32], [5 x i32]* @.compoundliteral, i32 0, i32 0), i32** @q
62+
// CHECK: %[[PTR:.*]] = getelementptr inbounds i32, i32* getelementptr inbounds ([5 x i32], [5 x i32]* @.compoundliteral.2, i32 0, i32 0), i32 %
63+
// CHECK: store i32* %[[PTR]], i32** @r
5664

57-
int *PR21912_1 = (int []){};
58-
// CHECK-LABEL: define {{.*}}__cxx_global_var_init.2()
59-
// CHECK: store i32* getelementptr inbounds ([0 x i32], [0 x i32]* @.compoundliteral.3, i32 0, i32 0), i32** @PR21912_1
65+
int *PR21912_1 = (int []){} + n;
66+
// CHECK-LABEL: define {{.*}}__cxx_global_var_init.3()
67+
// CHECK: %[[PTR:.*]] = getelementptr inbounds i32, i32* getelementptr inbounds ([0 x i32], [0 x i32]* @.compoundliteral.4, i32 0, i32 0), i32 %
68+
// CHECK: store i32* %[[PTR]], i32** @PR21912_1
6069

6170
union PR21912Ty {
6271
long long l;
6372
double d;
6473
};
65-
union PR21912Ty *PR21912_2 = (union PR21912Ty[]){{.d = 2.0}, {.l = 3}};
66-
// CHECK-LABEL: define {{.*}}__cxx_global_var_init.4()
67-
// CHECK: store %union.PR21912Ty* getelementptr inbounds ([2 x %union.PR21912Ty], [2 x %union.PR21912Ty]* bitcast (<{ { double }, %union.PR21912Ty }>* @.compoundliteral.5 to [2 x %union.PR21912Ty]*), i32 0, i32 0), %union.PR21912Ty** @PR21912_2
74+
union PR21912Ty *PR21912_2 = (union PR21912Ty[]){{.d = 2.0}, {.l = 3}} + n;
75+
// CHECK-LABEL: define {{.*}}__cxx_global_var_init.5()
76+
// CHECK: %[[PTR:.*]] = getelementptr inbounds %union.PR21912Ty, %union.PR21912Ty* getelementptr inbounds ([2 x %union.PR21912Ty], [2 x %union.PR21912Ty]* bitcast (<{ { double }, %union.PR21912Ty }>* @.compoundliteral.6 to [2 x %union.PR21912Ty]*), i32 0, i32 0), i32 %
77+
// CHECK: store %union.PR21912Ty* %[[PTR]], %union.PR21912Ty** @PR21912_2, align 4
6878

6979
// This compound literal should have local scope.
7080
int computed_with_lambda = [] {

test/CodeGenCXX/stack-reuse.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,8 @@ void large_auto_object() {
132132

133133
int large_combiner_test(S_large s) {
134134
// CHECK-LABEL: define i32 @large_combiner_test
135-
// CHECK: [[T1:%.*]] = alloca %struct.Combiner
136135
// CHECK: [[T2:%.*]] = alloca %struct.Combiner
136+
// CHECK: [[T1:%.*]] = alloca %struct.Combiner
137137
// CHECK: [[T3:%.*]] = call %struct.Combiner* @_ZN8CombinerC1E7S_large(%struct.Combiner* nonnull [[T1]], [9 x i32] %s.coerce)
138138
// CHECK: call void @_ZN8Combiner1fEv(%struct.Combiner* nonnull sret [[T2]], %struct.Combiner* nonnull [[T1]])
139139
// CHECK: [[T4:%.*]] = getelementptr inbounds %struct.Combiner, %struct.Combiner* [[T2]], i32 0, i32 0, i32 0, i32 0

test/CodeGenCXX/temporaries.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,36 @@ namespace MultipleExtension {
779779
}
780780
}
781781

782+
namespace ArrayAccess {
783+
struct A { A(int); ~A(); };
784+
void g();
785+
void f() {
786+
using T = A[3];
787+
788+
// CHECK: call void @_ZN11ArrayAccess1AC1Ei({{.*}}, i32 1
789+
// CHECK-NOT: @_ZN11ArrayAccess1AD
790+
// CHECK: call void @_ZN11ArrayAccess1AC1Ei({{.*}}, i32 2
791+
// CHECK-NOT: @_ZN11ArrayAccess1AD
792+
// CHECK: call void @_ZN11ArrayAccess1AC1Ei({{.*}}, i32 3
793+
// CHECK-NOT: @_ZN11ArrayAccess1AD
794+
A &&a = T{1, 2, 3}[1];
795+
796+
// CHECK: call void @_ZN11ArrayAccess1AC1Ei({{.*}}, i32 4
797+
// CHECK-NOT: @_ZN11ArrayAccess1AD
798+
// CHECK: call void @_ZN11ArrayAccess1AC1Ei({{.*}}, i32 5
799+
// CHECK-NOT: @_ZN11ArrayAccess1AD
800+
// CHECK: call void @_ZN11ArrayAccess1AC1Ei({{.*}}, i32 6
801+
// CHECK-NOT: @_ZN11ArrayAccess1AD
802+
A &&b = 2[T{4, 5, 6}];
803+
804+
// CHECK: call void @_ZN11ArrayAccess1gEv(
805+
g();
806+
807+
// CHECK: call void @_ZN11ArrayAccess1AD
808+
// CHECK: call void @_ZN11ArrayAccess1AD
809+
}
810+
}
811+
782812
namespace PR14130 {
783813
struct S { S(int); };
784814
struct U { S &&s; };

test/SemaCXX/constant-expression-cxx11.cpp

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1467,13 +1467,26 @@ namespace VLASizeof {
14671467
}
14681468

14691469
namespace CompoundLiteral {
1470-
// FIXME:
1471-
// We don't model the semantics of this correctly: the compound literal is
1472-
// represented as a prvalue in the AST, but actually behaves like an lvalue.
1473-
// We treat the compound literal as a temporary and refuse to produce a
1474-
// pointer to it. This is OK: we're not required to treat this as a constant
1475-
// in C++, and in C we model compound literals as lvalues.
1476-
constexpr int *p = (int*)(int[1]){0}; // expected-warning {{C99}} expected-error {{constant expression}} expected-note 2{{temporary}}
1470+
// Matching GCC, file-scope array compound literals initialized by constants
1471+
// are lifetime-extended.
1472+
constexpr int *p = (int*)(int[1]){3}; // expected-warning {{C99}}
1473+
static_assert(*p == 3, "");
1474+
static_assert((int[2]){1, 2}[1] == 2, ""); // expected-warning {{C99}}
1475+
1476+
// Other kinds are not.
1477+
struct X { int a[2]; };
1478+
constexpr int *n = (X){1, 2}.a; // expected-warning {{C99}} expected-warning {{temporary array}}
1479+
// expected-error@-1 {{constant expression}}
1480+
// expected-note@-2 {{pointer to subobject of temporary}}
1481+
// expected-note@-3 {{temporary created here}}
1482+
1483+
void f() {
1484+
static constexpr int *p = (int*)(int[1]){3}; // expected-warning {{C99}}
1485+
// expected-error@-1 {{constant expression}}
1486+
// expected-note@-2 {{pointer to subobject of temporary}}
1487+
// expected-note@-3 {{temporary created here}}
1488+
static_assert((int[2]){1, 2}[1] == 2, ""); // expected-warning {{C99}}
1489+
}
14771490
}
14781491

14791492
namespace Vector {

www/cxx_dr_status.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7093,7 +7093,7 @@ <h2 id="cxxdr">C++ defect report implementation status</h2>
70937093
<td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1213">1213</a></td>
70947094
<td>CD3</td>
70957095
<td>Array subscripting and xvalues</td>
7096-
<td class="none" align="center">Unknown</td>
7096+
<td class="svn" align="center">SVN</td>
70977097
</tr>
70987098
<tr id="1214">
70997099
<td><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1214">1214</a></td>

0 commit comments

Comments
 (0)