blob: 6fd1d68dcd06cd64853cd0d1cb6904e74803da4b [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000021#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000022#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000025#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000028#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000029#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000030using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000031
Chris Lattner0cb78032009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Chris Lattnerd8b741c82009-02-24 23:10:27 +000036static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000037 const ArrayType *AT = Context.getAsArrayType(DeclType);
38 if (!AT) return 0;
39
Eli Friedman893abe42009-05-29 18:22:49 +000040 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
41 return 0;
42
Chris Lattnera9196812009-02-26 23:26:43 +000043 // See if this is a string literal or @encode.
44 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000045
Chris Lattnera9196812009-02-26 23:26:43 +000046 // Handle @encode, which is a narrow string.
47 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
48 return Init;
49
50 // Otherwise we can only handle string literals.
51 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000052 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000053
54 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000055 // char array can be initialized with a narrow string.
56 // Only allow char x[] = "foo"; not char x[] = L"foo";
57 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000059
Eli Friedman42a84652009-05-31 10:54:53 +000060 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
61 // correction from DR343): "An array with element type compatible with a
62 // qualified or unqualified version of wchar_t may be initialized by a wide
63 // string literal, optionally enclosed in braces."
64 if (Context.typesAreCompatible(Context.getWCharType(),
65 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000066 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner0cb78032009-02-24 22:27:37 +000068 return 0;
69}
70
Chris Lattnerd8b741c82009-02-24 23:10:27 +000071static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
72 // Get the length of the string as parsed.
73 uint64_t StrLength =
74 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
75
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattnerd8b741c82009-02-24 23:10:27 +000077 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000078 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000079 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000080 // being initialized to a string literal.
81 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000082 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000084 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
85 ConstVal,
86 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000087 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000088 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Eli Friedman893abe42009-05-29 18:22:49 +000090 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000091
Eli Friedman893abe42009-05-29 18:22:49 +000092 // C99 6.7.8p14. We have an array of character type with known size. However,
93 // the size may be smaller or larger than the string we are initializing.
94 // FIXME: Avoid truncation for 64-bit length strings.
95 if (StrLength-1 > CAT->getSize().getZExtValue())
96 S.Diag(Str->getSourceRange().getBegin(),
97 diag::warn_initializer_string_for_char_array_too_long)
98 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000099
Eli Friedman893abe42009-05-29 18:22:49 +0000100 // Set the type to the actual size that we are initializing. If we have
101 // something like:
102 // char x[1] = "foo";
103 // then this will set the string literal's type to char[1].
104 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000105}
106
Chris Lattner0cb78032009-02-24 22:27:37 +0000107//===----------------------------------------------------------------------===//
108// Semantic checking for initializer lists.
109//===----------------------------------------------------------------------===//
110
Douglas Gregorcde232f2009-01-29 01:05:33 +0000111/// @brief Semantic checking for initializer lists.
112///
113/// The InitListChecker class contains a set of routines that each
114/// handle the initialization of a certain kind of entity, e.g.,
115/// arrays, vectors, struct/union types, scalars, etc. The
116/// InitListChecker itself performs a recursive walk of the subobject
117/// structure of the type to be initialized, while stepping through
118/// the initializer list one element at a time. The IList and Index
119/// parameters to each of the Check* routines contain the active
120/// (syntactic) initializer list and the index into that initializer
121/// list that represents the current initializer. Each routine is
122/// responsible for moving that Index forward as it consumes elements.
123///
124/// Each Check* routine also has a StructuredList/StructuredIndex
125/// arguments, which contains the current the "structured" (semantic)
126/// initializer list and the index into that initializer list where we
127/// are copying initializers as we map them over to the semantic
128/// list. Once we have completed our recursive walk of the subobject
129/// structure, we will have constructed a full semantic initializer
130/// list.
131///
132/// C99 designators cause changes in the initializer list traversal,
133/// because they make the initialization "jump" into a specific
134/// subobject and then continue the initialization from that
135/// point. CheckDesignatedInitializer() recursively steps into the
136/// designated subobject and manages backing out the recursion to
137/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000138namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000139class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000140 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000141 bool hadError;
142 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
143 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000144
Anders Carlsson6cabf312010-01-23 23:23:01 +0000145 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000146 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000148 unsigned &StructuredIndex,
149 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000150 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000151 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000152 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000153 unsigned &StructuredIndex,
154 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000155 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000156 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000157 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000158 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000159 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000160 unsigned &StructuredIndex,
161 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000162 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000163 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000164 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000165 InitListExpr *StructuredList,
166 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000167 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000168 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000170 InitListExpr *StructuredList,
171 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000172 void CheckReferenceType(const InitializedEntity &Entity,
173 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000174 unsigned &Index,
175 InitListExpr *StructuredList,
176 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000178 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 InitListExpr *StructuredList,
180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000182 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000183 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000184 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000194 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000195 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000196 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000197 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000198 RecordDecl::field_iterator *NextField,
199 llvm::APSInt *NextElementIndex,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000203 bool FinishSubobjectInit,
204 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
206 QualType CurrentObjectType,
207 InitListExpr *StructuredList,
208 unsigned StructuredIndex,
209 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000210 void UpdateStructuredListElement(InitListExpr *StructuredList,
211 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 Expr *expr);
213 int numArrayElements(QualType DeclType);
214 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000215
Douglas Gregor2bb07652009-12-22 00:05:34 +0000216 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
217 const InitializedEntity &ParentEntity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000219 void FillInValueInitializations(const InitializedEntity &Entity,
220 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000221public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000222 InitListChecker(Sema &S, const InitializedEntity &Entity,
223 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 bool HadError() { return hadError; }
225
226 // @brief Retrieves the fully-structured initializer list used for
227 // semantic analysis and code generation.
228 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
229};
Chris Lattner9ececce2009-02-24 22:48:58 +0000230} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000231
Douglas Gregor2bb07652009-12-22 00:05:34 +0000232void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
233 const InitializedEntity &ParentEntity,
234 InitListExpr *ILE,
235 bool &RequiresSecondPass) {
236 SourceLocation Loc = ILE->getSourceRange().getBegin();
237 unsigned NumInits = ILE->getNumInits();
238 InitializedEntity MemberEntity
239 = InitializedEntity::InitializeMember(Field, &ParentEntity);
240 if (Init >= NumInits || !ILE->getInit(Init)) {
241 // FIXME: We probably don't need to handle references
242 // specially here, since value-initialization of references is
243 // handled in InitializationSequence.
244 if (Field->getType()->isReferenceType()) {
245 // C++ [dcl.init.aggr]p9:
246 // If an incomplete or empty initializer-list leaves a
247 // member of reference type uninitialized, the program is
248 // ill-formed.
249 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
250 << Field->getType()
251 << ILE->getSyntacticForm()->getSourceRange();
252 SemaRef.Diag(Field->getLocation(),
253 diag::note_uninit_reference_member);
254 hadError = true;
255 return;
256 }
257
258 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
259 true);
260 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
261 if (!InitSeq) {
262 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
263 hadError = true;
264 return;
265 }
266
John McCalldadc5752010-08-24 06:29:42 +0000267 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000268 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000269 if (MemberInit.isInvalid()) {
270 hadError = true;
271 return;
272 }
273
274 if (hadError) {
275 // Do nothing
276 } else if (Init < NumInits) {
277 ILE->setInit(Init, MemberInit.takeAs<Expr>());
278 } else if (InitSeq.getKind()
279 == InitializationSequence::ConstructorInitialization) {
280 // Value-initialization requires a constructor call, so
281 // extend the initializer list to include the constructor
282 // call and make a note that we'll need to take another pass
283 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000284 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000285 RequiresSecondPass = true;
286 }
287 } else if (InitListExpr *InnerILE
288 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289 FillInValueInitializations(MemberEntity, InnerILE,
290 RequiresSecondPass);
291}
292
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298 InitListExpr *ILE,
299 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000300 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000301 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000302 SourceLocation Loc = ILE->getSourceRange().getBegin();
303 if (ILE->getSyntacticForm())
304 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000306 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000307 if (RType->getDecl()->isUnion() &&
308 ILE->getInitializedFieldInUnion())
309 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310 Entity, ILE, RequiresSecondPass);
311 else {
312 unsigned Init = 0;
313 for (RecordDecl::field_iterator
314 Field = RType->getDecl()->field_begin(),
315 FieldEnd = RType->getDecl()->field_end();
316 Field != FieldEnd; ++Field) {
317 if (Field->isUnnamedBitfield())
318 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000319
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000321 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000322
323 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000328
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329 // Only look at the first initialization of a union.
330 if (RType->getDecl()->isUnion())
331 break;
332 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000333 }
334
335 return;
Mike Stump11289f42009-09-09 15:08:12 +0000336 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000337
338 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Douglas Gregor723796a2009-12-16 06:35:08 +0000340 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000343 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000347 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000349 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000350 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000352 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000354 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor723796a2009-12-16 06:35:08 +0000357
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000359 if (hadError)
360 return;
361
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000362 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000364 ElementEntity.setElementIndex(Init);
365
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000366 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000367 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368 true);
369 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370 if (!InitSeq) {
371 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000372 hadError = true;
373 return;
374 }
375
John McCalldadc5752010-08-24 06:29:42 +0000376 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000377 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000379 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000380 return;
381 }
382
383 if (hadError) {
384 // Do nothing
385 } else if (Init < NumInits) {
386 ILE->setInit(Init, ElementInit.takeAs<Expr>());
387 } else if (InitSeq.getKind()
388 == InitializationSequence::ConstructorInitialization) {
389 // Value-initialization requires a constructor call, so
390 // extend the initializer list to include the constructor
391 // call and make a note that we'll need to take another pass
392 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000393 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000394 RequiresSecondPass = true;
395 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000396 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
398 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000399 }
400}
401
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000402
Douglas Gregor723796a2009-12-16 06:35:08 +0000403InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
404 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000405 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000406 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000407
Eli Friedman23a9e312008-05-19 19:16:24 +0000408 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000409 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000410 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000411 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000412 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000413 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000414 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000415
Douglas Gregor723796a2009-12-16 06:35:08 +0000416 if (!hadError) {
417 bool RequiresSecondPass = false;
418 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000419 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 FillInValueInitializations(Entity, FullyStructuredList,
421 RequiresSecondPass);
422 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000423}
424
425int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000426 // FIXME: use a proper constant
427 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000428 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000429 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000430 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
431 }
432 return maxElements;
433}
434
435int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000436 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000437 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000438 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000439 Field = structDecl->field_begin(),
440 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000441 Field != FieldEnd; ++Field) {
442 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
443 ++InitializableMembers;
444 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000445 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000446 return std::min(InitializableMembers, 1);
447 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000448}
449
Anders Carlsson6cabf312010-01-23 23:23:01 +0000450void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000451 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000452 QualType T, unsigned &Index,
453 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000454 unsigned &StructuredIndex,
455 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000456 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Steve Narofff8ecff22008-05-01 22:18:59 +0000458 if (T->isArrayType())
459 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000460 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000461 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000462 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000463 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000464 else
465 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000466
Eli Friedmane0f832b2008-05-25 13:49:22 +0000467 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000468 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000470 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000471 hadError = true;
472 return;
473 }
474
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000475 // Build a structured initializer list corresponding to this subobject.
476 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000477 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
478 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000479 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
480 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000481 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000482
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000484 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000485 CheckListElementTypes(Entity, ParentIList, T,
486 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000487 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000488 StructuredSubobjectInitIndex,
489 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000490 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000491 StructuredSubobjectInitList->setType(T);
492
Douglas Gregor5741efb2009-03-01 17:12:46 +0000493 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000494 // range corresponds with the end of the last initializer it used.
495 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000496 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000497 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
498 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
499 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000500
501 // Warn about missing braces.
502 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000503 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
504 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000505 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000506 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
507 "{")
508 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000509 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000510 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000511 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000512}
513
Anders Carlsson6cabf312010-01-23 23:23:01 +0000514void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000515 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000516 unsigned &Index,
517 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000518 unsigned &StructuredIndex,
519 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000520 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000521 SyntacticToSemantic[IList] = StructuredList;
522 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000523 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
524 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000525 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
526 IList->setType(ExprTy);
527 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000530
Eli Friedman85f54972008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000540 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000547 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman425038c2009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000563
Chris Lattnerb0912a52009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000566 }
567 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000568
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000571 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000572 << FixItHint::CreateRemoval(IList->getLocStart())
573 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000574}
575
Anders Carlsson6cabf312010-01-23 23:23:01 +0000576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000577 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000578 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000579 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000580 unsigned &Index,
581 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000582 unsigned &StructuredIndex,
583 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000584 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000585 CheckScalarType(Entity, IList, DeclType, Index,
586 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000587 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000588 CheckVectorType(Entity, IList, DeclType, Index,
589 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000590 } else if (DeclType->isAggregateType()) {
591 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000592 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000593 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000594 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 StructuredList, StructuredIndex,
596 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000597 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000598 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000599 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000601 CheckArrayType(Entity, IList, DeclType, Zero,
602 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000603 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000606 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000608 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000610 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000611 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000612 } else if (DeclType->isRecordType()) {
613 // C++ [dcl.init]p14:
614 // [...] If the class is an aggregate (8.5.1), and the initializer
615 // is a brace-enclosed list, see 8.5.1.
616 //
617 // Note: 8.5.1 is handled below; here, we diagnose the case where
618 // we have an initializer list and a destination type that is not
619 // an aggregate.
620 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000622 << DeclType << IList->getSourceRange();
623 hadError = true;
624 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000625 CheckReferenceType(Entity, IList, DeclType, Index,
626 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000627 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000628 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
629 << DeclType;
630 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000631 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000632 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
633 << DeclType;
634 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000635 }
636}
637
Anders Carlsson6cabf312010-01-23 23:23:01 +0000638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000639 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000640 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000641 unsigned &Index,
642 InitListExpr *StructuredList,
643 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000644 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000645 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
646 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000648 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 = getStructuredSubobjectInit(IList, Index, ElemType,
650 StructuredList, StructuredIndex,
651 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000652 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000653 newStructuredList, newStructuredIndex);
654 ++StructuredIndex;
655 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000656 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
657 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000658 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000659 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000660 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000661 CheckScalarType(Entity, IList, ElemType, Index,
662 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000663 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000664 CheckReferenceType(Entity, IList, ElemType, Index,
665 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000666 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000667 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000668 // C++ [dcl.init.aggr]p12:
669 // All implicit type conversions (clause 4) are considered when
670 // initializing the aggregate member with an ini- tializer from
671 // an initializer-list. If the initializer can initialize a
672 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000673
Anders Carlsson0bd52402010-01-24 00:19:41 +0000674 // FIXME: Better EqualLoc?
675 InitializationKind Kind =
676 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
677 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
678
679 if (Seq) {
John McCalldadc5752010-08-24 06:29:42 +0000680 ExprResult Result =
John McCallfaf5fb42010-08-26 23:41:50 +0000681 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson0bd52402010-01-24 00:19:41 +0000682 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000683 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000684
685 UpdateStructuredListElement(StructuredList, StructuredIndex,
686 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000687 ++Index;
688 return;
689 }
690
691 // Fall through for subaggregate initialization
692 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000693 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000694 //
695 // The initializer for a structure or union object that has
696 // automatic storage duration shall be either an initializer
697 // list as described below, or a single expression that has
698 // compatible structure or union type. In the latter case, the
699 // initial value of the object, including unnamed members, is
700 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000701 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000702 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
704 ++Index;
705 return;
706 }
707
708 // Fall through for subaggregate initialization
709 }
710
711 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000712 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000713 // [...] Otherwise, if the member is itself a non-empty
714 // subaggregate, brace elision is assumed and the initializer is
715 // considered for the initialization of the first member of
716 // the subaggregate.
717 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000718 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000719 StructuredIndex);
720 ++StructuredIndex;
721 } else {
722 // We cannot initialize this element, so let
723 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000724 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
725 SemaRef.Owned(expr));
726 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000727 hadError = true;
728 ++Index;
729 ++StructuredIndex;
730 }
731 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000732}
733
Anders Carlsson6cabf312010-01-23 23:23:01 +0000734void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000735 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000736 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000737 InitListExpr *StructuredList,
738 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000739 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000740 Expr *expr = IList->getInit(Index);
Eli Friedmandf239252010-08-14 03:14:53 +0000741 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
742 SemaRef.Diag(SubIList->getLocStart(),
743 diag::warn_many_braces_around_scalar_init)
744 << SubIList->getSourceRange();
745
746 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
747 StructuredIndex);
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000748 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000749 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000750 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000751 diag::err_designator_for_scalar_init)
752 << DeclType << expr->getSourceRange();
753 hadError = true;
754 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000755 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000756 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000757 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000758
John McCalldadc5752010-08-24 06:29:42 +0000759 ExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000760 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
761 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000762
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000763 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000764
765 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000766 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000767 else {
768 ResultExpr = Result.takeAs<Expr>();
769
770 if (ResultExpr != expr) {
771 // The type was promoted, update initializer list.
772 IList->setInit(Index, ResultExpr);
773 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000774 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000775 if (hadError)
776 ++StructuredIndex;
777 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000778 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000779 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000780 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000781 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000782 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000783 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000784 ++Index;
785 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000786 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000787 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000788}
789
Anders Carlsson6cabf312010-01-23 23:23:01 +0000790void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
791 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000792 unsigned &Index,
793 InitListExpr *StructuredList,
794 unsigned &StructuredIndex) {
795 if (Index < IList->getNumInits()) {
796 Expr *expr = IList->getInit(Index);
797 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000798 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000799 << DeclType << IList->getSourceRange();
800 hadError = true;
801 ++Index;
802 ++StructuredIndex;
803 return;
Mike Stump11289f42009-09-09 15:08:12 +0000804 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000805
John McCalldadc5752010-08-24 06:29:42 +0000806 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000807 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
808 SemaRef.Owned(expr));
809
810 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000811 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000812
813 expr = Result.takeAs<Expr>();
814 IList->setInit(Index, expr);
815
Douglas Gregord14247a2009-01-30 22:09:00 +0000816 if (hadError)
817 ++StructuredIndex;
818 else
819 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
820 ++Index;
821 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000822 // FIXME: It would be wonderful if we could point at the actual member. In
823 // general, it would be useful to pass location information down the stack,
824 // so that we know the location (or decl) of the "current object" being
825 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000826 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000827 diag::err_init_reference_member_uninitialized)
828 << DeclType
829 << IList->getSourceRange();
830 hadError = true;
831 ++Index;
832 ++StructuredIndex;
833 return;
834 }
835}
836
Anders Carlsson6cabf312010-01-23 23:23:01 +0000837void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000838 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000839 unsigned &Index,
840 InitListExpr *StructuredList,
841 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000842 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000843 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000844 unsigned maxElements = VT->getNumElements();
845 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000846 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000847
Nate Begeman5ec4b312009-08-10 23:49:36 +0000848 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000849 InitializedEntity ElementEntity =
850 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000851
Anders Carlsson6cabf312010-01-23 23:23:01 +0000852 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
853 // Don't attempt to go past the end of the init list
854 if (Index >= IList->getNumInits())
855 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000856
Anders Carlsson6cabf312010-01-23 23:23:01 +0000857 ElementEntity.setElementIndex(Index);
858 CheckSubElementType(ElementEntity, IList, elementType, Index,
859 StructuredList, StructuredIndex);
860 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000861 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000862 InitializedEntity ElementEntity =
863 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
864
Nate Begeman5ec4b312009-08-10 23:49:36 +0000865 // OpenCL initializers allows vectors to be constructed from vectors.
866 for (unsigned i = 0; i < maxElements; ++i) {
867 // Don't attempt to go past the end of the init list
868 if (Index >= IList->getNumInits())
869 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000870
871 ElementEntity.setElementIndex(Index);
872
Nate Begeman5ec4b312009-08-10 23:49:36 +0000873 QualType IType = IList->getInit(Index)->getType();
874 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000875 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000876 StructuredList, StructuredIndex);
877 ++numEltsInit;
878 } else {
Nate Begeman5da51d32010-07-07 22:26:56 +0000879 QualType VecType;
John McCall9dd450b2009-09-21 23:43:11 +0000880 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000881 unsigned numIElts = IVT->getNumElements();
Nate Begeman5da51d32010-07-07 22:26:56 +0000882
883 if (IType->isExtVectorType())
884 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
885 else
886 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
887 IVT->getAltiVecSpecific());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000888 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000889 StructuredList, StructuredIndex);
890 numEltsInit += numIElts;
891 }
892 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
John Thompson7bc797b2010-04-20 23:21:17 +0000895 // OpenCL requires all elements to be initialized.
Nate Begeman5ec4b312009-08-10 23:49:36 +0000896 if (numEltsInit != maxElements)
Chris Lattnerb596ac72010-04-20 05:19:10 +0000897 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman5ec4b312009-08-10 23:49:36 +0000898 SemaRef.Diag(IList->getSourceRange().getBegin(),
899 diag::err_vector_incorrect_num_initializers)
900 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000901 }
902}
903
Anders Carlsson6cabf312010-01-23 23:23:01 +0000904void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000905 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000906 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000907 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000908 unsigned &Index,
909 InitListExpr *StructuredList,
910 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000911 // Check for the special-case of initializing an array with a string.
912 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000913 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
914 SemaRef.Context)) {
915 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000916 // We place the string literal directly into the resulting
917 // initializer list. This is the only place where the structure
918 // of the structured initializer list doesn't match exactly,
919 // because doing so would involve allocating one character
920 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000921 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000922 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000923 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000924 return;
925 }
926 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000927 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000928 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000929 // Check for VLAs; in standard C it would be possible to check this
930 // earlier, but I don't know where clang accepts VLAs (gcc accepts
931 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000932 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000933 diag::err_variable_object_no_init)
934 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000935 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000936 ++Index;
937 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000938 return;
939 }
940
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000941 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000942 llvm::APSInt maxElements(elementIndex.getBitWidth(),
943 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000944 bool maxElementsKnown = false;
945 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000946 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000947 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000948 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000949 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000950 maxElementsKnown = true;
951 }
952
Chris Lattnerb0912a52009-02-24 22:50:46 +0000953 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000954 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000955 while (Index < IList->getNumInits()) {
956 Expr *Init = IList->getInit(Index);
957 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000958 // If we're not the subobject that matches up with the '{' for
959 // the designator, we shouldn't be handling the
960 // designator. Return immediately.
961 if (!SubobjectIsDesignatorContext)
962 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000963
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000964 // Handle this designated initializer. elementIndex will be
965 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000966 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000967 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000968 StructuredList, StructuredIndex, true,
969 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000970 hadError = true;
971 continue;
972 }
973
Douglas Gregor033d1252009-01-23 16:54:12 +0000974 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
975 maxElements.extend(elementIndex.getBitWidth());
976 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
977 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000978 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000979
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000980 // If the array is of incomplete type, keep track of the number of
981 // elements in the initializer.
982 if (!maxElementsKnown && elementIndex > maxElements)
983 maxElements = elementIndex;
984
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000985 continue;
986 }
987
988 // If we know the maximum number of elements, and we've already
989 // hit it, stop consuming elements in the initializer list.
990 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000991 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000992
Anders Carlsson6cabf312010-01-23 23:23:01 +0000993 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000994 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000995 Entity);
996 // Check this element.
997 CheckSubElementType(ElementEntity, IList, elementType, Index,
998 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000999 ++elementIndex;
1000
1001 // If the array is of incomplete type, keep track of the number of
1002 // elements in the initializer.
1003 if (!maxElementsKnown && elementIndex > maxElements)
1004 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001005 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001006 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001007 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001008 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001009 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001010 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001011 // Sizing an array implicitly to zero is not allowed by ISO C,
1012 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001013 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001014 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001015 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001016
Mike Stump11289f42009-09-09 15:08:12 +00001017 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001018 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001019 }
1020}
1021
Anders Carlsson6cabf312010-01-23 23:23:01 +00001022void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001023 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001024 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001025 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001026 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001027 unsigned &Index,
1028 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001029 unsigned &StructuredIndex,
1030 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001031 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001032
Eli Friedman23a9e312008-05-19 19:16:24 +00001033 // If the record is invalid, some of it's members are invalid. To avoid
1034 // confusion, we forgo checking the intializer for the entire record.
1035 if (structDecl->isInvalidDecl()) {
1036 hadError = true;
1037 return;
Mike Stump11289f42009-09-09 15:08:12 +00001038 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001039
1040 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1041 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001042 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001043 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001044 Field != FieldEnd; ++Field) {
1045 if (Field->getDeclName()) {
1046 StructuredList->setInitializedFieldInUnion(*Field);
1047 break;
1048 }
1049 }
1050 return;
1051 }
1052
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001053 // If structDecl is a forward declaration, this loop won't do
1054 // anything except look at designated initializers; That's okay,
1055 // because an error should get printed out elsewhere. It might be
1056 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001057 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001058 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001059 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001060 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001061 while (Index < IList->getNumInits()) {
1062 Expr *Init = IList->getInit(Index);
1063
1064 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001065 // If we're not the subobject that matches up with the '{' for
1066 // the designator, we shouldn't be handling the
1067 // designator. Return immediately.
1068 if (!SubobjectIsDesignatorContext)
1069 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001070
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001071 // Handle this designated initializer. Field will be updated to
1072 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001073 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001074 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001075 StructuredList, StructuredIndex,
1076 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001077 hadError = true;
1078
Douglas Gregora9add4e2009-02-12 19:00:39 +00001079 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001080
1081 // Disable check for missing fields when designators are used.
1082 // This matches gcc behaviour.
1083 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001084 continue;
1085 }
1086
1087 if (Field == FieldEnd) {
1088 // We've run out of fields. We're done.
1089 break;
1090 }
1091
Douglas Gregora9add4e2009-02-12 19:00:39 +00001092 // We've already initialized a member of a union. We're done.
1093 if (InitializedSomething && DeclType->isUnionType())
1094 break;
1095
Douglas Gregor91f84212008-12-11 16:49:14 +00001096 // If we've hit the flexible array member at the end, we're done.
1097 if (Field->getType()->isIncompleteArrayType())
1098 break;
1099
Douglas Gregor51695702009-01-29 16:53:55 +00001100 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001101 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001102 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001103 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001104 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001105
Anders Carlsson6cabf312010-01-23 23:23:01 +00001106 InitializedEntity MemberEntity =
1107 InitializedEntity::InitializeMember(*Field, &Entity);
1108 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1109 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001110 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001111
1112 if (DeclType->isUnionType()) {
1113 // Initialize the first field within the union.
1114 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001115 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001116
1117 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001118 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001119
John McCalle40b58e2010-03-11 19:32:38 +00001120 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001121 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001122 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1123 // It is possible we have one or more unnamed bitfields remaining.
1124 // Find first (if any) named field and emit warning.
1125 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1126 it != end; ++it) {
1127 if (!it->isUnnamedBitfield()) {
1128 SemaRef.Diag(IList->getSourceRange().getEnd(),
1129 diag::warn_missing_field_initializers) << it->getName();
1130 break;
1131 }
1132 }
1133 }
1134
Mike Stump11289f42009-09-09 15:08:12 +00001135 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001136 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001137 return;
1138
1139 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001140 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001141 (!isa<InitListExpr>(IList->getInit(Index)) ||
1142 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001143 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001144 diag::err_flexible_array_init_nonempty)
1145 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001146 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001147 << *Field;
1148 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001149 ++Index;
1150 return;
1151 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001152 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001153 diag::ext_flexible_array_init)
1154 << IList->getInit(Index)->getSourceRange().getBegin();
1155 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1156 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001157 }
1158
Anders Carlsson6cabf312010-01-23 23:23:01 +00001159 InitializedEntity MemberEntity =
1160 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001161
Anders Carlsson6cabf312010-01-23 23:23:01 +00001162 if (isa<InitListExpr>(IList->getInit(Index)))
1163 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1164 StructuredList, StructuredIndex);
1165 else
1166 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001167 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001168}
Steve Narofff8ecff22008-05-01 22:18:59 +00001169
Douglas Gregord5846a12009-04-15 06:41:24 +00001170/// \brief Expand a field designator that refers to a member of an
1171/// anonymous struct or union into a series of field designators that
1172/// refers to the field within the appropriate subobject.
1173///
1174/// Field/FieldIndex will be updated to point to the (new)
1175/// currently-designated field.
1176static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001177 DesignatedInitExpr *DIE,
1178 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001179 FieldDecl *Field,
1180 RecordDecl::field_iterator &FieldIter,
1181 unsigned &FieldIndex) {
1182 typedef DesignatedInitExpr::Designator Designator;
1183
1184 // Build the path from the current object to the member of the
1185 // anonymous struct/union (backwards).
1186 llvm::SmallVector<FieldDecl *, 4> Path;
1187 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Douglas Gregord5846a12009-04-15 06:41:24 +00001189 // Build the replacement designators.
1190 llvm::SmallVector<Designator, 4> Replacements;
1191 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1192 FI = Path.rbegin(), FIEnd = Path.rend();
1193 FI != FIEnd; ++FI) {
1194 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001195 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001196 DIE->getDesignator(DesigIdx)->getDotLoc(),
1197 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1198 else
1199 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1200 SourceLocation()));
1201 Replacements.back().setField(*FI);
1202 }
1203
1204 // Expand the current designator into the set of replacement
1205 // designators, so we have a full subobject path down to where the
1206 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001207 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001208 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregord5846a12009-04-15 06:41:24 +00001210 // Update FieldIter/FieldIndex;
1211 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001212 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001213 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001214 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001215 FieldIter != FEnd; ++FieldIter) {
1216 if (FieldIter->isUnnamedBitfield())
1217 continue;
1218
1219 if (*FieldIter == Path.back())
1220 return;
1221
1222 ++FieldIndex;
1223 }
1224
1225 assert(false && "Unable to find anonymous struct/union field");
1226}
1227
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001228/// @brief Check the well-formedness of a C99 designated initializer.
1229///
1230/// Determines whether the designated initializer @p DIE, which
1231/// resides at the given @p Index within the initializer list @p
1232/// IList, is well-formed for a current object of type @p DeclType
1233/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001234/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001235/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001236///
1237/// @param IList The initializer list in which this designated
1238/// initializer occurs.
1239///
Douglas Gregora5324162009-04-15 04:56:10 +00001240/// @param DIE The designated initializer expression.
1241///
1242/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001243///
1244/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1245/// into which the designation in @p DIE should refer.
1246///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001247/// @param NextField If non-NULL and the first designator in @p DIE is
1248/// a field, this will be set to the field declaration corresponding
1249/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001250///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001251/// @param NextElementIndex If non-NULL and the first designator in @p
1252/// DIE is an array designator or GNU array-range designator, this
1253/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001254///
1255/// @param Index Index into @p IList where the designated initializer
1256/// @p DIE occurs.
1257///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001258/// @param StructuredList The initializer list expression that
1259/// describes all of the subobject initializers in the order they'll
1260/// actually be initialized.
1261///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001262/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001263bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001264InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001265 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001266 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001267 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001268 QualType &CurrentObjectType,
1269 RecordDecl::field_iterator *NextField,
1270 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001271 unsigned &Index,
1272 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001273 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001274 bool FinishSubobjectInit,
1275 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001276 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001277 // Check the actual initialization for the designated object type.
1278 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001279
1280 // Temporarily remove the designator expression from the
1281 // initializer list that the child calls see, so that we don't try
1282 // to re-process the designator.
1283 unsigned OldIndex = Index;
1284 IList->setInit(OldIndex, DIE->getInit());
1285
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001286 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001287 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001288
1289 // Restore the designated initializer expression in the syntactic
1290 // form of the initializer list.
1291 if (IList->getInit(OldIndex) != DIE->getInit())
1292 DIE->setInit(IList->getInit(OldIndex));
1293 IList->setInit(OldIndex, DIE);
1294
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001295 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001296 }
1297
Douglas Gregora5324162009-04-15 04:56:10 +00001298 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001299 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001300 "Need a non-designated initializer list to start from");
1301
Douglas Gregora5324162009-04-15 04:56:10 +00001302 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001303 // Determine the structural initializer list that corresponds to the
1304 // current subobject.
1305 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001306 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001307 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001308 SourceRange(D->getStartLocation(),
1309 DIE->getSourceRange().getEnd()));
1310 assert(StructuredList && "Expected a structured initializer list");
1311
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 if (D->isFieldDesignator()) {
1313 // C99 6.7.8p7:
1314 //
1315 // If a designator has the form
1316 //
1317 // . identifier
1318 //
1319 // then the current object (defined below) shall have
1320 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001321 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001322 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001323 if (!RT) {
1324 SourceLocation Loc = D->getDotLoc();
1325 if (Loc.isInvalid())
1326 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001327 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1328 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001329 ++Index;
1330 return true;
1331 }
1332
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001333 // Note: we perform a linear search of the fields here, despite
1334 // the fact that we have a faster lookup method, because we always
1335 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001336 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001337 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001338 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001339 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001340 Field = RT->getDecl()->field_begin(),
1341 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001342 for (; Field != FieldEnd; ++Field) {
1343 if (Field->isUnnamedBitfield())
1344 continue;
1345
Douglas Gregord5846a12009-04-15 06:41:24 +00001346 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 break;
1348
1349 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001350 }
1351
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001352 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001353 // There was no normal field in the struct with the designated
1354 // name. Perform another lookup for this name, which may find
1355 // something that we can't designate (e.g., a member function),
1356 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001357 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001358 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001359 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001360 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001361 // Name lookup didn't find anything. Determine whether this
1362 // was a typo for another field name.
1363 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1364 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001365 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1366 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001367 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001368 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001369 ->Equals(RT->getDecl())) {
1370 SemaRef.Diag(D->getFieldLoc(),
1371 diag::err_field_designator_unknown_suggest)
1372 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001373 << FixItHint::CreateReplacement(D->getFieldLoc(),
1374 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001375 SemaRef.Diag(ReplacementField->getLocation(),
1376 diag::note_previous_decl)
1377 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001378 } else {
1379 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1380 << FieldName << CurrentObjectType;
1381 ++Index;
1382 return true;
1383 }
1384 } else if (!KnownField) {
1385 // Determine whether we found a field at all.
1386 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1387 }
1388
1389 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001390 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001391 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001392 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001393 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001395 ++Index;
1396 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001397 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001398
1399 if (!KnownField &&
1400 cast<RecordDecl>((ReplacementField)->getDeclContext())
1401 ->isAnonymousStructOrUnion()) {
1402 // Handle an field designator that refers to a member of an
1403 // anonymous struct or union.
1404 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1405 ReplacementField,
1406 Field, FieldIndex);
1407 D = DIE->getDesignator(DesigIdx);
1408 } else if (!KnownField) {
1409 // The replacement field comes from typo correction; find it
1410 // in the list of fields.
1411 FieldIndex = 0;
1412 Field = RT->getDecl()->field_begin();
1413 for (; Field != FieldEnd; ++Field) {
1414 if (Field->isUnnamedBitfield())
1415 continue;
1416
1417 if (ReplacementField == *Field ||
1418 Field->getIdentifier() == ReplacementField->getIdentifier())
1419 break;
1420
1421 ++FieldIndex;
1422 }
1423 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001424 } else if (!KnownField &&
1425 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001426 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001427 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1428 Field, FieldIndex);
1429 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001430 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001431
1432 // All of the fields of a union are located at the same place in
1433 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001434 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001435 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001436 StructuredList->setInitializedFieldInUnion(*Field);
1437 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001439 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001440 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001442 // Make sure that our non-designated initializer list has space
1443 // for a subobject corresponding to this field.
1444 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001445 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001446
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001447 // This designator names a flexible array member.
1448 if (Field->getType()->isIncompleteArrayType()) {
1449 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001450 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001451 // We can't designate an object within the flexible array
1452 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001453 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001454 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001455 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001457 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001458 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 << *Field;
1461 Invalid = true;
1462 }
1463
1464 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1465 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001466 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001467 diag::err_flexible_array_init_needs_braces)
1468 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001469 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001470 << *Field;
1471 Invalid = true;
1472 }
1473
1474 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001475 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001476 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001477 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001478 diag::err_flexible_array_init_nonempty)
1479 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001480 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001481 << *Field;
1482 Invalid = true;
1483 }
1484
1485 if (Invalid) {
1486 ++Index;
1487 return true;
1488 }
1489
1490 // Initialize the array.
1491 bool prevHadError = hadError;
1492 unsigned newStructuredIndex = FieldIndex;
1493 unsigned OldIndex = Index;
1494 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001495
1496 InitializedEntity MemberEntity =
1497 InitializedEntity::InitializeMember(*Field, &Entity);
1498 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001499 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001500
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001501 IList->setInit(OldIndex, DIE);
1502 if (hadError && !prevHadError) {
1503 ++Field;
1504 ++FieldIndex;
1505 if (NextField)
1506 *NextField = Field;
1507 StructuredIndex = FieldIndex;
1508 return true;
1509 }
1510 } else {
1511 // Recurse to check later designated subobjects.
1512 QualType FieldType = (*Field)->getType();
1513 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001514
1515 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001516 InitializedEntity::InitializeMember(*Field, &Entity);
1517 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001518 FieldType, 0, 0, Index,
1519 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001520 true, false))
1521 return true;
1522 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001523
1524 // Find the position of the next field to be initialized in this
1525 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001527 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001528
1529 // If this the first designator, our caller will continue checking
1530 // the rest of this struct/class/union subobject.
1531 if (IsFirstDesignator) {
1532 if (NextField)
1533 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001534 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001535 return false;
1536 }
1537
Douglas Gregor17bd0942009-01-28 23:36:17 +00001538 if (!FinishSubobjectInit)
1539 return false;
1540
Douglas Gregord5846a12009-04-15 06:41:24 +00001541 // We've already initialized something in the union; we're done.
1542 if (RT->getDecl()->isUnion())
1543 return hadError;
1544
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001545 // Check the remaining fields within this class/struct/union subobject.
1546 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001547
Anders Carlsson6cabf312010-01-23 23:23:01 +00001548 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001549 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001550 return hadError && !prevHadError;
1551 }
1552
1553 // C99 6.7.8p6:
1554 //
1555 // If a designator has the form
1556 //
1557 // [ constant-expression ]
1558 //
1559 // then the current object (defined below) shall have array
1560 // type and the expression shall be an integer constant
1561 // expression. If the array is of unknown size, any
1562 // nonnegative value is valid.
1563 //
1564 // Additionally, cope with the GNU extension that permits
1565 // designators of the form
1566 //
1567 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001568 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001569 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001570 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571 << CurrentObjectType;
1572 ++Index;
1573 return true;
1574 }
1575
1576 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001577 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1578 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001579 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001580 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581 DesignatedEndIndex = DesignatedStartIndex;
1582 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001583 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001584
Mike Stump11289f42009-09-09 15:08:12 +00001585
1586 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001587 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001588 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001589 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001590 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001591
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001592 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001593 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001594 }
1595
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001596 if (isa<ConstantArrayType>(AT)) {
1597 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001598 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1599 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1600 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1601 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1602 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001603 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001604 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001605 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 << IndexExpr->getSourceRange();
1607 ++Index;
1608 return true;
1609 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001610 } else {
1611 // Make sure the bit-widths and signedness match.
1612 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1613 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001614 else if (DesignatedStartIndex.getBitWidth() <
1615 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001616 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1617 DesignatedStartIndex.setIsUnsigned(true);
1618 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619 }
Mike Stump11289f42009-09-09 15:08:12 +00001620
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001621 // Make sure that our non-designated initializer list has space
1622 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001623 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001624 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001625 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001626
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627 // Repeatedly perform subobject initializations in the range
1628 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001629
Douglas Gregor17bd0942009-01-28 23:36:17 +00001630 // Move to the next designator
1631 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1632 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001633
1634 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001635 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001636
Douglas Gregor17bd0942009-01-28 23:36:17 +00001637 while (DesignatedStartIndex <= DesignatedEndIndex) {
1638 // Recurse to check later designated subobjects.
1639 QualType ElementType = AT->getElementType();
1640 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001641
1642 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001643 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001644 ElementType, 0, 0, Index,
1645 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001646 (DesignatedStartIndex == DesignatedEndIndex),
1647 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001648 return true;
1649
1650 // Move to the next index in the array that we'll be initializing.
1651 ++DesignatedStartIndex;
1652 ElementIndex = DesignatedStartIndex.getZExtValue();
1653 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654
1655 // If this the first designator, our caller will continue checking
1656 // the rest of this array subobject.
1657 if (IsFirstDesignator) {
1658 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001659 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001660 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001661 return false;
1662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
Douglas Gregor17bd0942009-01-28 23:36:17 +00001664 if (!FinishSubobjectInit)
1665 return false;
1666
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001667 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001668 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001669 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001670 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001672 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001673}
1674
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001675// Get the structured initializer list for a subobject of type
1676// @p CurrentObjectType.
1677InitListExpr *
1678InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1679 QualType CurrentObjectType,
1680 InitListExpr *StructuredList,
1681 unsigned StructuredIndex,
1682 SourceRange InitRange) {
1683 Expr *ExistingInit = 0;
1684 if (!StructuredList)
1685 ExistingInit = SyntacticToSemantic[IList];
1686 else if (StructuredIndex < StructuredList->getNumInits())
1687 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001688
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1690 return Result;
1691
1692 if (ExistingInit) {
1693 // We are creating an initializer list that initializes the
1694 // subobjects of the current object, but there was already an
1695 // initialization that completely initialized the current
1696 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001697 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001698 // struct X { int a, b; };
1699 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001700 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001701 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1702 // designated initializer re-initializes the whole
1703 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001704 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001705 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001706 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001707 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001708 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001709 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 << ExistingInit->getSourceRange();
1711 }
1712
Mike Stump11289f42009-09-09 15:08:12 +00001713 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001714 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1715 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001716 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001717
Douglas Gregora8a089b2010-07-13 18:40:04 +00001718 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719
Douglas Gregor6d00c992009-03-20 23:58:33 +00001720 // Pre-allocate storage for the structured initializer list.
1721 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001722 unsigned NumInits = 0;
1723 if (!StructuredList)
1724 NumInits = IList->getNumInits();
1725 else if (Index < IList->getNumInits()) {
1726 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1727 NumInits = SubList->getNumInits();
1728 }
1729
Mike Stump11289f42009-09-09 15:08:12 +00001730 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001731 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1732 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1733 NumElements = CAType->getSize().getZExtValue();
1734 // Simple heuristic so that we don't allocate a very large
1735 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001736 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001737 NumElements = 0;
1738 }
John McCall9dd450b2009-09-21 23:43:11 +00001739 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001740 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001741 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001742 RecordDecl *RDecl = RType->getDecl();
1743 if (RDecl->isUnion())
1744 NumElements = 1;
1745 else
Mike Stump11289f42009-09-09 15:08:12 +00001746 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001747 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001748 }
1749
Douglas Gregor221c9a52009-03-21 18:13:52 +00001750 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001751 NumElements = IList->getNumInits();
1752
Ted Kremenekac034612010-04-13 23:39:13 +00001753 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001754
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001755 // Link this new initializer list into the structured initializer
1756 // lists.
1757 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001758 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001759 else {
1760 Result->setSyntacticForm(IList);
1761 SyntacticToSemantic[IList] = Result;
1762 }
1763
1764 return Result;
1765}
1766
1767/// Update the initializer at index @p StructuredIndex within the
1768/// structured initializer list to the value @p expr.
1769void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1770 unsigned &StructuredIndex,
1771 Expr *expr) {
1772 // No structured initializer list to update
1773 if (!StructuredList)
1774 return;
1775
Ted Kremenekac034612010-04-13 23:39:13 +00001776 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1777 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001778 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001779 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780 diag::warn_initializer_overrides)
1781 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001782 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001783 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001784 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001785 << PrevInit->getSourceRange();
1786 }
Mike Stump11289f42009-09-09 15:08:12 +00001787
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001788 ++StructuredIndex;
1789}
1790
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001791/// Check that the given Index expression is a valid array designator
1792/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001793/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001794/// and produces a reasonable diagnostic if there is a
1795/// failure. Returns true if there was an error, false otherwise. If
1796/// everything went okay, Value will receive the value of the constant
1797/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001798static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001799CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001800 SourceLocation Loc = Index->getSourceRange().getBegin();
1801
1802 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001803 if (S.VerifyIntegerConstantExpression(Index, &Value))
1804 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001805
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001806 if (Value.isSigned() && Value.isNegative())
1807 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001808 << Value.toString(10) << Index->getSourceRange();
1809
Douglas Gregor51650d32009-01-23 21:04:18 +00001810 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001811 return false;
1812}
1813
John McCalldadc5752010-08-24 06:29:42 +00001814ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001815 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001816 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001817 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818 typedef DesignatedInitExpr::Designator ASTDesignator;
1819
1820 bool Invalid = false;
1821 llvm::SmallVector<ASTDesignator, 32> Designators;
1822 llvm::SmallVector<Expr *, 32> InitExpressions;
1823
1824 // Build designators and check array designator expressions.
1825 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1826 const Designator &D = Desig.getDesignator(Idx);
1827 switch (D.getKind()) {
1828 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001829 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001830 D.getFieldLoc()));
1831 break;
1832
1833 case Designator::ArrayDesignator: {
1834 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1835 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001836 if (!Index->isTypeDependent() &&
1837 !Index->isValueDependent() &&
1838 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001839 Invalid = true;
1840 else {
1841 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001842 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843 D.getRBracketLoc()));
1844 InitExpressions.push_back(Index);
1845 }
1846 break;
1847 }
1848
1849 case Designator::ArrayRangeDesignator: {
1850 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1851 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1852 llvm::APSInt StartValue;
1853 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001854 bool StartDependent = StartIndex->isTypeDependent() ||
1855 StartIndex->isValueDependent();
1856 bool EndDependent = EndIndex->isTypeDependent() ||
1857 EndIndex->isValueDependent();
1858 if ((!StartDependent &&
1859 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1860 (!EndDependent &&
1861 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001862 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001863 else {
1864 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001865 if (StartDependent || EndDependent) {
1866 // Nothing to compute.
1867 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001868 EndValue.extend(StartValue.getBitWidth());
1869 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1870 StartValue.extend(EndValue.getBitWidth());
1871
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001872 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001873 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001874 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001875 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1876 Invalid = true;
1877 } else {
1878 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001879 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001880 D.getEllipsisLoc(),
1881 D.getRBracketLoc()));
1882 InitExpressions.push_back(StartIndex);
1883 InitExpressions.push_back(EndIndex);
1884 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001885 }
1886 break;
1887 }
1888 }
1889 }
1890
1891 if (Invalid || Init.isInvalid())
1892 return ExprError();
1893
1894 // Clear out the expressions within the designation.
1895 Desig.ClearExprs(*this);
1896
1897 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001898 = DesignatedInitExpr::Create(Context,
1899 Designators.data(), Designators.size(),
1900 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001901 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001902 return Owned(DIE);
1903}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001904
Douglas Gregor723796a2009-12-16 06:35:08 +00001905bool Sema::CheckInitList(const InitializedEntity &Entity,
1906 InitListExpr *&InitList, QualType &DeclType) {
1907 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001908 if (!CheckInitList.HadError())
1909 InitList = CheckInitList.getFullyStructuredList();
1910
1911 return CheckInitList.HadError();
1912}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001913
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001914//===----------------------------------------------------------------------===//
1915// Initialization entity
1916//===----------------------------------------------------------------------===//
1917
Douglas Gregor723796a2009-12-16 06:35:08 +00001918InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1919 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001920 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001921{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001922 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1923 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001924 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001925 } else {
1926 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001927 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001928 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001929}
1930
1931InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001932 CXXBaseSpecifier *Base,
1933 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001934{
1935 InitializedEntity Result;
1936 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001937 Result.Base = reinterpret_cast<uintptr_t>(Base);
1938 if (IsInheritedVirtualBase)
1939 Result.Base |= 0x01;
1940
Douglas Gregor1b303932009-12-22 15:35:07 +00001941 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001942 return Result;
1943}
1944
Douglas Gregor85dabae2009-12-16 01:38:02 +00001945DeclarationName InitializedEntity::getName() const {
1946 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001947 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001948 if (!VariableOrMember)
1949 return DeclarationName();
1950 // Fall through
1951
1952 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001953 case EK_Member:
1954 return VariableOrMember->getDeclName();
1955
1956 case EK_Result:
1957 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001958 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001959 case EK_Temporary:
1960 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001961 case EK_ArrayElement:
1962 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001963 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001964 return DeclarationName();
1965 }
1966
1967 // Silence GCC warning
1968 return DeclarationName();
1969}
1970
Douglas Gregora4b592a2009-12-19 03:01:41 +00001971DeclaratorDecl *InitializedEntity::getDecl() const {
1972 switch (getKind()) {
1973 case EK_Variable:
1974 case EK_Parameter:
1975 case EK_Member:
1976 return VariableOrMember;
1977
1978 case EK_Result:
1979 case EK_Exception:
1980 case EK_New:
1981 case EK_Temporary:
1982 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001983 case EK_ArrayElement:
1984 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001985 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001986 return 0;
1987 }
1988
1989 // Silence GCC warning
1990 return 0;
1991}
1992
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001993bool InitializedEntity::allowsNRVO() const {
1994 switch (getKind()) {
1995 case EK_Result:
1996 case EK_Exception:
1997 return LocAndNRVO.NRVO;
1998
1999 case EK_Variable:
2000 case EK_Parameter:
2001 case EK_Member:
2002 case EK_New:
2003 case EK_Temporary:
2004 case EK_Base:
2005 case EK_ArrayElement:
2006 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002007 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002008 break;
2009 }
2010
2011 return false;
2012}
2013
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002014//===----------------------------------------------------------------------===//
2015// Initialization sequence
2016//===----------------------------------------------------------------------===//
2017
2018void InitializationSequence::Step::Destroy() {
2019 switch (Kind) {
2020 case SK_ResolveAddressOfOverloadedFunction:
2021 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002022 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002023 case SK_CastDerivedToBaseLValue:
2024 case SK_BindReference:
2025 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002026 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002027 case SK_UserConversion:
2028 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002029 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002030 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002031 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002032 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002033 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002034 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002035 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002036 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002037 break;
2038
2039 case SK_ConversionSequence:
2040 delete ICS;
2041 }
2042}
2043
Douglas Gregor838fcc32010-03-26 20:14:36 +00002044bool InitializationSequence::isDirectReferenceBinding() const {
2045 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2046}
2047
2048bool InitializationSequence::isAmbiguous() const {
2049 if (getKind() != FailedSequence)
2050 return false;
2051
2052 switch (getFailureKind()) {
2053 case FK_TooManyInitsForReference:
2054 case FK_ArrayNeedsInitList:
2055 case FK_ArrayNeedsInitListOrStringLiteral:
2056 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2057 case FK_NonConstLValueReferenceBindingToTemporary:
2058 case FK_NonConstLValueReferenceBindingToUnrelated:
2059 case FK_RValueReferenceBindingToLValue:
2060 case FK_ReferenceInitDropsQualifiers:
2061 case FK_ReferenceInitFailed:
2062 case FK_ConversionFailed:
2063 case FK_TooManyInitsForScalar:
2064 case FK_ReferenceBindingToInitList:
2065 case FK_InitListBadDestinationType:
2066 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002067 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002068 return false;
2069
2070 case FK_ReferenceInitOverloadFailed:
2071 case FK_UserConversionOverloadFailed:
2072 case FK_ConstructorOverloadFailed:
2073 return FailedOverloadResult == OR_Ambiguous;
2074 }
2075
2076 return false;
2077}
2078
Douglas Gregorb33eed02010-04-16 22:09:46 +00002079bool InitializationSequence::isConstructorInitialization() const {
2080 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2081}
2082
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002083void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002084 FunctionDecl *Function,
2085 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002086 Step S;
2087 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2088 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002089 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002090 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002091 Steps.push_back(S);
2092}
2093
2094void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002095 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002096 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002097 switch (VK) {
2098 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2099 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2100 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002101 default: llvm_unreachable("No such category");
2102 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002103 S.Type = BaseType;
2104 Steps.push_back(S);
2105}
2106
2107void InitializationSequence::AddReferenceBindingStep(QualType T,
2108 bool BindingTemporary) {
2109 Step S;
2110 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2111 S.Type = T;
2112 Steps.push_back(S);
2113}
2114
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002115void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2116 Step S;
2117 S.Kind = SK_ExtraneousCopyToTemporary;
2118 S.Type = T;
2119 Steps.push_back(S);
2120}
2121
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002122void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002123 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002124 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002125 Step S;
2126 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002127 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002128 S.Function.Function = Function;
2129 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002130 Steps.push_back(S);
2131}
2132
2133void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002134 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002135 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002136 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002137 switch (VK) {
2138 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002139 S.Kind = SK_QualificationConversionRValue;
2140 break;
John McCall2536c6d2010-08-25 10:28:54 +00002141 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002142 S.Kind = SK_QualificationConversionXValue;
2143 break;
John McCall2536c6d2010-08-25 10:28:54 +00002144 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002145 S.Kind = SK_QualificationConversionLValue;
2146 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002147 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002148 S.Type = Ty;
2149 Steps.push_back(S);
2150}
2151
2152void InitializationSequence::AddConversionSequenceStep(
2153 const ImplicitConversionSequence &ICS,
2154 QualType T) {
2155 Step S;
2156 S.Kind = SK_ConversionSequence;
2157 S.Type = T;
2158 S.ICS = new ImplicitConversionSequence(ICS);
2159 Steps.push_back(S);
2160}
2161
Douglas Gregor51e77d52009-12-10 17:56:55 +00002162void InitializationSequence::AddListInitializationStep(QualType T) {
2163 Step S;
2164 S.Kind = SK_ListInitialization;
2165 S.Type = T;
2166 Steps.push_back(S);
2167}
2168
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002169void
2170InitializationSequence::AddConstructorInitializationStep(
2171 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002172 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002173 QualType T) {
2174 Step S;
2175 S.Kind = SK_ConstructorInitialization;
2176 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002177 S.Function.Function = Constructor;
2178 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002179 Steps.push_back(S);
2180}
2181
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002182void InitializationSequence::AddZeroInitializationStep(QualType T) {
2183 Step S;
2184 S.Kind = SK_ZeroInitialization;
2185 S.Type = T;
2186 Steps.push_back(S);
2187}
2188
Douglas Gregore1314a62009-12-18 05:02:21 +00002189void InitializationSequence::AddCAssignmentStep(QualType T) {
2190 Step S;
2191 S.Kind = SK_CAssignment;
2192 S.Type = T;
2193 Steps.push_back(S);
2194}
2195
Eli Friedman78275202009-12-19 08:11:05 +00002196void InitializationSequence::AddStringInitStep(QualType T) {
2197 Step S;
2198 S.Kind = SK_StringInit;
2199 S.Type = T;
2200 Steps.push_back(S);
2201}
2202
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002203void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2204 Step S;
2205 S.Kind = SK_ObjCObjectConversion;
2206 S.Type = T;
2207 Steps.push_back(S);
2208}
2209
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002210void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2211 OverloadingResult Result) {
2212 SequenceKind = FailedSequence;
2213 this->Failure = Failure;
2214 this->FailedOverloadResult = Result;
2215}
2216
2217//===----------------------------------------------------------------------===//
2218// Attempt initialization
2219//===----------------------------------------------------------------------===//
2220
2221/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002222static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002223 const InitializedEntity &Entity,
2224 const InitializationKind &Kind,
2225 InitListExpr *InitList,
2226 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002227 // FIXME: We only perform rudimentary checking of list
2228 // initializations at this point, then assume that any list
2229 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002230 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002231 // do all of the necessary checking. C++0x initializer lists will
2232 // force us to perform more checking here.
2233 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2234
Douglas Gregor1b303932009-12-22 15:35:07 +00002235 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002236
2237 // C++ [dcl.init]p13:
2238 // If T is a scalar type, then a declaration of the form
2239 //
2240 // T x = { a };
2241 //
2242 // is equivalent to
2243 //
2244 // T x = a;
2245 if (DestType->isScalarType()) {
2246 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2247 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2248 return;
2249 }
2250
2251 // Assume scalar initialization from a single value works.
2252 } else if (DestType->isAggregateType()) {
2253 // Assume aggregate initialization works.
2254 } else if (DestType->isVectorType()) {
2255 // Assume vector initialization works.
2256 } else if (DestType->isReferenceType()) {
2257 // FIXME: C++0x defines behavior for this.
2258 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2259 return;
2260 } else if (DestType->isRecordType()) {
2261 // FIXME: C++0x defines behavior for this
2262 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2263 }
2264
2265 // Add a general "list initialization" step.
2266 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002267}
2268
2269/// \brief Try a reference initialization that involves calling a conversion
2270/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002271static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2272 const InitializedEntity &Entity,
2273 const InitializationKind &Kind,
2274 Expr *Initializer,
2275 bool AllowRValues,
2276 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002277 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002278 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2279 QualType T1 = cv1T1.getUnqualifiedType();
2280 QualType cv2T2 = Initializer->getType();
2281 QualType T2 = cv2T2.getUnqualifiedType();
2282
2283 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002284 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002285 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002286 T1, T2, DerivedToBase,
2287 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002288 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002289 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002290 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002291
2292 // Build the candidate set directly in the initialization sequence
2293 // structure, so that it will persist if we fail.
2294 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2295 CandidateSet.clear();
2296
2297 // Determine whether we are allowed to call explicit constructors or
2298 // explicit conversion operators.
2299 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2300
2301 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002302 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2303 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002304 // The type we're converting to is a class type. Enumerate its constructors
2305 // to see if there is a suitable conversion.
2306 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002307
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002308 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002309 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002311 NamedDecl *D = *Con;
2312 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2313
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002314 // Find the constructor (which may be a template).
2315 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002316 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 if (ConstructorTmpl)
2318 Constructor = cast<CXXConstructorDecl>(
2319 ConstructorTmpl->getTemplatedDecl());
2320 else
John McCalla0296f72010-03-19 07:35:19 +00002321 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002322
2323 if (!Constructor->isInvalidDecl() &&
2324 Constructor->isConvertingConstructor(AllowExplicit)) {
2325 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002326 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002327 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002328 &Initializer, 1, CandidateSet,
2329 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002330 else
John McCalla0296f72010-03-19 07:35:19 +00002331 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002332 &Initializer, 1, CandidateSet,
2333 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002334 }
2335 }
2336 }
John McCall3696dcb2010-08-17 07:23:57 +00002337 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2338 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002339
Douglas Gregor496e8b342010-05-07 19:42:26 +00002340 const RecordType *T2RecordType = 0;
2341 if ((T2RecordType = T2->getAs<RecordType>()) &&
2342 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002343 // The type we're converting from is a class type, enumerate its conversion
2344 // functions.
2345 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2346
2347 // Determine the type we are converting to. If we are allowed to
2348 // convert to an rvalue, take the type that the destination type
2349 // refers to.
2350 QualType ToType = AllowRValues? cv1T1 : DestType;
2351
John McCallad371252010-01-20 00:46:10 +00002352 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002354 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2355 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002356 NamedDecl *D = *I;
2357 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2358 if (isa<UsingShadowDecl>(D))
2359 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2360
2361 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2362 CXXConversionDecl *Conv;
2363 if (ConvTemplate)
2364 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2365 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002366 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002367
2368 // If the conversion function doesn't return a reference type,
2369 // it can't be considered for this conversion unless we're allowed to
2370 // consider rvalues.
2371 // FIXME: Do we need to make sure that we only consider conversion
2372 // candidates with reference-compatible results? That might be needed to
2373 // break recursion.
2374 if ((AllowExplicit || !Conv->isExplicit()) &&
2375 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2376 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002377 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002378 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002379 ToType, CandidateSet);
2380 else
John McCalla0296f72010-03-19 07:35:19 +00002381 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002382 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383 }
2384 }
2385 }
John McCall3696dcb2010-08-17 07:23:57 +00002386 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2387 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002388
2389 SourceLocation DeclLoc = Initializer->getLocStart();
2390
2391 // Perform overload resolution. If it fails, return the failed result.
2392 OverloadCandidateSet::iterator Best;
2393 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002394 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002395 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002396
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002398
2399 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002400 if (isa<CXXConversionDecl>(Function))
2401 T2 = Function->getResultType();
2402 else
2403 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002404
2405 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002406 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002407 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002408
2409 // Determine whether we need to perform derived-to-base or
2410 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002411 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002412 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002413 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002414 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002415 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002416
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002417 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002418 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002420 = S.CompareReferenceRelationship(DeclLoc, T1,
2421 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002422 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002423 if (NewRefRelationship == Sema::Ref_Incompatible) {
2424 // If the type we've converted to is not reference-related to the
2425 // type we're looking for, then there is another conversion step
2426 // we need to perform to produce a temporary of the right type
2427 // that we'll be binding to.
2428 ImplicitConversionSequence ICS;
2429 ICS.setStandard();
2430 ICS.Standard = Best->FinalConversion;
2431 T2 = ICS.Standard.getToType(2);
2432 Sequence.AddConversionSequenceStep(ICS, T2);
2433 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002434 Sequence.AddDerivedToBaseCastStep(
2435 S.Context.getQualifiedType(T1,
2436 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002437 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002438 else if (NewObjCConversion)
2439 Sequence.AddObjCObjectConversionStep(
2440 S.Context.getQualifiedType(T1,
2441 T2.getNonReferenceType().getQualifiers()));
2442
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002443 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002444 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445
2446 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2447 return OR_Success;
2448}
2449
Sebastian Redld92badf2010-06-30 18:13:39 +00002450/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002451static void TryReferenceInitialization(Sema &S,
2452 const InitializedEntity &Entity,
2453 const InitializationKind &Kind,
2454 Expr *Initializer,
2455 InitializationSequence &Sequence) {
2456 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002457
Douglas Gregor1b303932009-12-22 15:35:07 +00002458 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002459 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002460 Qualifiers T1Quals;
2461 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002462 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002463 Qualifiers T2Quals;
2464 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002465 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002466
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002467 // If the initializer is the address of an overloaded function, try
2468 // to resolve the overloaded function. If all goes well, T2 is the
2469 // type of the resulting function.
2470 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002471 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002472 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2473 T1,
John McCall16df1e52010-03-30 21:47:33 +00002474 false,
2475 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002476 if (!Fn) {
2477 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2478 return;
2479 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002480
John McCall16df1e52010-03-30 21:47:33 +00002481 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002482 cv2T2 = Fn->getType();
2483 T2 = cv2T2.getUnqualifiedType();
2484 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002486 // Compute some basic properties of the types and the initializer.
2487 bool isLValueRef = DestType->isLValueReferenceType();
2488 bool isRValueRef = !isLValueRef;
2489 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002490 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002491 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002492 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002493 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2494 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002495
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002496 // C++0x [dcl.init.ref]p5:
2497 // A reference to type "cv1 T1" is initialized by an expression of type
2498 // "cv2 T2" as follows:
2499 //
2500 // - If the reference is an lvalue reference and the initializer
2501 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002502 // Note the analogous bullet points for rvlaue refs to functions. Because
2503 // there are no function rvalues in C++, rvalue refs to functions are treated
2504 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002506 bool T1Function = T1->isFunctionType();
2507 if (isLValueRef || T1Function) {
2508 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002509 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2510 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2511 // reference-compatible with "cv2 T2," or
2512 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002513 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002514 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002515 // can occur. However, we do pay attention to whether it is a bit-field
2516 // to decide whether we're actually binding to a temporary created from
2517 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 if (DerivedToBase)
2519 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002520 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002521 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002522 else if (ObjCConversion)
2523 Sequence.AddObjCObjectConversionStep(
2524 S.Context.getQualifiedType(T1, T2Quals));
2525
Chandler Carruth04bdce62010-01-12 20:32:25 +00002526 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002527 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002528 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002529 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002530 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002531 return;
2532 }
2533
2534 // - has a class type (i.e., T2 is a class type), where T1 is not
2535 // reference-related to T2, and can be implicitly converted to an
2536 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2537 // with "cv3 T3" (this conversion is selected by enumerating the
2538 // applicable conversion functions (13.3.1.6) and choosing the best
2539 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002540 // If we have an rvalue ref to function type here, the rhs must be
2541 // an rvalue.
2542 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2543 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002544 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2545 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002546 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002547 Sequence);
2548 if (ConvOvlResult == OR_Success)
2549 return;
John McCall0d1da222010-01-12 00:44:57 +00002550 if (ConvOvlResult != OR_No_Viable_Function) {
2551 Sequence.SetOverloadFailure(
2552 InitializationSequence::FK_ReferenceInitOverloadFailed,
2553 ConvOvlResult);
2554 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 }
2556 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002557
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002558 // - Otherwise, the reference shall be an lvalue reference to a
2559 // non-volatile const type (i.e., cv1 shall be const), or the reference
2560 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002561 // be an rvalue or have a function type.
2562 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002563 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002564 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002565 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2566 Sequence.SetOverloadFailure(
2567 InitializationSequence::FK_ReferenceInitOverloadFailed,
2568 ConvOvlResult);
2569 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002570 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002571 ? (RefRelationship == Sema::Ref_Related
2572 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2573 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2574 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2575 else
2576 Sequence.SetFailed(
2577 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002578
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002579 return;
2580 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002581
2582 // - [If T1 is not a function type], if T2 is a class type and
2583 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002584 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002585 // - the initializer expression is an rvalue and "cv1 T1" is
2586 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002587 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002589 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2590 // compiler the freedom to perform a copy here or bind to the
2591 // object, while C++0x requires that we bind directly to the
2592 // object. Hence, we always bind to the object without making an
2593 // extra copy. However, in C++03 requires that we check for the
2594 // presence of a suitable copy constructor:
2595 //
2596 // The constructor that would be used to make the copy shall
2597 // be callable whether or not the copy is actually done.
2598 if (!S.getLangOptions().CPlusPlus0x)
2599 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2600
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002601 if (DerivedToBase)
2602 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002603 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002604 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002605 else if (ObjCConversion)
2606 Sequence.AddObjCObjectConversionStep(
2607 S.Context.getQualifiedType(T1, T2Quals));
2608
Chandler Carruth04bdce62010-01-12 20:32:25 +00002609 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002610 Sequence.AddQualificationConversionStep(cv1T1,
John McCall2536c6d2010-08-25 10:28:54 +00002611 isXValue ? VK_XValue : VK_RValue);
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002612 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002613 return;
2614 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002615
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002616 // - T1 is not reference-related to T2 and the initializer expression
2617 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2618 // conversion is selected by enumerating the applicable conversion
2619 // functions (13.3.1.6) and choosing the best one through overload
2620 // resolution (13.3)),
2621 if (RefRelationship == Sema::Ref_Incompatible) {
2622 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2623 Kind, Initializer,
2624 /*AllowRValues=*/true,
2625 Sequence);
2626 if (ConvOvlResult)
2627 Sequence.SetOverloadFailure(
2628 InitializationSequence::FK_ReferenceInitOverloadFailed,
2629 ConvOvlResult);
2630
2631 return;
2632 }
2633
2634 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2635 return;
2636 }
2637
2638 // - If the initializer expression is an rvalue, with T2 an array type,
2639 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2640 // is bound to the object represented by the rvalue (see 3.10).
2641 // FIXME: How can an array type be reference-compatible with anything?
2642 // Don't we mean the element types of T1 and T2?
2643
2644 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2645 // from the initializer expression using the rules for a non-reference
2646 // copy initialization (8.5). The reference is then bound to the
2647 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002648
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002649 // Determine whether we are allowed to call explicit constructors or
2650 // explicit conversion operators.
2651 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002652
2653 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2654
2655 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2656 /*SuppressUserConversions*/ false,
2657 AllowExplicit,
2658 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002659 // FIXME: Use the conversion function set stored in ICS to turn
2660 // this into an overloading ambiguity diagnostic. However, we need
2661 // to keep that set as an OverloadCandidateSet rather than as some
2662 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002663 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2664 Sequence.SetOverloadFailure(
2665 InitializationSequence::FK_ReferenceInitOverloadFailed,
2666 ConvOvlResult);
2667 else
2668 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002669 return;
2670 }
2671
2672 // [...] If T1 is reference-related to T2, cv1 must be the
2673 // same cv-qualification as, or greater cv-qualification
2674 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002675 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2676 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002678 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002679 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2680 return;
2681 }
2682
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002683 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2684 return;
2685}
2686
2687/// \brief Attempt character array initialization from a string literal
2688/// (C++ [dcl.init.string], C99 6.7.8).
2689static void TryStringLiteralInitialization(Sema &S,
2690 const InitializedEntity &Entity,
2691 const InitializationKind &Kind,
2692 Expr *Initializer,
2693 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002694 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002695 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002696}
2697
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002698/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2699/// enumerates the constructors of the initialized entity and performs overload
2700/// resolution to select the best.
2701static void TryConstructorInitialization(Sema &S,
2702 const InitializedEntity &Entity,
2703 const InitializationKind &Kind,
2704 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002705 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002706 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002707 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002708
2709 // Build the candidate set directly in the initialization sequence
2710 // structure, so that it will persist if we fail.
2711 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2712 CandidateSet.clear();
2713
2714 // Determine whether we are allowed to call explicit constructors or
2715 // explicit conversion operators.
2716 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2717 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002718 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002719
2720 // The type we're constructing needs to be complete.
2721 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002722 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002723 return;
2724 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002725
2726 // The type we're converting to is a class type. Enumerate its constructors
2727 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002728 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2729 assert(DestRecordType && "Constructor initialization requires record type");
2730 CXXRecordDecl *DestRecordDecl
2731 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2732
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002733 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002734 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002735 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002736 NamedDecl *D = *Con;
2737 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002738 bool SuppressUserConversions = false;
2739
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002740 // Find the constructor (which may be a template).
2741 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002742 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002743 if (ConstructorTmpl)
2744 Constructor = cast<CXXConstructorDecl>(
2745 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002746 else {
John McCalla0296f72010-03-19 07:35:19 +00002747 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002748
2749 // If we're performing copy initialization using a copy constructor, we
2750 // suppress user-defined conversions on the arguments.
2751 // FIXME: Move constructors?
2752 if (Kind.getKind() == InitializationKind::IK_Copy &&
2753 Constructor->isCopyConstructor())
2754 SuppressUserConversions = true;
2755 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002756
2757 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002758 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002759 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002760 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002761 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002762 Args, NumArgs, CandidateSet,
2763 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002764 else
John McCalla0296f72010-03-19 07:35:19 +00002765 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002766 Args, NumArgs, CandidateSet,
2767 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002768 }
2769 }
2770
2771 SourceLocation DeclLoc = Kind.getLocation();
2772
2773 // Perform overload resolution. If it fails, return the failed result.
2774 OverloadCandidateSet::iterator Best;
2775 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002776 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002777 Sequence.SetOverloadFailure(
2778 InitializationSequence::FK_ConstructorOverloadFailed,
2779 Result);
2780 return;
2781 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002782
2783 // C++0x [dcl.init]p6:
2784 // If a program calls for the default initialization of an object
2785 // of a const-qualified type T, T shall be a class type with a
2786 // user-provided default constructor.
2787 if (Kind.getKind() == InitializationKind::IK_Default &&
2788 Entity.getType().isConstQualified() &&
2789 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2790 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2791 return;
2792 }
2793
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002794 // Add the constructor initialization step. Any cv-qualification conversion is
2795 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002796 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002797 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002798 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002799 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002800}
2801
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002802/// \brief Attempt value initialization (C++ [dcl.init]p7).
2803static void TryValueInitialization(Sema &S,
2804 const InitializedEntity &Entity,
2805 const InitializationKind &Kind,
2806 InitializationSequence &Sequence) {
2807 // C++ [dcl.init]p5:
2808 //
2809 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002810 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002811
2812 // -- if T is an array type, then each element is value-initialized;
2813 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2814 T = AT->getElementType();
2815
2816 if (const RecordType *RT = T->getAs<RecordType>()) {
2817 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2818 // -- if T is a class type (clause 9) with a user-declared
2819 // constructor (12.1), then the default constructor for T is
2820 // called (and the initialization is ill-formed if T has no
2821 // accessible default constructor);
2822 //
2823 // FIXME: we really want to refer to a single subobject of the array,
2824 // but Entity doesn't have a way to capture that (yet).
2825 if (ClassDecl->hasUserDeclaredConstructor())
2826 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2827
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002828 // -- if T is a (possibly cv-qualified) non-union class type
2829 // without a user-provided constructor, then the object is
2830 // zero-initialized and, if T’s implicitly-declared default
2831 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002832 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002833 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002834 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002835 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2836 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002837 }
2838 }
2839
Douglas Gregor1b303932009-12-22 15:35:07 +00002840 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002841 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2842}
2843
Douglas Gregor85dabae2009-12-16 01:38:02 +00002844/// \brief Attempt default initialization (C++ [dcl.init]p6).
2845static void TryDefaultInitialization(Sema &S,
2846 const InitializedEntity &Entity,
2847 const InitializationKind &Kind,
2848 InitializationSequence &Sequence) {
2849 assert(Kind.getKind() == InitializationKind::IK_Default);
2850
2851 // C++ [dcl.init]p6:
2852 // To default-initialize an object of type T means:
2853 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002854 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002855 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2856 DestType = Array->getElementType();
2857
2858 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2859 // constructor for T is called (and the initialization is ill-formed if
2860 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002861 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002862 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2863 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002864 }
2865
2866 // - otherwise, no initialization is performed.
2867 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2868
2869 // If a program calls for the default initialization of an object of
2870 // a const-qualified type T, T shall be a class type with a user-provided
2871 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002872 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002873 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2874}
2875
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002876/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2877/// which enumerates all conversion functions and performs overload resolution
2878/// to select the best.
2879static void TryUserDefinedConversion(Sema &S,
2880 const InitializedEntity &Entity,
2881 const InitializationKind &Kind,
2882 Expr *Initializer,
2883 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002884 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2885
Douglas Gregor1b303932009-12-22 15:35:07 +00002886 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002887 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2888 QualType SourceType = Initializer->getType();
2889 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2890 "Must have a class type to perform a user-defined conversion");
2891
2892 // Build the candidate set directly in the initialization sequence
2893 // structure, so that it will persist if we fail.
2894 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2895 CandidateSet.clear();
2896
2897 // Determine whether we are allowed to call explicit constructors or
2898 // explicit conversion operators.
2899 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2900
2901 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2902 // The type we're converting to is a class type. Enumerate its constructors
2903 // to see if there is a suitable conversion.
2904 CXXRecordDecl *DestRecordDecl
2905 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2906
Douglas Gregord9848152010-04-26 14:36:57 +00002907 // Try to complete the type we're converting to.
2908 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002909 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002910 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002911 Con != ConEnd; ++Con) {
2912 NamedDecl *D = *Con;
2913 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002914
Douglas Gregord9848152010-04-26 14:36:57 +00002915 // Find the constructor (which may be a template).
2916 CXXConstructorDecl *Constructor = 0;
2917 FunctionTemplateDecl *ConstructorTmpl
2918 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002919 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002920 Constructor = cast<CXXConstructorDecl>(
2921 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002922 else
Douglas Gregord9848152010-04-26 14:36:57 +00002923 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002924
2925 if (!Constructor->isInvalidDecl() &&
2926 Constructor->isConvertingConstructor(AllowExplicit)) {
2927 if (ConstructorTmpl)
2928 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2929 /*ExplicitArgs*/ 0,
2930 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002931 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002932 else
2933 S.AddOverloadCandidate(Constructor, FoundDecl,
2934 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002935 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002936 }
2937 }
2938 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002939 }
Eli Friedman78275202009-12-19 08:11:05 +00002940
2941 SourceLocation DeclLoc = Initializer->getLocStart();
2942
Douglas Gregor540c3b02009-12-14 17:27:33 +00002943 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2944 // The type we're converting from is a class type, enumerate its conversion
2945 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002946
Eli Friedman4afe9a32009-12-20 22:12:03 +00002947 // We can only enumerate the conversion functions for a complete type; if
2948 // the type isn't complete, simply skip this step.
2949 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2950 CXXRecordDecl *SourceRecordDecl
2951 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002952
John McCallad371252010-01-20 00:46:10 +00002953 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002954 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002955 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002956 E = Conversions->end();
2957 I != E; ++I) {
2958 NamedDecl *D = *I;
2959 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2960 if (isa<UsingShadowDecl>(D))
2961 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2962
2963 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2964 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002965 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002966 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002967 else
John McCallda4458e2010-03-31 01:36:47 +00002968 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002969
2970 if (AllowExplicit || !Conv->isExplicit()) {
2971 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002972 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002973 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002974 CandidateSet);
2975 else
John McCalla0296f72010-03-19 07:35:19 +00002976 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002977 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002978 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002979 }
2980 }
2981 }
2982
Douglas Gregor540c3b02009-12-14 17:27:33 +00002983 // Perform overload resolution. If it fails, return the failed result.
2984 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002985 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002986 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002987 Sequence.SetOverloadFailure(
2988 InitializationSequence::FK_UserConversionOverloadFailed,
2989 Result);
2990 return;
2991 }
John McCall0d1da222010-01-12 00:44:57 +00002992
Douglas Gregor540c3b02009-12-14 17:27:33 +00002993 FunctionDecl *Function = Best->Function;
2994
2995 if (isa<CXXConstructorDecl>(Function)) {
2996 // Add the user-defined conversion step. Any cv-qualification conversion is
2997 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00002998 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002999 return;
3000 }
3001
3002 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003003 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003004 if (ConvType->getAs<RecordType>()) {
3005 // If we're converting to a class type, there may be an copy if
3006 // the resulting temporary object (possible to create an object of
3007 // a base class type). That copy is not a separate conversion, so
3008 // we just make a note of the actual destination type (possibly a
3009 // base class of the type returned by the conversion function) and
3010 // let the user-defined conversion step handle the conversion.
3011 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3012 return;
3013 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003014
Douglas Gregor5ab11652010-04-17 22:01:05 +00003015 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3016
3017 // If the conversion following the call to the conversion function
3018 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003019 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3020 Best->FinalConversion.Third) {
3021 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003022 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003023 ICS.Standard = Best->FinalConversion;
3024 Sequence.AddConversionSequenceStep(ICS, DestType);
3025 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003026}
3027
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003028InitializationSequence::InitializationSequence(Sema &S,
3029 const InitializedEntity &Entity,
3030 const InitializationKind &Kind,
3031 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003032 unsigned NumArgs)
3033 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003034 ASTContext &Context = S.Context;
3035
3036 // C++0x [dcl.init]p16:
3037 // The semantics of initializers are as follows. The destination type is
3038 // the type of the object or reference being initialized and the source
3039 // type is the type of the initializer expression. The source type is not
3040 // defined when the initializer is a braced-init-list or when it is a
3041 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003042 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003043
3044 if (DestType->isDependentType() ||
3045 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3046 SequenceKind = DependentSequence;
3047 return;
3048 }
3049
3050 QualType SourceType;
3051 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003052 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003053 Initializer = Args[0];
3054 if (!isa<InitListExpr>(Initializer))
3055 SourceType = Initializer->getType();
3056 }
3057
3058 // - If the initializer is a braced-init-list, the object is
3059 // list-initialized (8.5.4).
3060 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3061 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003062 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003063 }
3064
3065 // - If the destination type is a reference type, see 8.5.3.
3066 if (DestType->isReferenceType()) {
3067 // C++0x [dcl.init.ref]p1:
3068 // A variable declared to be a T& or T&&, that is, "reference to type T"
3069 // (8.3.2), shall be initialized by an object, or function, of type T or
3070 // by an object that can be converted into a T.
3071 // (Therefore, multiple arguments are not permitted.)
3072 if (NumArgs != 1)
3073 SetFailed(FK_TooManyInitsForReference);
3074 else
3075 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3076 return;
3077 }
3078
3079 // - If the destination type is an array of characters, an array of
3080 // char16_t, an array of char32_t, or an array of wchar_t, and the
3081 // initializer is a string literal, see 8.5.2.
3082 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3083 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3084 return;
3085 }
3086
3087 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003088 if (Kind.getKind() == InitializationKind::IK_Value ||
3089 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003090 TryValueInitialization(S, Entity, Kind, *this);
3091 return;
3092 }
3093
Douglas Gregor85dabae2009-12-16 01:38:02 +00003094 // Handle default initialization.
3095 if (Kind.getKind() == InitializationKind::IK_Default){
3096 TryDefaultInitialization(S, Entity, Kind, *this);
3097 return;
3098 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003099
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003100 // - Otherwise, if the destination type is an array, the program is
3101 // ill-formed.
3102 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3103 if (AT->getElementType()->isAnyCharacterType())
3104 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3105 else
3106 SetFailed(FK_ArrayNeedsInitList);
3107
3108 return;
3109 }
Eli Friedman78275202009-12-19 08:11:05 +00003110
3111 // Handle initialization in C
3112 if (!S.getLangOptions().CPlusPlus) {
3113 setSequenceKind(CAssignment);
3114 AddCAssignmentStep(DestType);
3115 return;
3116 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003117
3118 // - If the destination type is a (possibly cv-qualified) class type:
3119 if (DestType->isRecordType()) {
3120 // - If the initialization is direct-initialization, or if it is
3121 // copy-initialization where the cv-unqualified version of the
3122 // source type is the same class as, or a derived class of, the
3123 // class of the destination, constructors are considered. [...]
3124 if (Kind.getKind() == InitializationKind::IK_Direct ||
3125 (Kind.getKind() == InitializationKind::IK_Copy &&
3126 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3127 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003128 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003129 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130 // - Otherwise (i.e., for the remaining copy-initialization cases),
3131 // user-defined conversion sequences that can convert from the source
3132 // type to the destination type or (when a conversion function is
3133 // used) to a derived class thereof are enumerated as described in
3134 // 13.3.1.4, and the best one is chosen through overload resolution
3135 // (13.3).
3136 else
3137 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3138 return;
3139 }
3140
Douglas Gregor85dabae2009-12-16 01:38:02 +00003141 if (NumArgs > 1) {
3142 SetFailed(FK_TooManyInitsForScalar);
3143 return;
3144 }
3145 assert(NumArgs == 1 && "Zero-argument case handled above");
3146
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003147 // - Otherwise, if the source type is a (possibly cv-qualified) class
3148 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003149 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003150 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3151 return;
3152 }
3153
3154 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003155 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003156 // conversions (Clause 4) will be used, if necessary, to convert the
3157 // initializer expression to the cv-unqualified version of the
3158 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003159 if (S.TryImplicitConversion(*this, Entity, Initializer,
3160 /*SuppressUserConversions*/ true,
3161 /*AllowExplicitConversions*/ false,
3162 /*InOverloadResolution*/ false))
3163 SetFailed(InitializationSequence::FK_ConversionFailed);
3164 else
3165 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003166}
3167
3168InitializationSequence::~InitializationSequence() {
3169 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3170 StepEnd = Steps.end();
3171 Step != StepEnd; ++Step)
3172 Step->Destroy();
3173}
3174
3175//===----------------------------------------------------------------------===//
3176// Perform initialization
3177//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003178static Sema::AssignmentAction
3179getAssignmentAction(const InitializedEntity &Entity) {
3180 switch(Entity.getKind()) {
3181 case InitializedEntity::EK_Variable:
3182 case InitializedEntity::EK_New:
3183 return Sema::AA_Initializing;
3184
3185 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003186 if (Entity.getDecl() &&
3187 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3188 return Sema::AA_Sending;
3189
Douglas Gregore1314a62009-12-18 05:02:21 +00003190 return Sema::AA_Passing;
3191
3192 case InitializedEntity::EK_Result:
3193 return Sema::AA_Returning;
3194
3195 case InitializedEntity::EK_Exception:
3196 case InitializedEntity::EK_Base:
3197 llvm_unreachable("No assignment action for C++-specific initialization");
3198 break;
3199
3200 case InitializedEntity::EK_Temporary:
3201 // FIXME: Can we tell apart casting vs. converting?
3202 return Sema::AA_Casting;
3203
3204 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003205 case InitializedEntity::EK_ArrayElement:
3206 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003207 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003208 return Sema::AA_Initializing;
3209 }
3210
3211 return Sema::AA_Converting;
3212}
3213
Douglas Gregor95562572010-04-24 23:45:46 +00003214/// \brief Whether we should binding a created object as a temporary when
3215/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003216static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003217 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003218 case InitializedEntity::EK_ArrayElement:
3219 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003220 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003221 case InitializedEntity::EK_New:
3222 case InitializedEntity::EK_Variable:
3223 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003224 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003225 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003226 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003227 return false;
3228
3229 case InitializedEntity::EK_Parameter:
3230 case InitializedEntity::EK_Temporary:
3231 return true;
3232 }
3233
3234 llvm_unreachable("missed an InitializedEntity kind?");
3235}
3236
Douglas Gregor95562572010-04-24 23:45:46 +00003237/// \brief Whether the given entity, when initialized with an object
3238/// created for that initialization, requires destruction.
3239static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3240 switch (Entity.getKind()) {
3241 case InitializedEntity::EK_Member:
3242 case InitializedEntity::EK_Result:
3243 case InitializedEntity::EK_New:
3244 case InitializedEntity::EK_Base:
3245 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003246 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003247 return false;
3248
3249 case InitializedEntity::EK_Variable:
3250 case InitializedEntity::EK_Parameter:
3251 case InitializedEntity::EK_Temporary:
3252 case InitializedEntity::EK_ArrayElement:
3253 case InitializedEntity::EK_Exception:
3254 return true;
3255 }
3256
3257 llvm_unreachable("missed an InitializedEntity kind?");
3258}
3259
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003260/// \brief Make a (potentially elidable) temporary copy of the object
3261/// provided by the given initializer by calling the appropriate copy
3262/// constructor.
3263///
3264/// \param S The Sema object used for type-checking.
3265///
3266/// \param T The type of the temporary object, which must either by
3267/// the type of the initializer expression or a superclass thereof.
3268///
3269/// \param Enter The entity being initialized.
3270///
3271/// \param CurInit The initializer expression.
3272///
3273/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3274/// is permitted in C++03 (but not C++0x) when binding a reference to
3275/// an rvalue.
3276///
3277/// \returns An expression that copies the initializer expression into
3278/// a temporary object, or an error expression if a copy could not be
3279/// created.
John McCalldadc5752010-08-24 06:29:42 +00003280static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003281 QualType T,
3282 const InitializedEntity &Entity,
3283 ExprResult CurInit,
3284 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003285 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003286 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003287 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003288 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003289 Class = cast<CXXRecordDecl>(Record->getDecl());
3290 if (!Class)
3291 return move(CurInit);
3292
3293 // C++0x [class.copy]p34:
3294 // When certain criteria are met, an implementation is allowed to
3295 // omit the copy/move construction of a class object, even if the
3296 // copy/move constructor and/or destructor for the object have
3297 // side effects. [...]
3298 // - when a temporary class object that has not been bound to a
3299 // reference (12.2) would be copied/moved to a class object
3300 // with the same cv-unqualified type, the copy/move operation
3301 // can be omitted by constructing the temporary object
3302 // directly into the target of the omitted copy/move
3303 //
3304 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003305 // elision for return statements and throw expressions are handled as part
3306 // of constructor initialization, while copy elision for exception handlers
3307 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003308 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003309 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003310 switch (Entity.getKind()) {
3311 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003312 Loc = Entity.getReturnLoc();
3313 break;
3314
3315 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003316 Loc = Entity.getThrowLoc();
3317 break;
3318
3319 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003320 Loc = Entity.getDecl()->getLocation();
3321 break;
3322
Anders Carlsson0bd52402010-01-24 00:19:41 +00003323 case InitializedEntity::EK_ArrayElement:
3324 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003325 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003326 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003327 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003328 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003329 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003330 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003331 Loc = CurInitExpr->getLocStart();
3332 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003333 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003334
3335 // Make sure that the type we are copying is complete.
3336 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3337 return move(CurInit);
3338
Douglas Gregore1314a62009-12-18 05:02:21 +00003339 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003340 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003341 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003342 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003343 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003344 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003345 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3346 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003347 !Constructor->isCopyConstructor() ||
3348 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003349 continue;
John McCalla0296f72010-03-19 07:35:19 +00003350
3351 DeclAccessPair FoundDecl
3352 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3353 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003354 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003355 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003356
3357 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003358 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003359 case OR_Success:
3360 break;
3361
3362 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003363 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3364 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3365 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003366 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003367 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003368 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003369 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003370 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003371 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003372
3373 case OR_Ambiguous:
3374 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003375 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003376 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003377 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003378 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003379
3380 case OR_Deleted:
3381 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003382 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003383 << CurInitExpr->getSourceRange();
3384 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3385 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003386 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003387 }
3388
Douglas Gregor5ab11652010-04-17 22:01:05 +00003389 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003390 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003391 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003392
Anders Carlssona01874b2010-04-21 18:47:17 +00003393 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003394 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003395
3396 if (IsExtraneousCopy) {
3397 // If this is a totally extraneous copy for C++03 reference
3398 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003399 // expression. We don't generate an (elided) copy operation here
3400 // because doing so would require us to pass down a flag to avoid
3401 // infinite recursion, where each step adds another extraneous,
3402 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003403
Douglas Gregor30b52772010-04-18 07:57:34 +00003404 // Instantiate the default arguments of any extra parameters in
3405 // the selected copy constructor, as if we were going to create a
3406 // proper call to the copy constructor.
3407 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3408 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3409 if (S.RequireCompleteType(Loc, Parm->getType(),
3410 S.PDiag(diag::err_call_incomplete_argument)))
3411 break;
3412
3413 // Build the default argument expression; we don't actually care
3414 // if this succeeds or not, because this routine will complain
3415 // if there was a problem.
3416 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3417 }
3418
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003419 return S.Owned(CurInitExpr);
3420 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003421
3422 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003423 // constructor call (we might have derived-to-base conversions, or
3424 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003425 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003426 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003427 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003428
Douglas Gregord0ace022010-04-25 00:55:24 +00003429 // Actually perform the constructor call.
3430 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003431 move_arg(ConstructorArgs),
3432 /*ZeroInit*/ false,
3433 CXXConstructExpr::CK_Complete);
Douglas Gregord0ace022010-04-25 00:55:24 +00003434
3435 // If we're supposed to bind temporaries, do so.
3436 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3437 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3438 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003439}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003440
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003441void InitializationSequence::PrintInitLocationNote(Sema &S,
3442 const InitializedEntity &Entity) {
3443 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3444 if (Entity.getDecl()->getLocation().isInvalid())
3445 return;
3446
3447 if (Entity.getDecl()->getDeclName())
3448 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3449 << Entity.getDecl()->getDeclName();
3450 else
3451 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3452 }
3453}
3454
John McCalldadc5752010-08-24 06:29:42 +00003455ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003456InitializationSequence::Perform(Sema &S,
3457 const InitializedEntity &Entity,
3458 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003459 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003460 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003461 if (SequenceKind == FailedSequence) {
3462 unsigned NumArgs = Args.size();
3463 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003464 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003465 }
3466
3467 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003468 // If the declaration is a non-dependent, incomplete array type
3469 // that has an initializer, then its type will be completed once
3470 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003471 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003472 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003473 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003474 if (const IncompleteArrayType *ArrayT
3475 = S.Context.getAsIncompleteArrayType(DeclType)) {
3476 // FIXME: We don't currently have the ability to accurately
3477 // compute the length of an initializer list without
3478 // performing full type-checking of the initializer list
3479 // (since we have to determine where braces are implicitly
3480 // introduced and such). So, we fall back to making the array
3481 // type a dependently-sized array type with no specified
3482 // bound.
3483 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3484 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003485
Douglas Gregor51e77d52009-12-10 17:56:55 +00003486 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003487 if (DeclaratorDecl *DD = Entity.getDecl()) {
3488 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3489 TypeLoc TL = TInfo->getTypeLoc();
3490 if (IncompleteArrayTypeLoc *ArrayLoc
3491 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3492 Brackets = ArrayLoc->getBracketsRange();
3493 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003494 }
3495
3496 *ResultType
3497 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3498 /*NumElts=*/0,
3499 ArrayT->getSizeModifier(),
3500 ArrayT->getIndexTypeCVRQualifiers(),
3501 Brackets);
3502 }
3503
3504 }
3505 }
3506
Eli Friedmana553d4a2009-12-22 02:35:53 +00003507 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003508 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003509
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003510 if (Args.size() == 0)
3511 return S.Owned((Expr *)0);
3512
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003513 unsigned NumArgs = Args.size();
3514 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3515 SourceLocation(),
3516 (Expr **)Args.release(),
3517 NumArgs,
3518 SourceLocation()));
3519 }
3520
Douglas Gregor85dabae2009-12-16 01:38:02 +00003521 if (SequenceKind == NoInitialization)
3522 return S.Owned((Expr *)0);
3523
Douglas Gregor1b303932009-12-22 15:35:07 +00003524 QualType DestType = Entity.getType().getNonReferenceType();
3525 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003526 // the same as Entity.getDecl()->getType() in cases involving type merging,
3527 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003528 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003529 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003530 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003531
John McCalldadc5752010-08-24 06:29:42 +00003532 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003533
3534 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3535
3536 // For initialization steps that start with a single initializer,
3537 // grab the only argument out the Args and place it into the "current"
3538 // initializer.
3539 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003540 case SK_ResolveAddressOfOverloadedFunction:
3541 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003542 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003543 case SK_CastDerivedToBaseLValue:
3544 case SK_BindReference:
3545 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003546 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003547 case SK_UserConversion:
3548 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003549 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003550 case SK_QualificationConversionRValue:
3551 case SK_ConversionSequence:
3552 case SK_ListInitialization:
3553 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003554 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003555 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003556 assert(Args.size() == 1);
John McCalldadc5752010-08-24 06:29:42 +00003557 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregore1314a62009-12-18 05:02:21 +00003558 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003559 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003560 break;
3561
3562 case SK_ConstructorInitialization:
3563 case SK_ZeroInitialization:
3564 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003565 }
3566
3567 // Walk through the computed steps for the initialization sequence,
3568 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003569 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003570 for (step_iterator Step = step_begin(), StepEnd = step_end();
3571 Step != StepEnd; ++Step) {
3572 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003573 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574
3575 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003576 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003577
3578 switch (Step->Kind) {
3579 case SK_ResolveAddressOfOverloadedFunction:
3580 // Overload resolution determined which function invoke; update the
3581 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003582 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003583 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003584 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003585 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003586 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003587 break;
3588
3589 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003590 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003591 case SK_CastDerivedToBaseLValue: {
3592 // We have a derived-to-base cast that produces either an rvalue or an
3593 // lvalue. Perform that cast.
3594
John McCallcf142162010-08-07 06:22:56 +00003595 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003596
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003597 // Casts to inaccessible base classes are allowed with C-style casts.
3598 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3599 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3600 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003601 CurInitExpr->getSourceRange(),
3602 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003603 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604
Douglas Gregor88d292c2010-05-13 16:44:06 +00003605 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3606 QualType T = SourceType;
3607 if (const PointerType *Pointer = T->getAs<PointerType>())
3608 T = Pointer->getPointeeType();
3609 if (const RecordType *RecordTy = T->getAs<RecordType>())
3610 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3611 cast<CXXRecordDecl>(RecordTy->getDecl()));
3612 }
3613
John McCall2536c6d2010-08-25 10:28:54 +00003614 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003615 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003616 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003617 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003618 VK_XValue :
3619 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003620 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3621 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003622 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003623 CurInit.get(),
3624 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003625 break;
3626 }
3627
3628 case SK_BindReference:
3629 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3630 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3631 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003632 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003633 << BitField->getDeclName()
3634 << CurInitExpr->getSourceRange();
3635 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003636 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003637 }
Anders Carlssona91be642010-01-29 02:47:33 +00003638
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003639 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003640 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003641 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3642 << Entity.getType().isVolatileQualified()
3643 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003644 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003645 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003646 }
3647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 // Reference binding does not have any corresponding ASTs.
3649
3650 // Check exception specifications
3651 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003652 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003653
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003654 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003657 // Reference binding does not have any corresponding ASTs.
3658
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003659 // Check exception specifications
3660 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003661 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003662
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003663 break;
3664
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003665 case SK_ExtraneousCopyToTemporary:
3666 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3667 /*IsExtraneousCopy=*/true);
3668 break;
3669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003670 case SK_UserConversion: {
3671 // We have a user-defined conversion that invokes either a constructor
3672 // or a conversion function.
John McCalle3027922010-08-25 11:45:40 +00003673 CastKind CastKind = CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003674 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003675 FunctionDecl *Fn = Step->Function.Function;
3676 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003677 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003678 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003679 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003680 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003681 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003682 SourceLocation Loc = CurInitExpr->getLocStart();
3683 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003684
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003685 // Determine the arguments required to actually perform the constructor
3686 // call.
3687 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00003688 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003689 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003690 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003691
3692 // Build the an expression that constructs a temporary.
3693 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003694 move_arg(ConstructorArgs),
3695 /*ZeroInit*/ false,
3696 CXXConstructExpr::CK_Complete);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003697 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003698 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003699
Anders Carlssona01874b2010-04-21 18:47:17 +00003700 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003701 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003702 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003703
John McCalle3027922010-08-25 11:45:40 +00003704 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003705 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3706 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3707 S.IsDerivedFrom(SourceType, Class))
3708 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003709
3710 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003711 } else {
3712 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003713 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003714 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003715 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003716 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003717 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003718
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003719 // FIXME: Should we move this initialization into a separate
3720 // derived-to-base conversion? I believe the answer is "no", because
3721 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003722 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003723 FoundFn, Conversion))
John McCallfaf5fb42010-08-26 23:41:50 +00003724 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003725
3726 // Do a little dance to make sure that CurInit has the proper
3727 // pointer.
3728 CurInit.release();
3729
3730 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003731 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3732 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003733 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003734 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735
John McCalle3027922010-08-25 11:45:40 +00003736 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003737
3738 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003739 }
3740
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003741 bool RequiresCopy = !IsCopy &&
3742 getKind() != InitializationSequence::ReferenceBinding;
3743 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003744 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003745 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3746 CurInitExpr = static_cast<Expr *>(CurInit.get());
3747 QualType T = CurInitExpr->getType();
3748 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003749 CXXDestructorDecl *Destructor
3750 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003751 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3752 S.PDiag(diag::err_access_dtor_temp) << T);
3753 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3754 }
3755 }
3756
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003757 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003758 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003759 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3760 CurInitExpr->getType(),
3761 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003762 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003763
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003764 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003765 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3766 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003767
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003768 break;
3769 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003770
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003771 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003772 case SK_QualificationConversionXValue:
3773 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003774 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003775 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003776 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003777 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003778 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003779 VK_XValue :
3780 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003781 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003782 CurInit.release();
3783 CurInit = S.Owned(CurInitExpr);
3784 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003785 }
3786
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003787 case SK_ConversionSequence: {
3788 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3789
3790 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3791 Sema::AA_Converting, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003792 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003793
3794 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003795 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003796 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003797 }
3798
Douglas Gregor51e77d52009-12-10 17:56:55 +00003799 case SK_ListInitialization: {
3800 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3801 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003802 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003803 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003804
3805 CurInit.release();
3806 CurInit = S.Owned(InitList);
3807 break;
3808 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003809
3810 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003811 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003812 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003813 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003814
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003815 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003816 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003817 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3818 ? Kind.getEqualLoc()
3819 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003820
3821 if (Kind.getKind() == InitializationKind::IK_Default) {
3822 // Force even a trivial, implicit default constructor to be
3823 // semantically checked. We do this explicitly because we don't build
3824 // the definition for completely trivial constructors.
3825 CXXRecordDecl *ClassDecl = Constructor->getParent();
3826 assert(ClassDecl && "No parent class for constructor.");
3827 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3828 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3829 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3830 }
3831
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003832 // Determine the arguments required to actually perform the constructor
3833 // call.
3834 if (S.CompleteConstructorCall(Constructor, move(Args),
3835 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003836 return ExprError();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003837
Chandler Carruthc9262402010-08-23 07:55:51 +00003838
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003839 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003840 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003841 (Kind.getKind() == InitializationKind::IK_Direct ||
3842 Kind.getKind() == InitializationKind::IK_Value)) {
3843 // An explicitly-constructed temporary, e.g., X(1, 2).
3844 unsigned NumExprs = ConstructorArgs.size();
3845 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003846 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor2b88c112010-09-08 00:15:04 +00003847
3848 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3849 if (!TSInfo)
3850 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3851
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003852 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3853 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00003854 TSInfo,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003855 Exprs,
3856 NumExprs,
Douglas Gregor199db362010-04-27 20:36:09 +00003857 Kind.getParenRange().getEnd(),
3858 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003859 } else {
3860 CXXConstructExpr::ConstructionKind ConstructKind =
3861 CXXConstructExpr::CK_Complete;
3862
3863 if (Entity.getKind() == InitializedEntity::EK_Base) {
3864 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3865 CXXConstructExpr::CK_VirtualBase :
3866 CXXConstructExpr::CK_NonVirtualBase;
3867 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003868
3869 // If the entity allows NRVO, mark the construction as elidable
3870 // unconditionally.
3871 if (Entity.allowsNRVO())
3872 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3873 Constructor, /*Elidable=*/true,
3874 move_arg(ConstructorArgs),
3875 ConstructorInitRequiresZeroInit,
3876 ConstructKind);
3877 else
3878 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3879 Constructor,
3880 move_arg(ConstructorArgs),
3881 ConstructorInitRequiresZeroInit,
3882 ConstructKind);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003883 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003884 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003885 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003886
3887 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003888 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003889 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003890 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003891
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003892 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003893 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003894
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003895 break;
3896 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003897
3898 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003899 step_iterator NextStep = Step;
3900 ++NextStep;
3901 if (NextStep != StepEnd &&
3902 NextStep->Kind == SK_ConstructorInitialization) {
3903 // The need for zero-initialization is recorded directly into
3904 // the call to the object's constructor within the next step.
3905 ConstructorInitRequiresZeroInit = true;
3906 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3907 S.getLangOptions().CPlusPlus &&
3908 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00003909 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3910 if (!TSInfo)
3911 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3912 Kind.getRange().getBegin());
3913
3914 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3915 TSInfo->getType().getNonLValueExprType(S.Context),
3916 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003917 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003918 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003919 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003920 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003921 break;
3922 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003923
3924 case SK_CAssignment: {
3925 QualType SourceType = CurInitExpr->getType();
3926 Sema::AssignConvertType ConvTy =
3927 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003928
3929 // If this is a call, allow conversion to a transparent union.
3930 if (ConvTy != Sema::Compatible &&
3931 Entity.getKind() == InitializedEntity::EK_Parameter &&
3932 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3933 == Sema::Compatible)
3934 ConvTy = Sema::Compatible;
3935
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003936 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003937 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3938 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003939 CurInitExpr,
3940 getAssignmentAction(Entity),
3941 &Complained)) {
3942 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003943 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003944 } else if (Complained)
3945 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003946
3947 CurInit.release();
3948 CurInit = S.Owned(CurInitExpr);
3949 break;
3950 }
Eli Friedman78275202009-12-19 08:11:05 +00003951
3952 case SK_StringInit: {
3953 QualType Ty = Step->Type;
3954 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3955 break;
3956 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003957
3958 case SK_ObjCObjectConversion:
3959 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003960 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003961 S.CastCategory(CurInitExpr));
3962 CurInit.release();
3963 CurInit = S.Owned(CurInitExpr);
3964 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003965 }
3966 }
3967
3968 return move(CurInit);
3969}
3970
3971//===----------------------------------------------------------------------===//
3972// Diagnose initialization failures
3973//===----------------------------------------------------------------------===//
3974bool InitializationSequence::Diagnose(Sema &S,
3975 const InitializedEntity &Entity,
3976 const InitializationKind &Kind,
3977 Expr **Args, unsigned NumArgs) {
3978 if (SequenceKind != FailedSequence)
3979 return false;
3980
Douglas Gregor1b303932009-12-22 15:35:07 +00003981 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003982 switch (Failure) {
3983 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003984 // FIXME: Customize for the initialized entity?
3985 if (NumArgs == 0)
3986 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3987 << DestType.getNonReferenceType();
3988 else // FIXME: diagnostic below could be better!
3989 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3990 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003991 break;
3992
3993 case FK_ArrayNeedsInitList:
3994 case FK_ArrayNeedsInitListOrStringLiteral:
3995 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3996 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3997 break;
3998
John McCall16df1e52010-03-30 21:47:33 +00003999 case FK_AddressOfOverloadFailed: {
4000 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004001 S.ResolveAddressOfOverloadedFunction(Args[0],
4002 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004003 true,
4004 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004005 break;
John McCall16df1e52010-03-30 21:47:33 +00004006 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004007
4008 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004009 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004010 switch (FailedOverloadResult) {
4011 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004012 if (Failure == FK_UserConversionOverloadFailed)
4013 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4014 << Args[0]->getType() << DestType
4015 << Args[0]->getSourceRange();
4016 else
4017 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4018 << DestType << Args[0]->getType()
4019 << Args[0]->getSourceRange();
4020
John McCall5c32be02010-08-24 20:38:10 +00004021 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004022 break;
4023
4024 case OR_No_Viable_Function:
4025 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4026 << Args[0]->getType() << DestType.getNonReferenceType()
4027 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004028 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004029 break;
4030
4031 case OR_Deleted: {
4032 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4033 << Args[0]->getType() << DestType.getNonReferenceType()
4034 << Args[0]->getSourceRange();
4035 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004036 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004037 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4038 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004039 if (Ovl == OR_Deleted) {
4040 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4041 << Best->Function->isDeleted();
4042 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004043 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004044 }
4045 break;
4046 }
4047
4048 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004049 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004050 break;
4051 }
4052 break;
4053
4054 case FK_NonConstLValueReferenceBindingToTemporary:
4055 case FK_NonConstLValueReferenceBindingToUnrelated:
4056 S.Diag(Kind.getLocation(),
4057 Failure == FK_NonConstLValueReferenceBindingToTemporary
4058 ? diag::err_lvalue_reference_bind_to_temporary
4059 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004060 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004061 << DestType.getNonReferenceType()
4062 << Args[0]->getType()
4063 << Args[0]->getSourceRange();
4064 break;
4065
4066 case FK_RValueReferenceBindingToLValue:
4067 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4068 << Args[0]->getSourceRange();
4069 break;
4070
4071 case FK_ReferenceInitDropsQualifiers:
4072 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4073 << DestType.getNonReferenceType()
4074 << Args[0]->getType()
4075 << Args[0]->getSourceRange();
4076 break;
4077
4078 case FK_ReferenceInitFailed:
4079 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4080 << DestType.getNonReferenceType()
4081 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4082 << Args[0]->getType()
4083 << Args[0]->getSourceRange();
4084 break;
4085
4086 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004087 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4088 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004089 << DestType
4090 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4091 << Args[0]->getType()
4092 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004093 break;
4094
4095 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004096 SourceRange R;
4097
4098 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004099 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004100 InitList->getLocEnd());
Douglas Gregor8ec51732010-09-08 21:40:08 +00004101 else
4102 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004103
Douglas Gregor8ec51732010-09-08 21:40:08 +00004104 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4105 if (Kind.isCStyleOrFunctionalCast())
4106 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4107 << R;
4108 else
4109 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4110 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004111 break;
4112 }
4113
4114 case FK_ReferenceBindingToInitList:
4115 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4116 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4117 break;
4118
4119 case FK_InitListBadDestinationType:
4120 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4121 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4122 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004123
4124 case FK_ConstructorOverloadFailed: {
4125 SourceRange ArgsRange;
4126 if (NumArgs)
4127 ArgsRange = SourceRange(Args[0]->getLocStart(),
4128 Args[NumArgs - 1]->getLocEnd());
4129
4130 // FIXME: Using "DestType" for the entity we're printing is probably
4131 // bad.
4132 switch (FailedOverloadResult) {
4133 case OR_Ambiguous:
4134 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4135 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004136 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4137 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004138 break;
4139
4140 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004141 if (Kind.getKind() == InitializationKind::IK_Default &&
4142 (Entity.getKind() == InitializedEntity::EK_Base ||
4143 Entity.getKind() == InitializedEntity::EK_Member) &&
4144 isa<CXXConstructorDecl>(S.CurContext)) {
4145 // This is implicit default initialization of a member or
4146 // base within a constructor. If no viable function was
4147 // found, notify the user that she needs to explicitly
4148 // initialize this base/member.
4149 CXXConstructorDecl *Constructor
4150 = cast<CXXConstructorDecl>(S.CurContext);
4151 if (Entity.getKind() == InitializedEntity::EK_Base) {
4152 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4153 << Constructor->isImplicit()
4154 << S.Context.getTypeDeclType(Constructor->getParent())
4155 << /*base=*/0
4156 << Entity.getType();
4157
4158 RecordDecl *BaseDecl
4159 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4160 ->getDecl();
4161 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4162 << S.Context.getTagDeclType(BaseDecl);
4163 } else {
4164 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4165 << Constructor->isImplicit()
4166 << S.Context.getTypeDeclType(Constructor->getParent())
4167 << /*member=*/1
4168 << Entity.getName();
4169 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4170
4171 if (const RecordType *Record
4172 = Entity.getType()->getAs<RecordType>())
4173 S.Diag(Record->getDecl()->getLocation(),
4174 diag::note_previous_decl)
4175 << S.Context.getTagDeclType(Record->getDecl());
4176 }
4177 break;
4178 }
4179
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004180 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4181 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004182 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004183 break;
4184
4185 case OR_Deleted: {
4186 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4187 << true << DestType << ArgsRange;
4188 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004189 OverloadingResult Ovl
4190 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004191 if (Ovl == OR_Deleted) {
4192 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4193 << Best->Function->isDeleted();
4194 } else {
4195 llvm_unreachable("Inconsistent overload resolution?");
4196 }
4197 break;
4198 }
4199
4200 case OR_Success:
4201 llvm_unreachable("Conversion did not fail!");
4202 break;
4203 }
4204 break;
4205 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004206
4207 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004208 if (Entity.getKind() == InitializedEntity::EK_Member &&
4209 isa<CXXConstructorDecl>(S.CurContext)) {
4210 // This is implicit default-initialization of a const member in
4211 // a constructor. Complain that it needs to be explicitly
4212 // initialized.
4213 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4214 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4215 << Constructor->isImplicit()
4216 << S.Context.getTypeDeclType(Constructor->getParent())
4217 << /*const=*/1
4218 << Entity.getName();
4219 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4220 << Entity.getName();
4221 } else {
4222 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4223 << DestType << (bool)DestType->getAs<RecordType>();
4224 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004225 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004226
4227 case FK_Incomplete:
4228 S.RequireCompleteType(Kind.getLocation(), DestType,
4229 diag::err_init_incomplete_type);
4230 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004231 }
4232
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004233 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004234 return true;
4235}
Douglas Gregore1314a62009-12-18 05:02:21 +00004236
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004237void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4238 switch (SequenceKind) {
4239 case FailedSequence: {
4240 OS << "Failed sequence: ";
4241 switch (Failure) {
4242 case FK_TooManyInitsForReference:
4243 OS << "too many initializers for reference";
4244 break;
4245
4246 case FK_ArrayNeedsInitList:
4247 OS << "array requires initializer list";
4248 break;
4249
4250 case FK_ArrayNeedsInitListOrStringLiteral:
4251 OS << "array requires initializer list or string literal";
4252 break;
4253
4254 case FK_AddressOfOverloadFailed:
4255 OS << "address of overloaded function failed";
4256 break;
4257
4258 case FK_ReferenceInitOverloadFailed:
4259 OS << "overload resolution for reference initialization failed";
4260 break;
4261
4262 case FK_NonConstLValueReferenceBindingToTemporary:
4263 OS << "non-const lvalue reference bound to temporary";
4264 break;
4265
4266 case FK_NonConstLValueReferenceBindingToUnrelated:
4267 OS << "non-const lvalue reference bound to unrelated type";
4268 break;
4269
4270 case FK_RValueReferenceBindingToLValue:
4271 OS << "rvalue reference bound to an lvalue";
4272 break;
4273
4274 case FK_ReferenceInitDropsQualifiers:
4275 OS << "reference initialization drops qualifiers";
4276 break;
4277
4278 case FK_ReferenceInitFailed:
4279 OS << "reference initialization failed";
4280 break;
4281
4282 case FK_ConversionFailed:
4283 OS << "conversion failed";
4284 break;
4285
4286 case FK_TooManyInitsForScalar:
4287 OS << "too many initializers for scalar";
4288 break;
4289
4290 case FK_ReferenceBindingToInitList:
4291 OS << "referencing binding to initializer list";
4292 break;
4293
4294 case FK_InitListBadDestinationType:
4295 OS << "initializer list for non-aggregate, non-scalar type";
4296 break;
4297
4298 case FK_UserConversionOverloadFailed:
4299 OS << "overloading failed for user-defined conversion";
4300 break;
4301
4302 case FK_ConstructorOverloadFailed:
4303 OS << "constructor overloading failed";
4304 break;
4305
4306 case FK_DefaultInitOfConst:
4307 OS << "default initialization of a const variable";
4308 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004309
4310 case FK_Incomplete:
4311 OS << "initialization of incomplete type";
4312 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004313 }
4314 OS << '\n';
4315 return;
4316 }
4317
4318 case DependentSequence:
4319 OS << "Dependent sequence: ";
4320 return;
4321
4322 case UserDefinedConversion:
4323 OS << "User-defined conversion sequence: ";
4324 break;
4325
4326 case ConstructorInitialization:
4327 OS << "Constructor initialization sequence: ";
4328 break;
4329
4330 case ReferenceBinding:
4331 OS << "Reference binding: ";
4332 break;
4333
4334 case ListInitialization:
4335 OS << "List initialization: ";
4336 break;
4337
4338 case ZeroInitialization:
4339 OS << "Zero initialization\n";
4340 return;
4341
4342 case NoInitialization:
4343 OS << "No initialization\n";
4344 return;
4345
4346 case StandardConversion:
4347 OS << "Standard conversion: ";
4348 break;
4349
4350 case CAssignment:
4351 OS << "C assignment: ";
4352 break;
4353
4354 case StringInit:
4355 OS << "String initialization: ";
4356 break;
4357 }
4358
4359 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4360 if (S != step_begin()) {
4361 OS << " -> ";
4362 }
4363
4364 switch (S->Kind) {
4365 case SK_ResolveAddressOfOverloadedFunction:
4366 OS << "resolve address of overloaded function";
4367 break;
4368
4369 case SK_CastDerivedToBaseRValue:
4370 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4371 break;
4372
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004373 case SK_CastDerivedToBaseXValue:
4374 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4375 break;
4376
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004377 case SK_CastDerivedToBaseLValue:
4378 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4379 break;
4380
4381 case SK_BindReference:
4382 OS << "bind reference to lvalue";
4383 break;
4384
4385 case SK_BindReferenceToTemporary:
4386 OS << "bind reference to a temporary";
4387 break;
4388
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004389 case SK_ExtraneousCopyToTemporary:
4390 OS << "extraneous C++03 copy to temporary";
4391 break;
4392
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004393 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004394 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004395 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004396
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004397 case SK_QualificationConversionRValue:
4398 OS << "qualification conversion (rvalue)";
4399
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004400 case SK_QualificationConversionXValue:
4401 OS << "qualification conversion (xvalue)";
4402
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004403 case SK_QualificationConversionLValue:
4404 OS << "qualification conversion (lvalue)";
4405 break;
4406
4407 case SK_ConversionSequence:
4408 OS << "implicit conversion sequence (";
4409 S->ICS->DebugPrint(); // FIXME: use OS
4410 OS << ")";
4411 break;
4412
4413 case SK_ListInitialization:
4414 OS << "list initialization";
4415 break;
4416
4417 case SK_ConstructorInitialization:
4418 OS << "constructor initialization";
4419 break;
4420
4421 case SK_ZeroInitialization:
4422 OS << "zero initialization";
4423 break;
4424
4425 case SK_CAssignment:
4426 OS << "C assignment";
4427 break;
4428
4429 case SK_StringInit:
4430 OS << "string initialization";
4431 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004432
4433 case SK_ObjCObjectConversion:
4434 OS << "Objective-C object conversion";
4435 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004436 }
4437 }
4438}
4439
4440void InitializationSequence::dump() const {
4441 dump(llvm::errs());
4442}
4443
Douglas Gregore1314a62009-12-18 05:02:21 +00004444//===----------------------------------------------------------------------===//
4445// Initialization helper functions
4446//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004447ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004448Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4449 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004450 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004451 if (Init.isInvalid())
4452 return ExprError();
4453
4454 Expr *InitE = (Expr *)Init.get();
4455 assert(InitE && "No initialization expression?");
4456
4457 if (EqualLoc.isInvalid())
4458 EqualLoc = InitE->getLocStart();
4459
4460 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4461 EqualLoc);
4462 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4463 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004464 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004465}