blob: 7b9c25e456483c81a781f6c6b0f8ac2ad85e9ddd [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"
21#include "clang/Sema/Sema.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
Douglas Gregor2bb07652009-12-22 00:05:34 +0000268 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
269 Sema::MultiExprArg(SemaRef, 0, 0));
270 if (MemberInit.isInvalid()) {
271 hadError = true;
272 return;
273 }
274
275 if (hadError) {
276 // Do nothing
277 } else if (Init < NumInits) {
278 ILE->setInit(Init, MemberInit.takeAs<Expr>());
279 } else if (InitSeq.getKind()
280 == InitializationSequence::ConstructorInitialization) {
281 // Value-initialization requires a constructor call, so
282 // extend the initializer list to include the constructor
283 // call and make a note that we'll need to take another pass
284 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000285 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000286 RequiresSecondPass = true;
287 }
288 } else if (InitListExpr *InnerILE
289 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
290 FillInValueInitializations(MemberEntity, InnerILE,
291 RequiresSecondPass);
292}
293
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000294/// Recursively replaces NULL values within the given initializer list
295/// with expressions that perform value-initialization of the
296/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000297void
298InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
299 InitListExpr *ILE,
300 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000301 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000302 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000303 SourceLocation Loc = ILE->getSourceRange().getBegin();
304 if (ILE->getSyntacticForm())
305 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000306
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000307 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000308 if (RType->getDecl()->isUnion() &&
309 ILE->getInitializedFieldInUnion())
310 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
311 Entity, ILE, RequiresSecondPass);
312 else {
313 unsigned Init = 0;
314 for (RecordDecl::field_iterator
315 Field = RType->getDecl()->field_begin(),
316 FieldEnd = RType->getDecl()->field_end();
317 Field != FieldEnd; ++Field) {
318 if (Field->isUnnamedBitfield())
319 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000320
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000322 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323
324 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
325 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000326 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000329
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 // Only look at the first initialization of a union.
331 if (RType->getDecl()->isUnion())
332 break;
333 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000334 }
335
336 return;
Mike Stump11289f42009-09-09 15:08:12 +0000337 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000338
339 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000340
Douglas Gregor723796a2009-12-16 06:35:08 +0000341 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000342 unsigned NumInits = ILE->getNumInits();
343 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000344 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000345 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000346 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
347 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000348 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
349 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000350 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000351 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000352 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000353 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
354 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000355 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000356 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Douglas Gregor723796a2009-12-16 06:35:08 +0000358
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000359 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000360 if (hadError)
361 return;
362
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000363 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
364 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000365 ElementEntity.setElementIndex(Init);
366
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000367 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000368 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
369 true);
370 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
371 if (!InitSeq) {
372 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000373 hadError = true;
374 return;
375 }
376
John McCalldadc5752010-08-24 06:29:42 +0000377 ExprResult ElementInit
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
379 Sema::MultiExprArg(SemaRef, 0, 0));
380 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000381 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000382 return;
383 }
384
385 if (hadError) {
386 // Do nothing
387 } else if (Init < NumInits) {
388 ILE->setInit(Init, ElementInit.takeAs<Expr>());
389 } else if (InitSeq.getKind()
390 == InitializationSequence::ConstructorInitialization) {
391 // Value-initialization requires a constructor call, so
392 // extend the initializer list to include the constructor
393 // call and make a note that we'll need to take another pass
394 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000395 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000396 RequiresSecondPass = true;
397 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000398 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
400 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000401 }
402}
403
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000404
Douglas Gregor723796a2009-12-16 06:35:08 +0000405InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
406 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000407 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000408 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000409
Eli Friedman23a9e312008-05-19 19:16:24 +0000410 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000411 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000412 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000413 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000414 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000415 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000416 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000417
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 if (!hadError) {
419 bool RequiresSecondPass = false;
420 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000421 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000422 FillInValueInitializations(Entity, FullyStructuredList,
423 RequiresSecondPass);
424 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000425}
426
427int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000428 // FIXME: use a proper constant
429 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000430 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000431 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000432 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
433 }
434 return maxElements;
435}
436
437int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000438 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000439 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000440 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000441 Field = structDecl->field_begin(),
442 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000443 Field != FieldEnd; ++Field) {
444 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
445 ++InitializableMembers;
446 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000447 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000448 return std::min(InitializableMembers, 1);
449 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000450}
451
Anders Carlsson6cabf312010-01-23 23:23:01 +0000452void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000453 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000454 QualType T, unsigned &Index,
455 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000456 unsigned &StructuredIndex,
457 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000458 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Steve Narofff8ecff22008-05-01 22:18:59 +0000460 if (T->isArrayType())
461 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000462 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000463 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000464 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000465 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000466 else
467 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000468
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000470 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000471 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000472 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000473 hadError = true;
474 return;
475 }
476
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000477 // Build a structured initializer list corresponding to this subobject.
478 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000479 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
480 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000481 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
482 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000483 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000484
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000485 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000486 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000487 CheckListElementTypes(Entity, ParentIList, T,
488 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000489 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000490 StructuredSubobjectInitIndex,
491 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000492 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000493 StructuredSubobjectInitList->setType(T);
494
Douglas Gregor5741efb2009-03-01 17:12:46 +0000495 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000496 // range corresponds with the end of the last initializer it used.
497 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000498 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000499 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
500 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
501 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000502
503 // Warn about missing braces.
504 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000505 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
506 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000507 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000508 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
509 "{")
510 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000511 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000512 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000513 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000514}
515
Anders Carlsson6cabf312010-01-23 23:23:01 +0000516void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000517 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000518 unsigned &Index,
519 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000520 unsigned &StructuredIndex,
521 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000522 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000523 SyntacticToSemantic[IList] = StructuredList;
524 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000525 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
526 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000527 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
528 IList->setType(ExprTy);
529 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000530 if (hadError)
531 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532
Eli Friedman85f54972008-05-25 13:22:35 +0000533 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000534 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000535 if (StructuredIndex == 1 &&
536 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000537 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000538 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000539 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000540 hadError = true;
541 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000542 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000543 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000544 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000545 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000546 // Don't complain for incomplete types, since we'll get an error
547 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000549 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000550 CurrentObjectType->isArrayType()? 0 :
551 CurrentObjectType->isVectorType()? 1 :
552 CurrentObjectType->isScalarType()? 2 :
553 CurrentObjectType->isUnionType()? 3 :
554 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000555
556 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000557 if (SemaRef.getLangOptions().CPlusPlus) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Nate Begeman425038c2009-07-07 21:53:06 +0000561 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000565
Chris Lattnerb0912a52009-02-24 22:50:46 +0000566 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000567 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000568 }
569 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000570
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000571 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000572 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000573 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000574 << FixItHint::CreateRemoval(IList->getLocStart())
575 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000576}
577
Anders Carlsson6cabf312010-01-23 23:23:01 +0000578void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000579 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000580 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000581 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000582 unsigned &Index,
583 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000584 unsigned &StructuredIndex,
585 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000586 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000587 CheckScalarType(Entity, IList, DeclType, Index,
588 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000590 CheckVectorType(Entity, IList, DeclType, Index,
591 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000595 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000602 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000603 CheckArrayType(Entity, IList, DeclType, Zero,
604 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000605 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000627 CheckReferenceType(Entity, IList, DeclType, Index,
628 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000629 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
631 << DeclType;
632 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000633 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000634 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
635 << DeclType;
636 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000637 }
638}
639
Anders Carlsson6cabf312010-01-23 23:23:01 +0000640void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000641 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000642 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 unsigned &Index,
644 InitListExpr *StructuredList,
645 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000646 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000647 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
648 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000650 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000651 = getStructuredSubobjectInit(IList, Index, ElemType,
652 StructuredList, StructuredIndex,
653 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000654 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 newStructuredList, newStructuredIndex);
656 ++StructuredIndex;
657 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000658 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
659 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000660 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000661 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000662 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000663 CheckScalarType(Entity, IList, ElemType, Index,
664 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000665 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000666 CheckReferenceType(Entity, IList, ElemType, Index,
667 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000668 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000669 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000670 // C++ [dcl.init.aggr]p12:
671 // All implicit type conversions (clause 4) are considered when
672 // initializing the aggregate member with an ini- tializer from
673 // an initializer-list. If the initializer can initialize a
674 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000675
Anders Carlsson0bd52402010-01-24 00:19:41 +0000676 // FIXME: Better EqualLoc?
677 InitializationKind Kind =
678 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
679 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
680
681 if (Seq) {
John McCalldadc5752010-08-24 06:29:42 +0000682 ExprResult Result =
Anders Carlsson0bd52402010-01-24 00:19:41 +0000683 Seq.Perform(SemaRef, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000684 Sema::MultiExprArg(SemaRef, &expr, 1));
Anders Carlsson0bd52402010-01-24 00:19:41 +0000685 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000686 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000687
688 UpdateStructuredListElement(StructuredList, StructuredIndex,
689 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000690 ++Index;
691 return;
692 }
693
694 // Fall through for subaggregate initialization
695 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000696 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000697 //
698 // The initializer for a structure or union object that has
699 // automatic storage duration shall be either an initializer
700 // list as described below, or a single expression that has
701 // compatible structure or union type. In the latter case, the
702 // initial value of the object, including unnamed members, is
703 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000704 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000705 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000706 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
707 ++Index;
708 return;
709 }
710
711 // Fall through for subaggregate initialization
712 }
713
714 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000715 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000716 // [...] Otherwise, if the member is itself a non-empty
717 // subaggregate, brace elision is assumed and the initializer is
718 // considered for the initialization of the first member of
719 // the subaggregate.
720 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000721 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000722 StructuredIndex);
723 ++StructuredIndex;
724 } else {
725 // We cannot initialize this element, so let
726 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000727 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
728 SemaRef.Owned(expr));
729 IList->setInit(Index, 0);
Douglas Gregord14247a2009-01-30 22:09:00 +0000730 hadError = true;
731 ++Index;
732 ++StructuredIndex;
733 }
734 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000735}
736
Anders Carlsson6cabf312010-01-23 23:23:01 +0000737void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000738 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000739 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000740 InitListExpr *StructuredList,
741 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000742 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000743 Expr *expr = IList->getInit(Index);
Eli Friedmandf239252010-08-14 03:14:53 +0000744 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
745 SemaRef.Diag(SubIList->getLocStart(),
746 diag::warn_many_braces_around_scalar_init)
747 << SubIList->getSourceRange();
748
749 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
750 StructuredIndex);
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000751 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000752 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000753 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000754 diag::err_designator_for_scalar_init)
755 << DeclType << expr->getSourceRange();
756 hadError = true;
757 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000758 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000759 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000760 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000761
John McCalldadc5752010-08-24 06:29:42 +0000762 ExprResult Result =
Eli Friedman673f94a2010-01-25 17:04:54 +0000763 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
764 SemaRef.Owned(expr));
Anders Carlsson26d05642010-01-23 18:35:41 +0000765
Chandler Carruthdfe198b2010-02-13 07:23:01 +0000766 Expr *ResultExpr = 0;
Anders Carlsson26d05642010-01-23 18:35:41 +0000767
768 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000769 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000770 else {
771 ResultExpr = Result.takeAs<Expr>();
772
773 if (ResultExpr != expr) {
774 // The type was promoted, update initializer list.
775 IList->setInit(Index, ResultExpr);
776 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000777 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000778 if (hadError)
779 ++StructuredIndex;
780 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000781 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000782 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000783 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000784 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000785 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000786 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000787 ++Index;
788 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000789 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000790 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000791}
792
Anders Carlsson6cabf312010-01-23 23:23:01 +0000793void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
794 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000795 unsigned &Index,
796 InitListExpr *StructuredList,
797 unsigned &StructuredIndex) {
798 if (Index < IList->getNumInits()) {
799 Expr *expr = IList->getInit(Index);
800 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000801 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000802 << DeclType << IList->getSourceRange();
803 hadError = true;
804 ++Index;
805 ++StructuredIndex;
806 return;
Mike Stump11289f42009-09-09 15:08:12 +0000807 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000808
John McCalldadc5752010-08-24 06:29:42 +0000809 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000810 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
811 SemaRef.Owned(expr));
812
813 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000814 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000815
816 expr = Result.takeAs<Expr>();
817 IList->setInit(Index, expr);
818
Douglas Gregord14247a2009-01-30 22:09:00 +0000819 if (hadError)
820 ++StructuredIndex;
821 else
822 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
823 ++Index;
824 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000825 // FIXME: It would be wonderful if we could point at the actual member. In
826 // general, it would be useful to pass location information down the stack,
827 // so that we know the location (or decl) of the "current object" being
828 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000829 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000830 diag::err_init_reference_member_uninitialized)
831 << DeclType
832 << IList->getSourceRange();
833 hadError = true;
834 ++Index;
835 ++StructuredIndex;
836 return;
837 }
838}
839
Anders Carlsson6cabf312010-01-23 23:23:01 +0000840void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000841 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000842 unsigned &Index,
843 InitListExpr *StructuredList,
844 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000845 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000846 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000847 unsigned maxElements = VT->getNumElements();
848 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000849 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000850
Nate Begeman5ec4b312009-08-10 23:49:36 +0000851 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000852 InitializedEntity ElementEntity =
853 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlssond0849252010-01-23 19:55:29 +0000854
Anders Carlsson6cabf312010-01-23 23:23:01 +0000855 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
856 // Don't attempt to go past the end of the init list
857 if (Index >= IList->getNumInits())
858 break;
Anders Carlssond0849252010-01-23 19:55:29 +0000859
Anders Carlsson6cabf312010-01-23 23:23:01 +0000860 ElementEntity.setElementIndex(Index);
861 CheckSubElementType(ElementEntity, IList, elementType, Index,
862 StructuredList, StructuredIndex);
863 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000864 } else {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000865 InitializedEntity ElementEntity =
866 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
867
Nate Begeman5ec4b312009-08-10 23:49:36 +0000868 // OpenCL initializers allows vectors to be constructed from vectors.
869 for (unsigned i = 0; i < maxElements; ++i) {
870 // Don't attempt to go past the end of the init list
871 if (Index >= IList->getNumInits())
872 break;
Anders Carlsson6cabf312010-01-23 23:23:01 +0000873
874 ElementEntity.setElementIndex(Index);
875
Nate Begeman5ec4b312009-08-10 23:49:36 +0000876 QualType IType = IList->getInit(Index)->getType();
877 if (!IType->isVectorType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000878 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000879 StructuredList, StructuredIndex);
880 ++numEltsInit;
881 } else {
Nate Begeman5da51d32010-07-07 22:26:56 +0000882 QualType VecType;
John McCall9dd450b2009-09-21 23:43:11 +0000883 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000884 unsigned numIElts = IVT->getNumElements();
Nate Begeman5da51d32010-07-07 22:26:56 +0000885
886 if (IType->isExtVectorType())
887 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
888 else
889 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
890 IVT->getAltiVecSpecific());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000891 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000892 StructuredList, StructuredIndex);
893 numEltsInit += numIElts;
894 }
895 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000896 }
Mike Stump11289f42009-09-09 15:08:12 +0000897
John Thompson7bc797b2010-04-20 23:21:17 +0000898 // OpenCL requires all elements to be initialized.
Nate Begeman5ec4b312009-08-10 23:49:36 +0000899 if (numEltsInit != maxElements)
Chris Lattnerb596ac72010-04-20 05:19:10 +0000900 if (SemaRef.getLangOptions().OpenCL)
Nate Begeman5ec4b312009-08-10 23:49:36 +0000901 SemaRef.Diag(IList->getSourceRange().getBegin(),
902 diag::err_vector_incorrect_num_initializers)
903 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000904 }
905}
906
Anders Carlsson6cabf312010-01-23 23:23:01 +0000907void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000908 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000909 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000910 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000911 unsigned &Index,
912 InitListExpr *StructuredList,
913 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 // Check for the special-case of initializing an array with a string.
915 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000916 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
917 SemaRef.Context)) {
918 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000919 // We place the string literal directly into the resulting
920 // initializer list. This is the only place where the structure
921 // of the structured initializer list doesn't match exactly,
922 // because doing so would involve allocating one character
923 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000924 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000925 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000926 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000927 return;
928 }
929 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000930 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000931 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000932 // Check for VLAs; in standard C it would be possible to check this
933 // earlier, but I don't know where clang accepts VLAs (gcc accepts
934 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000935 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000936 diag::err_variable_object_no_init)
937 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000938 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000939 ++Index;
940 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000941 return;
942 }
943
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000944 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000945 llvm::APSInt maxElements(elementIndex.getBitWidth(),
946 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000947 bool maxElementsKnown = false;
948 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000949 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000950 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000951 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000952 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000953 maxElementsKnown = true;
954 }
955
Chris Lattnerb0912a52009-02-24 22:50:46 +0000956 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000957 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000958 while (Index < IList->getNumInits()) {
959 Expr *Init = IList->getInit(Index);
960 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000961 // If we're not the subobject that matches up with the '{' for
962 // the designator, we shouldn't be handling the
963 // designator. Return immediately.
964 if (!SubobjectIsDesignatorContext)
965 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000966
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000967 // Handle this designated initializer. elementIndex will be
968 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000969 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000970 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000971 StructuredList, StructuredIndex, true,
972 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000973 hadError = true;
974 continue;
975 }
976
Douglas Gregor033d1252009-01-23 16:54:12 +0000977 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
978 maxElements.extend(elementIndex.getBitWidth());
979 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
980 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000981 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000982
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000983 // If the array is of incomplete type, keep track of the number of
984 // elements in the initializer.
985 if (!maxElementsKnown && elementIndex > maxElements)
986 maxElements = elementIndex;
987
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000988 continue;
989 }
990
991 // If we know the maximum number of elements, and we've already
992 // hit it, stop consuming elements in the initializer list.
993 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000994 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000995
Anders Carlsson6cabf312010-01-23 23:23:01 +0000996 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000997 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +0000998 Entity);
999 // Check this element.
1000 CheckSubElementType(ElementEntity, IList, elementType, Index,
1001 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001002 ++elementIndex;
1003
1004 // If the array is of incomplete type, keep track of the number of
1005 // elements in the initializer.
1006 if (!maxElementsKnown && elementIndex > maxElements)
1007 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001008 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001009 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001010 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001011 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001012 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001013 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001014 // Sizing an array implicitly to zero is not allowed by ISO C,
1015 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001016 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001017 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001018 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001019
Mike Stump11289f42009-09-09 15:08:12 +00001020 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001021 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001022 }
1023}
1024
Anders Carlsson6cabf312010-01-23 23:23:01 +00001025void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001026 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001027 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001028 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001029 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001030 unsigned &Index,
1031 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001032 unsigned &StructuredIndex,
1033 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001034 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001035
Eli Friedman23a9e312008-05-19 19:16:24 +00001036 // If the record is invalid, some of it's members are invalid. To avoid
1037 // confusion, we forgo checking the intializer for the entire record.
1038 if (structDecl->isInvalidDecl()) {
1039 hadError = true;
1040 return;
Mike Stump11289f42009-09-09 15:08:12 +00001041 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001042
1043 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1044 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001046 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001047 Field != FieldEnd; ++Field) {
1048 if (Field->getDeclName()) {
1049 StructuredList->setInitializedFieldInUnion(*Field);
1050 break;
1051 }
1052 }
1053 return;
1054 }
1055
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001056 // If structDecl is a forward declaration, this loop won't do
1057 // anything except look at designated initializers; That's okay,
1058 // because an error should get printed out elsewhere. It might be
1059 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001061 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001062 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001063 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001064 while (Index < IList->getNumInits()) {
1065 Expr *Init = IList->getInit(Index);
1066
1067 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001068 // If we're not the subobject that matches up with the '{' for
1069 // the designator, we shouldn't be handling the
1070 // designator. Return immediately.
1071 if (!SubobjectIsDesignatorContext)
1072 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001073
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001074 // Handle this designated initializer. Field will be updated to
1075 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001076 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001077 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001078 StructuredList, StructuredIndex,
1079 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001080 hadError = true;
1081
Douglas Gregora9add4e2009-02-12 19:00:39 +00001082 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001083
1084 // Disable check for missing fields when designators are used.
1085 // This matches gcc behaviour.
1086 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001087 continue;
1088 }
1089
1090 if (Field == FieldEnd) {
1091 // We've run out of fields. We're done.
1092 break;
1093 }
1094
Douglas Gregora9add4e2009-02-12 19:00:39 +00001095 // We've already initialized a member of a union. We're done.
1096 if (InitializedSomething && DeclType->isUnionType())
1097 break;
1098
Douglas Gregor91f84212008-12-11 16:49:14 +00001099 // If we've hit the flexible array member at the end, we're done.
1100 if (Field->getType()->isIncompleteArrayType())
1101 break;
1102
Douglas Gregor51695702009-01-29 16:53:55 +00001103 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001104 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001105 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001106 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001107 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001108
Anders Carlsson6cabf312010-01-23 23:23:01 +00001109 InitializedEntity MemberEntity =
1110 InitializedEntity::InitializeMember(*Field, &Entity);
1111 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1112 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001113 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001114
1115 if (DeclType->isUnionType()) {
1116 // Initialize the first field within the union.
1117 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001118 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001119
1120 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001121 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001122
John McCalle40b58e2010-03-11 19:32:38 +00001123 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001124 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001125 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1126 // It is possible we have one or more unnamed bitfields remaining.
1127 // Find first (if any) named field and emit warning.
1128 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1129 it != end; ++it) {
1130 if (!it->isUnnamedBitfield()) {
1131 SemaRef.Diag(IList->getSourceRange().getEnd(),
1132 diag::warn_missing_field_initializers) << it->getName();
1133 break;
1134 }
1135 }
1136 }
1137
Mike Stump11289f42009-09-09 15:08:12 +00001138 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001139 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001140 return;
1141
1142 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001143 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001144 (!isa<InitListExpr>(IList->getInit(Index)) ||
1145 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001146 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001147 diag::err_flexible_array_init_nonempty)
1148 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001149 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001150 << *Field;
1151 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001152 ++Index;
1153 return;
1154 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001155 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001156 diag::ext_flexible_array_init)
1157 << IList->getInit(Index)->getSourceRange().getBegin();
1158 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1159 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001160 }
1161
Anders Carlsson6cabf312010-01-23 23:23:01 +00001162 InitializedEntity MemberEntity =
1163 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001164
Anders Carlsson6cabf312010-01-23 23:23:01 +00001165 if (isa<InitListExpr>(IList->getInit(Index)))
1166 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1167 StructuredList, StructuredIndex);
1168 else
1169 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001170 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001171}
Steve Narofff8ecff22008-05-01 22:18:59 +00001172
Douglas Gregord5846a12009-04-15 06:41:24 +00001173/// \brief Expand a field designator that refers to a member of an
1174/// anonymous struct or union into a series of field designators that
1175/// refers to the field within the appropriate subobject.
1176///
1177/// Field/FieldIndex will be updated to point to the (new)
1178/// currently-designated field.
1179static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001180 DesignatedInitExpr *DIE,
1181 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001182 FieldDecl *Field,
1183 RecordDecl::field_iterator &FieldIter,
1184 unsigned &FieldIndex) {
1185 typedef DesignatedInitExpr::Designator Designator;
1186
1187 // Build the path from the current object to the member of the
1188 // anonymous struct/union (backwards).
1189 llvm::SmallVector<FieldDecl *, 4> Path;
1190 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001191
Douglas Gregord5846a12009-04-15 06:41:24 +00001192 // Build the replacement designators.
1193 llvm::SmallVector<Designator, 4> Replacements;
1194 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1195 FI = Path.rbegin(), FIEnd = Path.rend();
1196 FI != FIEnd; ++FI) {
1197 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001198 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001199 DIE->getDesignator(DesigIdx)->getDotLoc(),
1200 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1201 else
1202 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1203 SourceLocation()));
1204 Replacements.back().setField(*FI);
1205 }
1206
1207 // Expand the current designator into the set of replacement
1208 // designators, so we have a full subobject path down to where the
1209 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001210 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001211 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001212
Douglas Gregord5846a12009-04-15 06:41:24 +00001213 // Update FieldIter/FieldIndex;
1214 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001215 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001216 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001217 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001218 FieldIter != FEnd; ++FieldIter) {
1219 if (FieldIter->isUnnamedBitfield())
1220 continue;
1221
1222 if (*FieldIter == Path.back())
1223 return;
1224
1225 ++FieldIndex;
1226 }
1227
1228 assert(false && "Unable to find anonymous struct/union field");
1229}
1230
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001231/// @brief Check the well-formedness of a C99 designated initializer.
1232///
1233/// Determines whether the designated initializer @p DIE, which
1234/// resides at the given @p Index within the initializer list @p
1235/// IList, is well-formed for a current object of type @p DeclType
1236/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001237/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001238/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001239///
1240/// @param IList The initializer list in which this designated
1241/// initializer occurs.
1242///
Douglas Gregora5324162009-04-15 04:56:10 +00001243/// @param DIE The designated initializer expression.
1244///
1245/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001246///
1247/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1248/// into which the designation in @p DIE should refer.
1249///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001250/// @param NextField If non-NULL and the first designator in @p DIE is
1251/// a field, this will be set to the field declaration corresponding
1252/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001253///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001254/// @param NextElementIndex If non-NULL and the first designator in @p
1255/// DIE is an array designator or GNU array-range designator, this
1256/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001257///
1258/// @param Index Index into @p IList where the designated initializer
1259/// @p DIE occurs.
1260///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001261/// @param StructuredList The initializer list expression that
1262/// describes all of the subobject initializers in the order they'll
1263/// actually be initialized.
1264///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001265/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001266bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001267InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001268 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001269 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001270 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001271 QualType &CurrentObjectType,
1272 RecordDecl::field_iterator *NextField,
1273 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001274 unsigned &Index,
1275 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001276 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001277 bool FinishSubobjectInit,
1278 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001279 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001280 // Check the actual initialization for the designated object type.
1281 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001282
1283 // Temporarily remove the designator expression from the
1284 // initializer list that the child calls see, so that we don't try
1285 // to re-process the designator.
1286 unsigned OldIndex = Index;
1287 IList->setInit(OldIndex, DIE->getInit());
1288
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001289 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001290 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001291
1292 // Restore the designated initializer expression in the syntactic
1293 // form of the initializer list.
1294 if (IList->getInit(OldIndex) != DIE->getInit())
1295 DIE->setInit(IList->getInit(OldIndex));
1296 IList->setInit(OldIndex, DIE);
1297
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001298 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001299 }
1300
Douglas Gregora5324162009-04-15 04:56:10 +00001301 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001302 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001303 "Need a non-designated initializer list to start from");
1304
Douglas Gregora5324162009-04-15 04:56:10 +00001305 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001306 // Determine the structural initializer list that corresponds to the
1307 // current subobject.
1308 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001309 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001310 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001311 SourceRange(D->getStartLocation(),
1312 DIE->getSourceRange().getEnd()));
1313 assert(StructuredList && "Expected a structured initializer list");
1314
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001315 if (D->isFieldDesignator()) {
1316 // C99 6.7.8p7:
1317 //
1318 // If a designator has the form
1319 //
1320 // . identifier
1321 //
1322 // then the current object (defined below) shall have
1323 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001324 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001325 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001326 if (!RT) {
1327 SourceLocation Loc = D->getDotLoc();
1328 if (Loc.isInvalid())
1329 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001330 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1331 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001332 ++Index;
1333 return true;
1334 }
1335
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001336 // Note: we perform a linear search of the fields here, despite
1337 // the fact that we have a faster lookup method, because we always
1338 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001339 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001340 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001341 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001342 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001343 Field = RT->getDecl()->field_begin(),
1344 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001345 for (; Field != FieldEnd; ++Field) {
1346 if (Field->isUnnamedBitfield())
1347 continue;
1348
Douglas Gregord5846a12009-04-15 06:41:24 +00001349 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001350 break;
1351
1352 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001353 }
1354
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001355 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001356 // There was no normal field in the struct with the designated
1357 // name. Perform another lookup for this name, which may find
1358 // something that we can't designate (e.g., a member function),
1359 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001360 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001361 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001362 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001363 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001364 // Name lookup didn't find anything. Determine whether this
1365 // was a typo for another field name.
1366 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1367 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001368 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1369 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001370 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1371 ReplacementField->getDeclContext()->getLookupContext()
1372 ->Equals(RT->getDecl())) {
1373 SemaRef.Diag(D->getFieldLoc(),
1374 diag::err_field_designator_unknown_suggest)
1375 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001376 << FixItHint::CreateReplacement(D->getFieldLoc(),
1377 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001378 SemaRef.Diag(ReplacementField->getLocation(),
1379 diag::note_previous_decl)
1380 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001381 } else {
1382 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1383 << FieldName << CurrentObjectType;
1384 ++Index;
1385 return true;
1386 }
1387 } else if (!KnownField) {
1388 // Determine whether we found a field at all.
1389 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1390 }
1391
1392 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001393 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001394 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001395 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001396 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001397 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001398 ++Index;
1399 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001400 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001401
1402 if (!KnownField &&
1403 cast<RecordDecl>((ReplacementField)->getDeclContext())
1404 ->isAnonymousStructOrUnion()) {
1405 // Handle an field designator that refers to a member of an
1406 // anonymous struct or union.
1407 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1408 ReplacementField,
1409 Field, FieldIndex);
1410 D = DIE->getDesignator(DesigIdx);
1411 } else if (!KnownField) {
1412 // The replacement field comes from typo correction; find it
1413 // in the list of fields.
1414 FieldIndex = 0;
1415 Field = RT->getDecl()->field_begin();
1416 for (; Field != FieldEnd; ++Field) {
1417 if (Field->isUnnamedBitfield())
1418 continue;
1419
1420 if (ReplacementField == *Field ||
1421 Field->getIdentifier() == ReplacementField->getIdentifier())
1422 break;
1423
1424 ++FieldIndex;
1425 }
1426 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001427 } else if (!KnownField &&
1428 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001429 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001430 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1431 Field, FieldIndex);
1432 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001433 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001434
1435 // All of the fields of a union are located at the same place in
1436 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001437 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001438 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001439 StructuredList->setInitializedFieldInUnion(*Field);
1440 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001441
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001442 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001443 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001445 // Make sure that our non-designated initializer list has space
1446 // for a subobject corresponding to this field.
1447 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001448 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001449
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001450 // This designator names a flexible array member.
1451 if (Field->getType()->isIncompleteArrayType()) {
1452 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001453 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001454 // We can't designate an object within the flexible array
1455 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001456 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001457 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001458 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001459 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001460 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001461 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001462 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001463 << *Field;
1464 Invalid = true;
1465 }
1466
1467 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1468 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001469 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001470 diag::err_flexible_array_init_needs_braces)
1471 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001472 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001473 << *Field;
1474 Invalid = true;
1475 }
1476
1477 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001478 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001479 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001480 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001481 diag::err_flexible_array_init_nonempty)
1482 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001483 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001484 << *Field;
1485 Invalid = true;
1486 }
1487
1488 if (Invalid) {
1489 ++Index;
1490 return true;
1491 }
1492
1493 // Initialize the array.
1494 bool prevHadError = hadError;
1495 unsigned newStructuredIndex = FieldIndex;
1496 unsigned OldIndex = Index;
1497 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001498
1499 InitializedEntity MemberEntity =
1500 InitializedEntity::InitializeMember(*Field, &Entity);
1501 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001503
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001504 IList->setInit(OldIndex, DIE);
1505 if (hadError && !prevHadError) {
1506 ++Field;
1507 ++FieldIndex;
1508 if (NextField)
1509 *NextField = Field;
1510 StructuredIndex = FieldIndex;
1511 return true;
1512 }
1513 } else {
1514 // Recurse to check later designated subobjects.
1515 QualType FieldType = (*Field)->getType();
1516 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001517
1518 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001519 InitializedEntity::InitializeMember(*Field, &Entity);
1520 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001521 FieldType, 0, 0, Index,
1522 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001523 true, false))
1524 return true;
1525 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526
1527 // Find the position of the next field to be initialized in this
1528 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001529 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001530 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001531
1532 // If this the first designator, our caller will continue checking
1533 // the rest of this struct/class/union subobject.
1534 if (IsFirstDesignator) {
1535 if (NextField)
1536 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001537 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001538 return false;
1539 }
1540
Douglas Gregor17bd0942009-01-28 23:36:17 +00001541 if (!FinishSubobjectInit)
1542 return false;
1543
Douglas Gregord5846a12009-04-15 06:41:24 +00001544 // We've already initialized something in the union; we're done.
1545 if (RT->getDecl()->isUnion())
1546 return hadError;
1547
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001548 // Check the remaining fields within this class/struct/union subobject.
1549 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001550
Anders Carlsson6cabf312010-01-23 23:23:01 +00001551 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001552 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001553 return hadError && !prevHadError;
1554 }
1555
1556 // C99 6.7.8p6:
1557 //
1558 // If a designator has the form
1559 //
1560 // [ constant-expression ]
1561 //
1562 // then the current object (defined below) shall have array
1563 // type and the expression shall be an integer constant
1564 // expression. If the array is of unknown size, any
1565 // nonnegative value is valid.
1566 //
1567 // Additionally, cope with the GNU extension that permits
1568 // designators of the form
1569 //
1570 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001571 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001572 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001573 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574 << CurrentObjectType;
1575 ++Index;
1576 return true;
1577 }
1578
1579 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001580 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1581 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001582 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001583 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001584 DesignatedEndIndex = DesignatedStartIndex;
1585 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001586 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001587
Mike Stump11289f42009-09-09 15:08:12 +00001588
1589 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001590 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001591 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001592 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001594
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001595 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001596 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001597 }
1598
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001599 if (isa<ConstantArrayType>(AT)) {
1600 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001601 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1602 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1603 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1604 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1605 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001606 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001607 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001608 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609 << IndexExpr->getSourceRange();
1610 ++Index;
1611 return true;
1612 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001613 } else {
1614 // Make sure the bit-widths and signedness match.
1615 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1616 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001617 else if (DesignatedStartIndex.getBitWidth() <
1618 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001619 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1620 DesignatedStartIndex.setIsUnsigned(true);
1621 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 }
Mike Stump11289f42009-09-09 15:08:12 +00001623
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001624 // Make sure that our non-designated initializer list has space
1625 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001626 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001627 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001628 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001629
Douglas Gregor17bd0942009-01-28 23:36:17 +00001630 // Repeatedly perform subobject initializations in the range
1631 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001632
Douglas Gregor17bd0942009-01-28 23:36:17 +00001633 // Move to the next designator
1634 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1635 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001636
1637 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001638 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001639
Douglas Gregor17bd0942009-01-28 23:36:17 +00001640 while (DesignatedStartIndex <= DesignatedEndIndex) {
1641 // Recurse to check later designated subobjects.
1642 QualType ElementType = AT->getElementType();
1643 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001644
1645 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001646 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001647 ElementType, 0, 0, Index,
1648 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001649 (DesignatedStartIndex == DesignatedEndIndex),
1650 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651 return true;
1652
1653 // Move to the next index in the array that we'll be initializing.
1654 ++DesignatedStartIndex;
1655 ElementIndex = DesignatedStartIndex.getZExtValue();
1656 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001657
1658 // If this the first designator, our caller will continue checking
1659 // the rest of this array subobject.
1660 if (IsFirstDesignator) {
1661 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001662 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001664 return false;
1665 }
Mike Stump11289f42009-09-09 15:08:12 +00001666
Douglas Gregor17bd0942009-01-28 23:36:17 +00001667 if (!FinishSubobjectInit)
1668 return false;
1669
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001670 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001671 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001672 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001673 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001675 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001676}
1677
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001678// Get the structured initializer list for a subobject of type
1679// @p CurrentObjectType.
1680InitListExpr *
1681InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1682 QualType CurrentObjectType,
1683 InitListExpr *StructuredList,
1684 unsigned StructuredIndex,
1685 SourceRange InitRange) {
1686 Expr *ExistingInit = 0;
1687 if (!StructuredList)
1688 ExistingInit = SyntacticToSemantic[IList];
1689 else if (StructuredIndex < StructuredList->getNumInits())
1690 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001692 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1693 return Result;
1694
1695 if (ExistingInit) {
1696 // We are creating an initializer list that initializes the
1697 // subobjects of the current object, but there was already an
1698 // initialization that completely initialized the current
1699 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001700 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001701 // struct X { int a, b; };
1702 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001703 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001704 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1705 // designated initializer re-initializes the whole
1706 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001707 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001708 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001709 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001710 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001712 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001713 << ExistingInit->getSourceRange();
1714 }
1715
Mike Stump11289f42009-09-09 15:08:12 +00001716 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001717 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1718 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001719 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001720
Douglas Gregora8a089b2010-07-13 18:40:04 +00001721 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001722
Douglas Gregor6d00c992009-03-20 23:58:33 +00001723 // Pre-allocate storage for the structured initializer list.
1724 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001725 unsigned NumInits = 0;
1726 if (!StructuredList)
1727 NumInits = IList->getNumInits();
1728 else if (Index < IList->getNumInits()) {
1729 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1730 NumInits = SubList->getNumInits();
1731 }
1732
Mike Stump11289f42009-09-09 15:08:12 +00001733 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001734 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1735 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1736 NumElements = CAType->getSize().getZExtValue();
1737 // Simple heuristic so that we don't allocate a very large
1738 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001739 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001740 NumElements = 0;
1741 }
John McCall9dd450b2009-09-21 23:43:11 +00001742 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001743 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001744 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001745 RecordDecl *RDecl = RType->getDecl();
1746 if (RDecl->isUnion())
1747 NumElements = 1;
1748 else
Mike Stump11289f42009-09-09 15:08:12 +00001749 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001750 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001751 }
1752
Douglas Gregor221c9a52009-03-21 18:13:52 +00001753 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001754 NumElements = IList->getNumInits();
1755
Ted Kremenekac034612010-04-13 23:39:13 +00001756 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001757
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001758 // Link this new initializer list into the structured initializer
1759 // lists.
1760 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001761 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001762 else {
1763 Result->setSyntacticForm(IList);
1764 SyntacticToSemantic[IList] = Result;
1765 }
1766
1767 return Result;
1768}
1769
1770/// Update the initializer at index @p StructuredIndex within the
1771/// structured initializer list to the value @p expr.
1772void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1773 unsigned &StructuredIndex,
1774 Expr *expr) {
1775 // No structured initializer list to update
1776 if (!StructuredList)
1777 return;
1778
Ted Kremenekac034612010-04-13 23:39:13 +00001779 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1780 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001781 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001782 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001783 diag::warn_initializer_overrides)
1784 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001785 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001786 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001787 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001788 << PrevInit->getSourceRange();
1789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001791 ++StructuredIndex;
1792}
1793
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001794/// Check that the given Index expression is a valid array designator
1795/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001796/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001797/// and produces a reasonable diagnostic if there is a
1798/// failure. Returns true if there was an error, false otherwise. If
1799/// everything went okay, Value will receive the value of the constant
1800/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001801static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001802CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803 SourceLocation Loc = Index->getSourceRange().getBegin();
1804
1805 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001806 if (S.VerifyIntegerConstantExpression(Index, &Value))
1807 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001808
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001809 if (Value.isSigned() && Value.isNegative())
1810 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001811 << Value.toString(10) << Index->getSourceRange();
1812
Douglas Gregor51650d32009-01-23 21:04:18 +00001813 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001814 return false;
1815}
1816
John McCalldadc5752010-08-24 06:29:42 +00001817ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001819 bool GNUSyntax,
John McCalldadc5752010-08-24 06:29:42 +00001820 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001821 typedef DesignatedInitExpr::Designator ASTDesignator;
1822
1823 bool Invalid = false;
1824 llvm::SmallVector<ASTDesignator, 32> Designators;
1825 llvm::SmallVector<Expr *, 32> InitExpressions;
1826
1827 // Build designators and check array designator expressions.
1828 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1829 const Designator &D = Desig.getDesignator(Idx);
1830 switch (D.getKind()) {
1831 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001832 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001833 D.getFieldLoc()));
1834 break;
1835
1836 case Designator::ArrayDesignator: {
1837 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1838 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001839 if (!Index->isTypeDependent() &&
1840 !Index->isValueDependent() &&
1841 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842 Invalid = true;
1843 else {
1844 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001845 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001846 D.getRBracketLoc()));
1847 InitExpressions.push_back(Index);
1848 }
1849 break;
1850 }
1851
1852 case Designator::ArrayRangeDesignator: {
1853 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1854 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1855 llvm::APSInt StartValue;
1856 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001857 bool StartDependent = StartIndex->isTypeDependent() ||
1858 StartIndex->isValueDependent();
1859 bool EndDependent = EndIndex->isTypeDependent() ||
1860 EndIndex->isValueDependent();
1861 if ((!StartDependent &&
1862 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1863 (!EndDependent &&
1864 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001865 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001866 else {
1867 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001868 if (StartDependent || EndDependent) {
1869 // Nothing to compute.
1870 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001871 EndValue.extend(StartValue.getBitWidth());
1872 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1873 StartValue.extend(EndValue.getBitWidth());
1874
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001875 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001876 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001877 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001878 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1879 Invalid = true;
1880 } else {
1881 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001882 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001883 D.getEllipsisLoc(),
1884 D.getRBracketLoc()));
1885 InitExpressions.push_back(StartIndex);
1886 InitExpressions.push_back(EndIndex);
1887 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001888 }
1889 break;
1890 }
1891 }
1892 }
1893
1894 if (Invalid || Init.isInvalid())
1895 return ExprError();
1896
1897 // Clear out the expressions within the designation.
1898 Desig.ClearExprs(*this);
1899
1900 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001901 = DesignatedInitExpr::Create(Context,
1902 Designators.data(), Designators.size(),
1903 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001904 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001905 return Owned(DIE);
1906}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001907
Douglas Gregor723796a2009-12-16 06:35:08 +00001908bool Sema::CheckInitList(const InitializedEntity &Entity,
1909 InitListExpr *&InitList, QualType &DeclType) {
1910 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001911 if (!CheckInitList.HadError())
1912 InitList = CheckInitList.getFullyStructuredList();
1913
1914 return CheckInitList.HadError();
1915}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001917//===----------------------------------------------------------------------===//
1918// Initialization entity
1919//===----------------------------------------------------------------------===//
1920
Douglas Gregor723796a2009-12-16 06:35:08 +00001921InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1922 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001923 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001924{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001925 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1926 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001927 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001928 } else {
1929 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001930 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001931 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001932}
1933
1934InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001935 CXXBaseSpecifier *Base,
1936 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001937{
1938 InitializedEntity Result;
1939 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001940 Result.Base = reinterpret_cast<uintptr_t>(Base);
1941 if (IsInheritedVirtualBase)
1942 Result.Base |= 0x01;
1943
Douglas Gregor1b303932009-12-22 15:35:07 +00001944 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001945 return Result;
1946}
1947
Douglas Gregor85dabae2009-12-16 01:38:02 +00001948DeclarationName InitializedEntity::getName() const {
1949 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001950 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001951 if (!VariableOrMember)
1952 return DeclarationName();
1953 // Fall through
1954
1955 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001956 case EK_Member:
1957 return VariableOrMember->getDeclName();
1958
1959 case EK_Result:
1960 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001961 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001962 case EK_Temporary:
1963 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001964 case EK_ArrayElement:
1965 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001966 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001967 return DeclarationName();
1968 }
1969
1970 // Silence GCC warning
1971 return DeclarationName();
1972}
1973
Douglas Gregora4b592a2009-12-19 03:01:41 +00001974DeclaratorDecl *InitializedEntity::getDecl() const {
1975 switch (getKind()) {
1976 case EK_Variable:
1977 case EK_Parameter:
1978 case EK_Member:
1979 return VariableOrMember;
1980
1981 case EK_Result:
1982 case EK_Exception:
1983 case EK_New:
1984 case EK_Temporary:
1985 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001986 case EK_ArrayElement:
1987 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001988 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001989 return 0;
1990 }
1991
1992 // Silence GCC warning
1993 return 0;
1994}
1995
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001996bool InitializedEntity::allowsNRVO() const {
1997 switch (getKind()) {
1998 case EK_Result:
1999 case EK_Exception:
2000 return LocAndNRVO.NRVO;
2001
2002 case EK_Variable:
2003 case EK_Parameter:
2004 case EK_Member:
2005 case EK_New:
2006 case EK_Temporary:
2007 case EK_Base:
2008 case EK_ArrayElement:
2009 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002010 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002011 break;
2012 }
2013
2014 return false;
2015}
2016
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002017//===----------------------------------------------------------------------===//
2018// Initialization sequence
2019//===----------------------------------------------------------------------===//
2020
2021void InitializationSequence::Step::Destroy() {
2022 switch (Kind) {
2023 case SK_ResolveAddressOfOverloadedFunction:
2024 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002025 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002026 case SK_CastDerivedToBaseLValue:
2027 case SK_BindReference:
2028 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002029 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002030 case SK_UserConversion:
2031 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002032 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002033 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002034 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002035 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002036 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002037 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002038 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002039 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002040 break;
2041
2042 case SK_ConversionSequence:
2043 delete ICS;
2044 }
2045}
2046
Douglas Gregor838fcc32010-03-26 20:14:36 +00002047bool InitializationSequence::isDirectReferenceBinding() const {
2048 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2049}
2050
2051bool InitializationSequence::isAmbiguous() const {
2052 if (getKind() != FailedSequence)
2053 return false;
2054
2055 switch (getFailureKind()) {
2056 case FK_TooManyInitsForReference:
2057 case FK_ArrayNeedsInitList:
2058 case FK_ArrayNeedsInitListOrStringLiteral:
2059 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2060 case FK_NonConstLValueReferenceBindingToTemporary:
2061 case FK_NonConstLValueReferenceBindingToUnrelated:
2062 case FK_RValueReferenceBindingToLValue:
2063 case FK_ReferenceInitDropsQualifiers:
2064 case FK_ReferenceInitFailed:
2065 case FK_ConversionFailed:
2066 case FK_TooManyInitsForScalar:
2067 case FK_ReferenceBindingToInitList:
2068 case FK_InitListBadDestinationType:
2069 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002070 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002071 return false;
2072
2073 case FK_ReferenceInitOverloadFailed:
2074 case FK_UserConversionOverloadFailed:
2075 case FK_ConstructorOverloadFailed:
2076 return FailedOverloadResult == OR_Ambiguous;
2077 }
2078
2079 return false;
2080}
2081
Douglas Gregorb33eed02010-04-16 22:09:46 +00002082bool InitializationSequence::isConstructorInitialization() const {
2083 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2084}
2085
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002086void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002087 FunctionDecl *Function,
2088 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002089 Step S;
2090 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2091 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002092 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002093 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002094 Steps.push_back(S);
2095}
2096
2097void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002098 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002100 switch (VK) {
2101 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2102 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2103 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002104 default: llvm_unreachable("No such category");
2105 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002106 S.Type = BaseType;
2107 Steps.push_back(S);
2108}
2109
2110void InitializationSequence::AddReferenceBindingStep(QualType T,
2111 bool BindingTemporary) {
2112 Step S;
2113 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2114 S.Type = T;
2115 Steps.push_back(S);
2116}
2117
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002118void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2119 Step S;
2120 S.Kind = SK_ExtraneousCopyToTemporary;
2121 S.Type = T;
2122 Steps.push_back(S);
2123}
2124
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002125void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002126 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002127 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002128 Step S;
2129 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002130 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002131 S.Function.Function = Function;
2132 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002133 Steps.push_back(S);
2134}
2135
2136void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002137 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002138 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002139 switch (VK) {
2140 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002141 S.Kind = SK_QualificationConversionRValue;
2142 break;
John McCall2536c6d2010-08-25 10:28:54 +00002143 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002144 S.Kind = SK_QualificationConversionXValue;
2145 break;
John McCall2536c6d2010-08-25 10:28:54 +00002146 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002147 S.Kind = SK_QualificationConversionLValue;
2148 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002149 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002150 S.Type = Ty;
2151 Steps.push_back(S);
2152}
2153
2154void InitializationSequence::AddConversionSequenceStep(
2155 const ImplicitConversionSequence &ICS,
2156 QualType T) {
2157 Step S;
2158 S.Kind = SK_ConversionSequence;
2159 S.Type = T;
2160 S.ICS = new ImplicitConversionSequence(ICS);
2161 Steps.push_back(S);
2162}
2163
Douglas Gregor51e77d52009-12-10 17:56:55 +00002164void InitializationSequence::AddListInitializationStep(QualType T) {
2165 Step S;
2166 S.Kind = SK_ListInitialization;
2167 S.Type = T;
2168 Steps.push_back(S);
2169}
2170
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002171void
2172InitializationSequence::AddConstructorInitializationStep(
2173 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002174 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002175 QualType T) {
2176 Step S;
2177 S.Kind = SK_ConstructorInitialization;
2178 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002179 S.Function.Function = Constructor;
2180 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002181 Steps.push_back(S);
2182}
2183
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002184void InitializationSequence::AddZeroInitializationStep(QualType T) {
2185 Step S;
2186 S.Kind = SK_ZeroInitialization;
2187 S.Type = T;
2188 Steps.push_back(S);
2189}
2190
Douglas Gregore1314a62009-12-18 05:02:21 +00002191void InitializationSequence::AddCAssignmentStep(QualType T) {
2192 Step S;
2193 S.Kind = SK_CAssignment;
2194 S.Type = T;
2195 Steps.push_back(S);
2196}
2197
Eli Friedman78275202009-12-19 08:11:05 +00002198void InitializationSequence::AddStringInitStep(QualType T) {
2199 Step S;
2200 S.Kind = SK_StringInit;
2201 S.Type = T;
2202 Steps.push_back(S);
2203}
2204
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002205void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2206 Step S;
2207 S.Kind = SK_ObjCObjectConversion;
2208 S.Type = T;
2209 Steps.push_back(S);
2210}
2211
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2213 OverloadingResult Result) {
2214 SequenceKind = FailedSequence;
2215 this->Failure = Failure;
2216 this->FailedOverloadResult = Result;
2217}
2218
2219//===----------------------------------------------------------------------===//
2220// Attempt initialization
2221//===----------------------------------------------------------------------===//
2222
2223/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002224static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002225 const InitializedEntity &Entity,
2226 const InitializationKind &Kind,
2227 InitListExpr *InitList,
2228 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002229 // FIXME: We only perform rudimentary checking of list
2230 // initializations at this point, then assume that any list
2231 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002232 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002233 // do all of the necessary checking. C++0x initializer lists will
2234 // force us to perform more checking here.
2235 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2236
Douglas Gregor1b303932009-12-22 15:35:07 +00002237 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002238
2239 // C++ [dcl.init]p13:
2240 // If T is a scalar type, then a declaration of the form
2241 //
2242 // T x = { a };
2243 //
2244 // is equivalent to
2245 //
2246 // T x = a;
2247 if (DestType->isScalarType()) {
2248 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2249 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2250 return;
2251 }
2252
2253 // Assume scalar initialization from a single value works.
2254 } else if (DestType->isAggregateType()) {
2255 // Assume aggregate initialization works.
2256 } else if (DestType->isVectorType()) {
2257 // Assume vector initialization works.
2258 } else if (DestType->isReferenceType()) {
2259 // FIXME: C++0x defines behavior for this.
2260 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2261 return;
2262 } else if (DestType->isRecordType()) {
2263 // FIXME: C++0x defines behavior for this
2264 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2265 }
2266
2267 // Add a general "list initialization" step.
2268 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002269}
2270
2271/// \brief Try a reference initialization that involves calling a conversion
2272/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002273static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2274 const InitializedEntity &Entity,
2275 const InitializationKind &Kind,
2276 Expr *Initializer,
2277 bool AllowRValues,
2278 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002279 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002280 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2281 QualType T1 = cv1T1.getUnqualifiedType();
2282 QualType cv2T2 = Initializer->getType();
2283 QualType T2 = cv2T2.getUnqualifiedType();
2284
2285 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002286 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002287 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002288 T1, T2, DerivedToBase,
2289 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002290 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002291 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002292 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002293
2294 // Build the candidate set directly in the initialization sequence
2295 // structure, so that it will persist if we fail.
2296 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2297 CandidateSet.clear();
2298
2299 // Determine whether we are allowed to call explicit constructors or
2300 // explicit conversion operators.
2301 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2302
2303 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002304 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2305 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002306 // The type we're converting to is a class type. Enumerate its constructors
2307 // to see if there is a suitable conversion.
2308 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002309
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002311 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002312 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002313 NamedDecl *D = *Con;
2314 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2315
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002316 // Find the constructor (which may be a template).
2317 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002318 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002319 if (ConstructorTmpl)
2320 Constructor = cast<CXXConstructorDecl>(
2321 ConstructorTmpl->getTemplatedDecl());
2322 else
John McCalla0296f72010-03-19 07:35:19 +00002323 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002324
2325 if (!Constructor->isInvalidDecl() &&
2326 Constructor->isConvertingConstructor(AllowExplicit)) {
2327 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002328 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002329 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002330 &Initializer, 1, CandidateSet);
2331 else
John McCalla0296f72010-03-19 07:35:19 +00002332 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002333 &Initializer, 1, CandidateSet);
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
John McCall5c32be02010-08-24 20:38:10 +00002394 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
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
John McCall5c32be02010-08-24 20:38:10 +00002986 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
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 Gregorc9cd64e2010-04-18 07:40:54 +00003281 QualType T,
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003282 const InitializedEntity &Entity,
John McCalldadc5752010-08-24 06:29:42 +00003283 ExprResult CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003284 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.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003308 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003309 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregore1314a62009-12-18 05:02:21 +00003310 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003311 switch (Entity.getKind()) {
3312 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003313 Loc = Entity.getReturnLoc();
3314 break;
3315
3316 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003317 Loc = Entity.getThrowLoc();
3318 break;
3319
3320 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003321 Loc = Entity.getDecl()->getLocation();
3322 break;
3323
Anders Carlsson0bd52402010-01-24 00:19:41 +00003324 case InitializedEntity::EK_ArrayElement:
3325 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003326 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003327 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003328 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003329 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003330 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003331 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003332 Loc = CurInitExpr->getLocStart();
3333 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003334 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003335
3336 // Make sure that the type we are copying is complete.
3337 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3338 return move(CurInit);
3339
Douglas Gregore1314a62009-12-18 05:02:21 +00003340 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003341 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003342 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003343 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003344 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003345 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003346 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3347 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003348 !Constructor->isCopyConstructor() ||
3349 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003350 continue;
John McCalla0296f72010-03-19 07:35:19 +00003351
3352 DeclAccessPair FoundDecl
3353 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3354 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003355 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003356 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003357
3358 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003359 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003360 case OR_Success:
3361 break;
3362
3363 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003364 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3365 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3366 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003367 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003368 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003369 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003370 if (!IsExtraneousCopy || S.isSFINAEContext())
3371 return S.ExprError();
3372 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003373
3374 case OR_Ambiguous:
3375 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003376 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003377 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003378 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003379 return S.ExprError();
3380
3381 case OR_Deleted:
3382 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003383 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003384 << CurInitExpr->getSourceRange();
3385 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3386 << Best->Function->isDeleted();
3387 return S.ExprError();
3388 }
3389
Douglas Gregor5ab11652010-04-17 22:01:05 +00003390 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003391 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003392 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003393
Anders Carlssona01874b2010-04-21 18:47:17 +00003394 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003395 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003396
3397 if (IsExtraneousCopy) {
3398 // If this is a totally extraneous copy for C++03 reference
3399 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003400 // expression. We don't generate an (elided) copy operation here
3401 // because doing so would require us to pass down a flag to avoid
3402 // infinite recursion, where each step adds another extraneous,
3403 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003404
Douglas Gregor30b52772010-04-18 07:57:34 +00003405 // Instantiate the default arguments of any extra parameters in
3406 // the selected copy constructor, as if we were going to create a
3407 // proper call to the copy constructor.
3408 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3409 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3410 if (S.RequireCompleteType(Loc, Parm->getType(),
3411 S.PDiag(diag::err_call_incomplete_argument)))
3412 break;
3413
3414 // Build the default argument expression; we don't actually care
3415 // if this succeeds or not, because this routine will complain
3416 // if there was a problem.
3417 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3418 }
3419
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003420 return S.Owned(CurInitExpr);
3421 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003422
3423 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003424 // constructor call (we might have derived-to-base conversions, or
3425 // the copy constructor may have default arguments).
Douglas Gregor5ab11652010-04-17 22:01:05 +00003426 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003427 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003428 Loc, ConstructorArgs))
3429 return S.ExprError();
3430
Douglas Gregord0ace022010-04-25 00:55:24 +00003431 // Actually perform the constructor call.
3432 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003433 move_arg(ConstructorArgs),
3434 /*ZeroInit*/ false,
3435 CXXConstructExpr::CK_Complete);
Douglas Gregord0ace022010-04-25 00:55:24 +00003436
3437 // If we're supposed to bind temporaries, do so.
3438 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3439 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3440 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003441}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003442
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003443void InitializationSequence::PrintInitLocationNote(Sema &S,
3444 const InitializedEntity &Entity) {
3445 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3446 if (Entity.getDecl()->getLocation().isInvalid())
3447 return;
3448
3449 if (Entity.getDecl()->getDeclName())
3450 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3451 << Entity.getDecl()->getDeclName();
3452 else
3453 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3454 }
3455}
3456
John McCalldadc5752010-08-24 06:29:42 +00003457ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003458InitializationSequence::Perform(Sema &S,
3459 const InitializedEntity &Entity,
3460 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003461 Action::MultiExprArg Args,
3462 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003463 if (SequenceKind == FailedSequence) {
3464 unsigned NumArgs = Args.size();
3465 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3466 return S.ExprError();
3467 }
3468
3469 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003470 // If the declaration is a non-dependent, incomplete array type
3471 // that has an initializer, then its type will be completed once
3472 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003473 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003474 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003475 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003476 if (const IncompleteArrayType *ArrayT
3477 = S.Context.getAsIncompleteArrayType(DeclType)) {
3478 // FIXME: We don't currently have the ability to accurately
3479 // compute the length of an initializer list without
3480 // performing full type-checking of the initializer list
3481 // (since we have to determine where braces are implicitly
3482 // introduced and such). So, we fall back to making the array
3483 // type a dependently-sized array type with no specified
3484 // bound.
3485 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3486 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003487
Douglas Gregor51e77d52009-12-10 17:56:55 +00003488 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003489 if (DeclaratorDecl *DD = Entity.getDecl()) {
3490 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3491 TypeLoc TL = TInfo->getTypeLoc();
3492 if (IncompleteArrayTypeLoc *ArrayLoc
3493 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3494 Brackets = ArrayLoc->getBracketsRange();
3495 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003496 }
3497
3498 *ResultType
3499 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3500 /*NumElts=*/0,
3501 ArrayT->getSizeModifier(),
3502 ArrayT->getIndexTypeCVRQualifiers(),
3503 Brackets);
3504 }
3505
3506 }
3507 }
3508
Eli Friedmana553d4a2009-12-22 02:35:53 +00003509 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003510 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003511
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003512 if (Args.size() == 0)
3513 return S.Owned((Expr *)0);
3514
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003515 unsigned NumArgs = Args.size();
3516 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3517 SourceLocation(),
3518 (Expr **)Args.release(),
3519 NumArgs,
3520 SourceLocation()));
3521 }
3522
Douglas Gregor85dabae2009-12-16 01:38:02 +00003523 if (SequenceKind == NoInitialization)
3524 return S.Owned((Expr *)0);
3525
Douglas Gregor1b303932009-12-22 15:35:07 +00003526 QualType DestType = Entity.getType().getNonReferenceType();
3527 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003528 // the same as Entity.getDecl()->getType() in cases involving type merging,
3529 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003530 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003531 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003532 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003533
John McCalldadc5752010-08-24 06:29:42 +00003534 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003535
3536 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3537
3538 // For initialization steps that start with a single initializer,
3539 // grab the only argument out the Args and place it into the "current"
3540 // initializer.
3541 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003542 case SK_ResolveAddressOfOverloadedFunction:
3543 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003544 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003545 case SK_CastDerivedToBaseLValue:
3546 case SK_BindReference:
3547 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003548 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003549 case SK_UserConversion:
3550 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003551 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003552 case SK_QualificationConversionRValue:
3553 case SK_ConversionSequence:
3554 case SK_ListInitialization:
3555 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003556 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003557 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003558 assert(Args.size() == 1);
John McCalldadc5752010-08-24 06:29:42 +00003559 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregore1314a62009-12-18 05:02:21 +00003560 if (CurInit.isInvalid())
3561 return S.ExprError();
3562 break;
3563
3564 case SK_ConstructorInitialization:
3565 case SK_ZeroInitialization:
3566 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003567 }
3568
3569 // Walk through the computed steps for the initialization sequence,
3570 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003571 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003572 for (step_iterator Step = step_begin(), StepEnd = step_end();
3573 Step != StepEnd; ++Step) {
3574 if (CurInit.isInvalid())
3575 return S.ExprError();
3576
3577 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003578 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003579
3580 switch (Step->Kind) {
3581 case SK_ResolveAddressOfOverloadedFunction:
3582 // Overload resolution determined which function invoke; update the
3583 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003584 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003585 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003586 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003587 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003588 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003589 break;
3590
3591 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003592 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003593 case SK_CastDerivedToBaseLValue: {
3594 // We have a derived-to-base cast that produces either an rvalue or an
3595 // lvalue. Perform that cast.
3596
John McCallcf142162010-08-07 06:22:56 +00003597 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003598
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003599 // Casts to inaccessible base classes are allowed with C-style casts.
3600 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3601 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3602 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003603 CurInitExpr->getSourceRange(),
3604 &BasePath, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003605 return S.ExprError();
3606
Douglas Gregor88d292c2010-05-13 16:44:06 +00003607 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3608 QualType T = SourceType;
3609 if (const PointerType *Pointer = T->getAs<PointerType>())
3610 T = Pointer->getPointeeType();
3611 if (const RecordType *RecordTy = T->getAs<RecordType>())
3612 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3613 cast<CXXRecordDecl>(RecordTy->getDecl()));
3614 }
3615
John McCall2536c6d2010-08-25 10:28:54 +00003616 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003617 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003618 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003619 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003620 VK_XValue :
3621 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003622 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3623 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003624 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003625 CurInit.get(),
3626 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627 break;
3628 }
3629
3630 case SK_BindReference:
3631 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3632 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3633 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003634 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003635 << BitField->getDeclName()
3636 << CurInitExpr->getSourceRange();
3637 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3638 return S.ExprError();
3639 }
Anders Carlssona91be642010-01-29 02:47:33 +00003640
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003641 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003642 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003643 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3644 << Entity.getType().isVolatileQualified()
3645 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003646 PrintInitLocationNote(S, Entity);
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003647 return S.ExprError();
3648 }
3649
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650 // Reference binding does not have any corresponding ASTs.
3651
3652 // Check exception specifications
3653 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3654 return S.ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003657
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003658 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003659 // Reference binding does not have any corresponding ASTs.
3660
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661 // Check exception specifications
3662 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3663 return S.ExprError();
3664
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003665 break;
3666
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003667 case SK_ExtraneousCopyToTemporary:
3668 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3669 /*IsExtraneousCopy=*/true);
3670 break;
3671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 case SK_UserConversion: {
3673 // We have a user-defined conversion that invokes either a constructor
3674 // or a conversion function.
John McCalle3027922010-08-25 11:45:40 +00003675 CastKind CastKind = CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003676 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003677 FunctionDecl *Fn = Step->Function.Function;
3678 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003679 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003680 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003681 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003682 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003683 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003684 SourceLocation Loc = CurInitExpr->getLocStart();
3685 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003686
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003687 // Determine the arguments required to actually perform the constructor
3688 // call.
3689 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003690 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003691 Loc, ConstructorArgs))
3692 return S.ExprError();
3693
3694 // Build the an expression that constructs a temporary.
3695 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003696 move_arg(ConstructorArgs),
3697 /*ZeroInit*/ false,
3698 CXXConstructExpr::CK_Complete);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003699 if (CurInit.isInvalid())
3700 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003701
Anders Carlssona01874b2010-04-21 18:47:17 +00003702 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003703 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003704 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003705
John McCalle3027922010-08-25 11:45:40 +00003706 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003707 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3708 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3709 S.IsDerivedFrom(SourceType, Class))
3710 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003711
3712 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003713 } else {
3714 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003715 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003716 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003717 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003718 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003719 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003720
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003721 // FIXME: Should we move this initialization into a separate
3722 // derived-to-base conversion? I believe the answer is "no", because
3723 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003724 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003725 FoundFn, Conversion))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003726 return S.ExprError();
3727
3728 // Do a little dance to make sure that CurInit has the proper
3729 // pointer.
3730 CurInit.release();
3731
3732 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003733 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3734 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735 if (CurInit.isInvalid() || !CurInit.get())
3736 return S.ExprError();
3737
John McCalle3027922010-08-25 11:45:40 +00003738 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003739
3740 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003741 }
3742
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003743 bool RequiresCopy = !IsCopy &&
3744 getKind() != InitializationSequence::ReferenceBinding;
3745 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003746 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003747 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3748 CurInitExpr = static_cast<Expr *>(CurInit.get());
3749 QualType T = CurInitExpr->getType();
3750 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003751 CXXDestructorDecl *Destructor
3752 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003753 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3754 S.PDiag(diag::err_access_dtor_temp) << T);
3755 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3756 }
3757 }
3758
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003760 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003761 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3762 CurInitExpr->getType(),
3763 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003764 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003765
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003766 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003767 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3768 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003770 break;
3771 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003772
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003773 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003774 case SK_QualificationConversionXValue:
3775 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003776 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003777 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003778 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003779 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003780 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003781 VK_XValue :
3782 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003783 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003784 CurInit.release();
3785 CurInit = S.Owned(CurInitExpr);
3786 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003787 }
3788
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003789 case SK_ConversionSequence: {
3790 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3791
3792 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3793 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003794 return S.ExprError();
3795
3796 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003797 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003798 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003799 }
3800
Douglas Gregor51e77d52009-12-10 17:56:55 +00003801 case SK_ListInitialization: {
3802 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3803 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003804 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003805 return S.ExprError();
3806
3807 CurInit.release();
3808 CurInit = S.Owned(InitList);
3809 break;
3810 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003811
3812 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003813 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003814 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003815 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003816
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003817 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003818 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003819 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3820 ? Kind.getEqualLoc()
3821 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003822
3823 if (Kind.getKind() == InitializationKind::IK_Default) {
3824 // Force even a trivial, implicit default constructor to be
3825 // semantically checked. We do this explicitly because we don't build
3826 // the definition for completely trivial constructors.
3827 CXXRecordDecl *ClassDecl = Constructor->getParent();
3828 assert(ClassDecl && "No parent class for constructor.");
3829 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3830 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3831 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3832 }
3833
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003834 // Determine the arguments required to actually perform the constructor
3835 // call.
3836 if (S.CompleteConstructorCall(Constructor, move(Args),
3837 Loc, ConstructorArgs))
3838 return S.ExprError();
3839
Chandler Carruthc9262402010-08-23 07:55:51 +00003840
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003841 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003842 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003843 (Kind.getKind() == InitializationKind::IK_Direct ||
3844 Kind.getKind() == InitializationKind::IK_Value)) {
3845 // An explicitly-constructed temporary, e.g., X(1, 2).
3846 unsigned NumExprs = ConstructorArgs.size();
3847 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003848 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003849 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3850 Constructor,
3851 Entity.getType(),
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003852 Loc,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003853 Exprs,
3854 NumExprs,
Douglas Gregor199db362010-04-27 20:36:09 +00003855 Kind.getParenRange().getEnd(),
3856 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003857 } else {
3858 CXXConstructExpr::ConstructionKind ConstructKind =
3859 CXXConstructExpr::CK_Complete;
3860
3861 if (Entity.getKind() == InitializedEntity::EK_Base) {
3862 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3863 CXXConstructExpr::CK_VirtualBase :
3864 CXXConstructExpr::CK_NonVirtualBase;
3865 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003866
3867 // If the entity allows NRVO, mark the construction as elidable
3868 // unconditionally.
3869 if (Entity.allowsNRVO())
3870 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3871 Constructor, /*Elidable=*/true,
3872 move_arg(ConstructorArgs),
3873 ConstructorInitRequiresZeroInit,
3874 ConstructKind);
3875 else
3876 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3877 Constructor,
3878 move_arg(ConstructorArgs),
3879 ConstructorInitRequiresZeroInit,
3880 ConstructKind);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003881 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003882 if (CurInit.isInvalid())
3883 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003884
3885 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003886 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003887 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003888 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003889
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003890 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003891 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003892
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003893 break;
3894 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003895
3896 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003897 step_iterator NextStep = Step;
3898 ++NextStep;
3899 if (NextStep != StepEnd &&
3900 NextStep->Kind == SK_ConstructorInitialization) {
3901 // The need for zero-initialization is recorded directly into
3902 // the call to the object's constructor within the next step.
3903 ConstructorInitRequiresZeroInit = true;
3904 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3905 S.getLangOptions().CPlusPlus &&
3906 !Kind.isImplicitValueInit()) {
Douglas Gregor747eb782010-07-08 06:14:04 +00003907 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003908 Kind.getRange().getBegin(),
3909 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003910 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003911 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003912 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003913 break;
3914 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003915
3916 case SK_CAssignment: {
3917 QualType SourceType = CurInitExpr->getType();
3918 Sema::AssignConvertType ConvTy =
3919 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003920
3921 // If this is a call, allow conversion to a transparent union.
3922 if (ConvTy != Sema::Compatible &&
3923 Entity.getKind() == InitializedEntity::EK_Parameter &&
3924 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3925 == Sema::Compatible)
3926 ConvTy = Sema::Compatible;
3927
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003928 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003929 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3930 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003931 CurInitExpr,
3932 getAssignmentAction(Entity),
3933 &Complained)) {
3934 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003935 return S.ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003936 } else if (Complained)
3937 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003938
3939 CurInit.release();
3940 CurInit = S.Owned(CurInitExpr);
3941 break;
3942 }
Eli Friedman78275202009-12-19 08:11:05 +00003943
3944 case SK_StringInit: {
3945 QualType Ty = Step->Type;
3946 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3947 break;
3948 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003949
3950 case SK_ObjCObjectConversion:
3951 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003952 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003953 S.CastCategory(CurInitExpr));
3954 CurInit.release();
3955 CurInit = S.Owned(CurInitExpr);
3956 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003957 }
3958 }
3959
3960 return move(CurInit);
3961}
3962
3963//===----------------------------------------------------------------------===//
3964// Diagnose initialization failures
3965//===----------------------------------------------------------------------===//
3966bool InitializationSequence::Diagnose(Sema &S,
3967 const InitializedEntity &Entity,
3968 const InitializationKind &Kind,
3969 Expr **Args, unsigned NumArgs) {
3970 if (SequenceKind != FailedSequence)
3971 return false;
3972
Douglas Gregor1b303932009-12-22 15:35:07 +00003973 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003974 switch (Failure) {
3975 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003976 // FIXME: Customize for the initialized entity?
3977 if (NumArgs == 0)
3978 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3979 << DestType.getNonReferenceType();
3980 else // FIXME: diagnostic below could be better!
3981 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3982 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003983 break;
3984
3985 case FK_ArrayNeedsInitList:
3986 case FK_ArrayNeedsInitListOrStringLiteral:
3987 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3988 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3989 break;
3990
John McCall16df1e52010-03-30 21:47:33 +00003991 case FK_AddressOfOverloadFailed: {
3992 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003993 S.ResolveAddressOfOverloadedFunction(Args[0],
3994 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00003995 true,
3996 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003997 break;
John McCall16df1e52010-03-30 21:47:33 +00003998 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003999
4000 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004001 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004002 switch (FailedOverloadResult) {
4003 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004004 if (Failure == FK_UserConversionOverloadFailed)
4005 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4006 << Args[0]->getType() << DestType
4007 << Args[0]->getSourceRange();
4008 else
4009 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4010 << DestType << Args[0]->getType()
4011 << Args[0]->getSourceRange();
4012
John McCall5c32be02010-08-24 20:38:10 +00004013 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004014 break;
4015
4016 case OR_No_Viable_Function:
4017 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4018 << Args[0]->getType() << DestType.getNonReferenceType()
4019 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004020 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004021 break;
4022
4023 case OR_Deleted: {
4024 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4025 << Args[0]->getType() << DestType.getNonReferenceType()
4026 << Args[0]->getSourceRange();
4027 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004028 OverloadingResult Ovl
4029 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004030 if (Ovl == OR_Deleted) {
4031 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4032 << Best->Function->isDeleted();
4033 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004034 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004035 }
4036 break;
4037 }
4038
4039 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004040 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041 break;
4042 }
4043 break;
4044
4045 case FK_NonConstLValueReferenceBindingToTemporary:
4046 case FK_NonConstLValueReferenceBindingToUnrelated:
4047 S.Diag(Kind.getLocation(),
4048 Failure == FK_NonConstLValueReferenceBindingToTemporary
4049 ? diag::err_lvalue_reference_bind_to_temporary
4050 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004051 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004052 << DestType.getNonReferenceType()
4053 << Args[0]->getType()
4054 << Args[0]->getSourceRange();
4055 break;
4056
4057 case FK_RValueReferenceBindingToLValue:
4058 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4059 << Args[0]->getSourceRange();
4060 break;
4061
4062 case FK_ReferenceInitDropsQualifiers:
4063 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4064 << DestType.getNonReferenceType()
4065 << Args[0]->getType()
4066 << Args[0]->getSourceRange();
4067 break;
4068
4069 case FK_ReferenceInitFailed:
4070 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4071 << DestType.getNonReferenceType()
4072 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4073 << Args[0]->getType()
4074 << Args[0]->getSourceRange();
4075 break;
4076
4077 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004078 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4079 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004080 << DestType
4081 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4082 << Args[0]->getType()
4083 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004084 break;
4085
4086 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004087 SourceRange R;
4088
4089 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4090 R = SourceRange(InitList->getInit(1)->getLocStart(),
4091 InitList->getLocEnd());
4092 else
4093 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004094
4095 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00004096 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004097 break;
4098 }
4099
4100 case FK_ReferenceBindingToInitList:
4101 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4102 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4103 break;
4104
4105 case FK_InitListBadDestinationType:
4106 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4107 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4108 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004109
4110 case FK_ConstructorOverloadFailed: {
4111 SourceRange ArgsRange;
4112 if (NumArgs)
4113 ArgsRange = SourceRange(Args[0]->getLocStart(),
4114 Args[NumArgs - 1]->getLocEnd());
4115
4116 // FIXME: Using "DestType" for the entity we're printing is probably
4117 // bad.
4118 switch (FailedOverloadResult) {
4119 case OR_Ambiguous:
4120 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4121 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004122 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4123 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004124 break;
4125
4126 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004127 if (Kind.getKind() == InitializationKind::IK_Default &&
4128 (Entity.getKind() == InitializedEntity::EK_Base ||
4129 Entity.getKind() == InitializedEntity::EK_Member) &&
4130 isa<CXXConstructorDecl>(S.CurContext)) {
4131 // This is implicit default initialization of a member or
4132 // base within a constructor. If no viable function was
4133 // found, notify the user that she needs to explicitly
4134 // initialize this base/member.
4135 CXXConstructorDecl *Constructor
4136 = cast<CXXConstructorDecl>(S.CurContext);
4137 if (Entity.getKind() == InitializedEntity::EK_Base) {
4138 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4139 << Constructor->isImplicit()
4140 << S.Context.getTypeDeclType(Constructor->getParent())
4141 << /*base=*/0
4142 << Entity.getType();
4143
4144 RecordDecl *BaseDecl
4145 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4146 ->getDecl();
4147 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4148 << S.Context.getTagDeclType(BaseDecl);
4149 } else {
4150 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4151 << Constructor->isImplicit()
4152 << S.Context.getTypeDeclType(Constructor->getParent())
4153 << /*member=*/1
4154 << Entity.getName();
4155 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4156
4157 if (const RecordType *Record
4158 = Entity.getType()->getAs<RecordType>())
4159 S.Diag(Record->getDecl()->getLocation(),
4160 diag::note_previous_decl)
4161 << S.Context.getTagDeclType(Record->getDecl());
4162 }
4163 break;
4164 }
4165
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004166 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4167 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004168 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004169 break;
4170
4171 case OR_Deleted: {
4172 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4173 << true << DestType << ArgsRange;
4174 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004175 OverloadingResult Ovl
4176 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004177 if (Ovl == OR_Deleted) {
4178 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4179 << Best->Function->isDeleted();
4180 } else {
4181 llvm_unreachable("Inconsistent overload resolution?");
4182 }
4183 break;
4184 }
4185
4186 case OR_Success:
4187 llvm_unreachable("Conversion did not fail!");
4188 break;
4189 }
4190 break;
4191 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004192
4193 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004194 if (Entity.getKind() == InitializedEntity::EK_Member &&
4195 isa<CXXConstructorDecl>(S.CurContext)) {
4196 // This is implicit default-initialization of a const member in
4197 // a constructor. Complain that it needs to be explicitly
4198 // initialized.
4199 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4200 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4201 << Constructor->isImplicit()
4202 << S.Context.getTypeDeclType(Constructor->getParent())
4203 << /*const=*/1
4204 << Entity.getName();
4205 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4206 << Entity.getName();
4207 } else {
4208 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4209 << DestType << (bool)DestType->getAs<RecordType>();
4210 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004211 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004212
4213 case FK_Incomplete:
4214 S.RequireCompleteType(Kind.getLocation(), DestType,
4215 diag::err_init_incomplete_type);
4216 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004217 }
4218
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004219 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004220 return true;
4221}
Douglas Gregore1314a62009-12-18 05:02:21 +00004222
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004223void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4224 switch (SequenceKind) {
4225 case FailedSequence: {
4226 OS << "Failed sequence: ";
4227 switch (Failure) {
4228 case FK_TooManyInitsForReference:
4229 OS << "too many initializers for reference";
4230 break;
4231
4232 case FK_ArrayNeedsInitList:
4233 OS << "array requires initializer list";
4234 break;
4235
4236 case FK_ArrayNeedsInitListOrStringLiteral:
4237 OS << "array requires initializer list or string literal";
4238 break;
4239
4240 case FK_AddressOfOverloadFailed:
4241 OS << "address of overloaded function failed";
4242 break;
4243
4244 case FK_ReferenceInitOverloadFailed:
4245 OS << "overload resolution for reference initialization failed";
4246 break;
4247
4248 case FK_NonConstLValueReferenceBindingToTemporary:
4249 OS << "non-const lvalue reference bound to temporary";
4250 break;
4251
4252 case FK_NonConstLValueReferenceBindingToUnrelated:
4253 OS << "non-const lvalue reference bound to unrelated type";
4254 break;
4255
4256 case FK_RValueReferenceBindingToLValue:
4257 OS << "rvalue reference bound to an lvalue";
4258 break;
4259
4260 case FK_ReferenceInitDropsQualifiers:
4261 OS << "reference initialization drops qualifiers";
4262 break;
4263
4264 case FK_ReferenceInitFailed:
4265 OS << "reference initialization failed";
4266 break;
4267
4268 case FK_ConversionFailed:
4269 OS << "conversion failed";
4270 break;
4271
4272 case FK_TooManyInitsForScalar:
4273 OS << "too many initializers for scalar";
4274 break;
4275
4276 case FK_ReferenceBindingToInitList:
4277 OS << "referencing binding to initializer list";
4278 break;
4279
4280 case FK_InitListBadDestinationType:
4281 OS << "initializer list for non-aggregate, non-scalar type";
4282 break;
4283
4284 case FK_UserConversionOverloadFailed:
4285 OS << "overloading failed for user-defined conversion";
4286 break;
4287
4288 case FK_ConstructorOverloadFailed:
4289 OS << "constructor overloading failed";
4290 break;
4291
4292 case FK_DefaultInitOfConst:
4293 OS << "default initialization of a const variable";
4294 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004295
4296 case FK_Incomplete:
4297 OS << "initialization of incomplete type";
4298 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004299 }
4300 OS << '\n';
4301 return;
4302 }
4303
4304 case DependentSequence:
4305 OS << "Dependent sequence: ";
4306 return;
4307
4308 case UserDefinedConversion:
4309 OS << "User-defined conversion sequence: ";
4310 break;
4311
4312 case ConstructorInitialization:
4313 OS << "Constructor initialization sequence: ";
4314 break;
4315
4316 case ReferenceBinding:
4317 OS << "Reference binding: ";
4318 break;
4319
4320 case ListInitialization:
4321 OS << "List initialization: ";
4322 break;
4323
4324 case ZeroInitialization:
4325 OS << "Zero initialization\n";
4326 return;
4327
4328 case NoInitialization:
4329 OS << "No initialization\n";
4330 return;
4331
4332 case StandardConversion:
4333 OS << "Standard conversion: ";
4334 break;
4335
4336 case CAssignment:
4337 OS << "C assignment: ";
4338 break;
4339
4340 case StringInit:
4341 OS << "String initialization: ";
4342 break;
4343 }
4344
4345 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4346 if (S != step_begin()) {
4347 OS << " -> ";
4348 }
4349
4350 switch (S->Kind) {
4351 case SK_ResolveAddressOfOverloadedFunction:
4352 OS << "resolve address of overloaded function";
4353 break;
4354
4355 case SK_CastDerivedToBaseRValue:
4356 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4357 break;
4358
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004359 case SK_CastDerivedToBaseXValue:
4360 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4361 break;
4362
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004363 case SK_CastDerivedToBaseLValue:
4364 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4365 break;
4366
4367 case SK_BindReference:
4368 OS << "bind reference to lvalue";
4369 break;
4370
4371 case SK_BindReferenceToTemporary:
4372 OS << "bind reference to a temporary";
4373 break;
4374
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004375 case SK_ExtraneousCopyToTemporary:
4376 OS << "extraneous C++03 copy to temporary";
4377 break;
4378
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004379 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004380 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004381 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004382
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004383 case SK_QualificationConversionRValue:
4384 OS << "qualification conversion (rvalue)";
4385
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004386 case SK_QualificationConversionXValue:
4387 OS << "qualification conversion (xvalue)";
4388
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004389 case SK_QualificationConversionLValue:
4390 OS << "qualification conversion (lvalue)";
4391 break;
4392
4393 case SK_ConversionSequence:
4394 OS << "implicit conversion sequence (";
4395 S->ICS->DebugPrint(); // FIXME: use OS
4396 OS << ")";
4397 break;
4398
4399 case SK_ListInitialization:
4400 OS << "list initialization";
4401 break;
4402
4403 case SK_ConstructorInitialization:
4404 OS << "constructor initialization";
4405 break;
4406
4407 case SK_ZeroInitialization:
4408 OS << "zero initialization";
4409 break;
4410
4411 case SK_CAssignment:
4412 OS << "C assignment";
4413 break;
4414
4415 case SK_StringInit:
4416 OS << "string initialization";
4417 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004418
4419 case SK_ObjCObjectConversion:
4420 OS << "Objective-C object conversion";
4421 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004422 }
4423 }
4424}
4425
4426void InitializationSequence::dump() const {
4427 dump(llvm::errs());
4428}
4429
Douglas Gregore1314a62009-12-18 05:02:21 +00004430//===----------------------------------------------------------------------===//
4431// Initialization helper functions
4432//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004433ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004434Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4435 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004436 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004437 if (Init.isInvalid())
4438 return ExprError();
4439
4440 Expr *InitE = (Expr *)Init.get();
4441 assert(InitE && "No initialization expression?");
4442
4443 if (EqualLoc.isInvalid())
4444 EqualLoc = InitE->getLocStart();
4445
4446 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4447 EqualLoc);
4448 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4449 Init.release();
John McCall37ad5512010-08-23 06:44:23 +00004450 return Seq.Perform(*this, Entity, Kind, MultiExprArg(*this, &InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004451}