blob: fdac4762728cf57af0a222d9240f1739bc2427f2 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
John McCall8b0666c2010-08-20 18:27:03 +000018#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000021#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000022#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000023#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000025#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000028#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000029#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000030using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000031
Chris Lattner0cb78032009-02-24 22:27:37 +000032//===----------------------------------------------------------------------===//
33// Sema Initialization Checking
34//===----------------------------------------------------------------------===//
35
Chris Lattnerd8b741c82009-02-24 23:10:27 +000036static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000037 const ArrayType *AT = Context.getAsArrayType(DeclType);
38 if (!AT) return 0;
39
Eli Friedman893abe42009-05-29 18:22:49 +000040 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
41 return 0;
42
Chris Lattnera9196812009-02-26 23:26:43 +000043 // See if this is a string literal or @encode.
44 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000045
Chris Lattnera9196812009-02-26 23:26:43 +000046 // Handle @encode, which is a narrow string.
47 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
48 return Init;
49
50 // Otherwise we can only handle string literals.
51 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000052 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000053
54 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000055 // char array can be initialized with a narrow string.
56 // Only allow char x[] = "foo"; not char x[] = L"foo";
57 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000059
Eli Friedman42a84652009-05-31 10:54:53 +000060 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
61 // correction from DR343): "An array with element type compatible with a
62 // qualified or unqualified version of wchar_t may be initialized by a wide
63 // string literal, optionally enclosed in braces."
64 if (Context.typesAreCompatible(Context.getWCharType(),
65 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000066 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner0cb78032009-02-24 22:27:37 +000068 return 0;
69}
70
Chris Lattnerd8b741c82009-02-24 23:10:27 +000071static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
72 // Get the length of the string as parsed.
73 uint64_t StrLength =
74 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
75
Mike Stump11289f42009-09-09 15:08:12 +000076
Chris Lattnerd8b741c82009-02-24 23:10:27 +000077 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000078 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000079 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000080 // being initialized to a string literal.
81 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000082 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000084 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
85 ConstVal,
86 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000087 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000088 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Eli Friedman893abe42009-05-29 18:22:49 +000090 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000091
Eli Friedman893abe42009-05-29 18:22:49 +000092 // C99 6.7.8p14. We have an array of character type with known size. However,
93 // the size may be smaller or larger than the string we are initializing.
94 // FIXME: Avoid truncation for 64-bit length strings.
95 if (StrLength-1 > CAT->getSize().getZExtValue())
96 S.Diag(Str->getSourceRange().getBegin(),
97 diag::warn_initializer_string_for_char_array_too_long)
98 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000099
Eli Friedman893abe42009-05-29 18:22:49 +0000100 // Set the type to the actual size that we are initializing. If we have
101 // something like:
102 // char x[1] = "foo";
103 // then this will set the string literal's type to char[1].
104 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000105}
106
Chris Lattner0cb78032009-02-24 22:27:37 +0000107//===----------------------------------------------------------------------===//
108// Semantic checking for initializer lists.
109//===----------------------------------------------------------------------===//
110
Douglas Gregorcde232f2009-01-29 01:05:33 +0000111/// @brief Semantic checking for initializer lists.
112///
113/// The InitListChecker class contains a set of routines that each
114/// handle the initialization of a certain kind of entity, e.g.,
115/// arrays, vectors, struct/union types, scalars, etc. The
116/// InitListChecker itself performs a recursive walk of the subobject
117/// structure of the type to be initialized, while stepping through
118/// the initializer list one element at a time. The IList and Index
119/// parameters to each of the Check* routines contain the active
120/// (syntactic) initializer list and the index into that initializer
121/// list that represents the current initializer. Each routine is
122/// responsible for moving that Index forward as it consumes elements.
123///
124/// Each Check* routine also has a StructuredList/StructuredIndex
125/// arguments, which contains the current the "structured" (semantic)
126/// initializer list and the index into that initializer list where we
127/// are copying initializers as we map them over to the semantic
128/// list. Once we have completed our recursive walk of the subobject
129/// structure, we will have constructed a full semantic initializer
130/// list.
131///
132/// C99 designators cause changes in the initializer list traversal,
133/// because they make the initialization "jump" into a specific
134/// subobject and then continue the initialization from that
135/// point. CheckDesignatedInitializer() recursively steps into the
136/// designated subobject and manages backing out the recursion to
137/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000138namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000139class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000140 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000141 bool hadError;
142 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
143 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000144
Anders Carlsson6cabf312010-01-23 23:23:01 +0000145 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000146 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000147 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000148 unsigned &StructuredIndex,
149 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000150 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000151 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000152 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000153 unsigned &StructuredIndex,
154 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000155 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000156 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000157 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000158 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000159 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000160 unsigned &StructuredIndex,
161 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000162 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000163 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000164 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000165 InitListExpr *StructuredList,
166 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000167 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000168 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000170 InitListExpr *StructuredList,
171 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000172 void CheckReferenceType(const InitializedEntity &Entity,
173 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000174 unsigned &Index,
175 InitListExpr *StructuredList,
176 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000178 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 InitListExpr *StructuredList,
180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000182 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000183 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000184 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000185 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000188 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000190 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000191 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000194 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000195 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000196 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000197 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000198 RecordDecl::field_iterator *NextField,
199 llvm::APSInt *NextElementIndex,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000203 bool FinishSubobjectInit,
204 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
206 QualType CurrentObjectType,
207 InitListExpr *StructuredList,
208 unsigned StructuredIndex,
209 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000210 void UpdateStructuredListElement(InitListExpr *StructuredList,
211 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000212 Expr *expr);
213 int numArrayElements(QualType DeclType);
214 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000215
Douglas Gregor2bb07652009-12-22 00:05:34 +0000216 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
217 const InitializedEntity &ParentEntity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000219 void FillInValueInitializations(const InitializedEntity &Entity,
220 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000221public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000222 InitListChecker(Sema &S, const InitializedEntity &Entity,
223 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 bool HadError() { return hadError; }
225
226 // @brief Retrieves the fully-structured initializer list used for
227 // semantic analysis and code generation.
228 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
229};
Chris Lattner9ececce2009-02-24 22:48:58 +0000230} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000231
Douglas Gregor2bb07652009-12-22 00:05:34 +0000232void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
233 const InitializedEntity &ParentEntity,
234 InitListExpr *ILE,
235 bool &RequiresSecondPass) {
236 SourceLocation Loc = ILE->getSourceRange().getBegin();
237 unsigned NumInits = ILE->getNumInits();
238 InitializedEntity MemberEntity
239 = InitializedEntity::InitializeMember(Field, &ParentEntity);
240 if (Init >= NumInits || !ILE->getInit(Init)) {
241 // FIXME: We probably don't need to handle references
242 // specially here, since value-initialization of references is
243 // handled in InitializationSequence.
244 if (Field->getType()->isReferenceType()) {
245 // C++ [dcl.init.aggr]p9:
246 // If an incomplete or empty initializer-list leaves a
247 // member of reference type uninitialized, the program is
248 // ill-formed.
249 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
250 << Field->getType()
251 << ILE->getSyntacticForm()->getSourceRange();
252 SemaRef.Diag(Field->getLocation(),
253 diag::note_uninit_reference_member);
254 hadError = true;
255 return;
256 }
257
258 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
259 true);
260 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
261 if (!InitSeq) {
262 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
263 hadError = true;
264 return;
265 }
266
John McCalldadc5752010-08-24 06:29:42 +0000267 ExprResult MemberInit
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 McCall7a1da892010-08-26 16:36:35 +00002139 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002140 switch (VK) {
2141 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002142 S.Kind = SK_QualificationConversionRValue;
2143 break;
John McCall2536c6d2010-08-25 10:28:54 +00002144 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002145 S.Kind = SK_QualificationConversionXValue;
2146 break;
John McCall2536c6d2010-08-25 10:28:54 +00002147 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002148 S.Kind = SK_QualificationConversionLValue;
2149 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002150 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002151 S.Type = Ty;
2152 Steps.push_back(S);
2153}
2154
2155void InitializationSequence::AddConversionSequenceStep(
2156 const ImplicitConversionSequence &ICS,
2157 QualType T) {
2158 Step S;
2159 S.Kind = SK_ConversionSequence;
2160 S.Type = T;
2161 S.ICS = new ImplicitConversionSequence(ICS);
2162 Steps.push_back(S);
2163}
2164
Douglas Gregor51e77d52009-12-10 17:56:55 +00002165void InitializationSequence::AddListInitializationStep(QualType T) {
2166 Step S;
2167 S.Kind = SK_ListInitialization;
2168 S.Type = T;
2169 Steps.push_back(S);
2170}
2171
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002172void
2173InitializationSequence::AddConstructorInitializationStep(
2174 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002175 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002176 QualType T) {
2177 Step S;
2178 S.Kind = SK_ConstructorInitialization;
2179 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002180 S.Function.Function = Constructor;
2181 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002182 Steps.push_back(S);
2183}
2184
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002185void InitializationSequence::AddZeroInitializationStep(QualType T) {
2186 Step S;
2187 S.Kind = SK_ZeroInitialization;
2188 S.Type = T;
2189 Steps.push_back(S);
2190}
2191
Douglas Gregore1314a62009-12-18 05:02:21 +00002192void InitializationSequence::AddCAssignmentStep(QualType T) {
2193 Step S;
2194 S.Kind = SK_CAssignment;
2195 S.Type = T;
2196 Steps.push_back(S);
2197}
2198
Eli Friedman78275202009-12-19 08:11:05 +00002199void InitializationSequence::AddStringInitStep(QualType T) {
2200 Step S;
2201 S.Kind = SK_StringInit;
2202 S.Type = T;
2203 Steps.push_back(S);
2204}
2205
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002206void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2207 Step S;
2208 S.Kind = SK_ObjCObjectConversion;
2209 S.Type = T;
2210 Steps.push_back(S);
2211}
2212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002213void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2214 OverloadingResult Result) {
2215 SequenceKind = FailedSequence;
2216 this->Failure = Failure;
2217 this->FailedOverloadResult = Result;
2218}
2219
2220//===----------------------------------------------------------------------===//
2221// Attempt initialization
2222//===----------------------------------------------------------------------===//
2223
2224/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002225static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002226 const InitializedEntity &Entity,
2227 const InitializationKind &Kind,
2228 InitListExpr *InitList,
2229 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002230 // FIXME: We only perform rudimentary checking of list
2231 // initializations at this point, then assume that any list
2232 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002233 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002234 // do all of the necessary checking. C++0x initializer lists will
2235 // force us to perform more checking here.
2236 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2237
Douglas Gregor1b303932009-12-22 15:35:07 +00002238 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002239
2240 // C++ [dcl.init]p13:
2241 // If T is a scalar type, then a declaration of the form
2242 //
2243 // T x = { a };
2244 //
2245 // is equivalent to
2246 //
2247 // T x = a;
2248 if (DestType->isScalarType()) {
2249 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2250 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2251 return;
2252 }
2253
2254 // Assume scalar initialization from a single value works.
2255 } else if (DestType->isAggregateType()) {
2256 // Assume aggregate initialization works.
2257 } else if (DestType->isVectorType()) {
2258 // Assume vector initialization works.
2259 } else if (DestType->isReferenceType()) {
2260 // FIXME: C++0x defines behavior for this.
2261 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2262 return;
2263 } else if (DestType->isRecordType()) {
2264 // FIXME: C++0x defines behavior for this
2265 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2266 }
2267
2268 // Add a general "list initialization" step.
2269 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002270}
2271
2272/// \brief Try a reference initialization that involves calling a conversion
2273/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002274static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2275 const InitializedEntity &Entity,
2276 const InitializationKind &Kind,
2277 Expr *Initializer,
2278 bool AllowRValues,
2279 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002280 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002281 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2282 QualType T1 = cv1T1.getUnqualifiedType();
2283 QualType cv2T2 = Initializer->getType();
2284 QualType T2 = cv2T2.getUnqualifiedType();
2285
2286 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002287 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002288 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002289 T1, T2, DerivedToBase,
2290 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002291 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002292 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002293 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002294
2295 // Build the candidate set directly in the initialization sequence
2296 // structure, so that it will persist if we fail.
2297 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2298 CandidateSet.clear();
2299
2300 // Determine whether we are allowed to call explicit constructors or
2301 // explicit conversion operators.
2302 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2303
2304 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002305 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2306 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002307 // The type we're converting to is a class type. Enumerate its constructors
2308 // to see if there is a suitable conversion.
2309 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002310
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002311 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002312 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002313 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002314 NamedDecl *D = *Con;
2315 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 // Find the constructor (which may be a template).
2318 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002319 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002320 if (ConstructorTmpl)
2321 Constructor = cast<CXXConstructorDecl>(
2322 ConstructorTmpl->getTemplatedDecl());
2323 else
John McCalla0296f72010-03-19 07:35:19 +00002324 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002325
2326 if (!Constructor->isInvalidDecl() &&
2327 Constructor->isConvertingConstructor(AllowExplicit)) {
2328 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002329 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002330 /*ExplicitArgs*/ 0,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002331 &Initializer, 1, CandidateSet);
2332 else
John McCalla0296f72010-03-19 07:35:19 +00002333 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002334 &Initializer, 1, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002335 }
2336 }
2337 }
John McCall3696dcb2010-08-17 07:23:57 +00002338 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2339 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002340
Douglas Gregor496e8b342010-05-07 19:42:26 +00002341 const RecordType *T2RecordType = 0;
2342 if ((T2RecordType = T2->getAs<RecordType>()) &&
2343 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002344 // The type we're converting from is a class type, enumerate its conversion
2345 // functions.
2346 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2347
2348 // Determine the type we are converting to. If we are allowed to
2349 // convert to an rvalue, take the type that the destination type
2350 // refers to.
2351 QualType ToType = AllowRValues? cv1T1 : DestType;
2352
John McCallad371252010-01-20 00:46:10 +00002353 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002354 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002355 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2356 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002357 NamedDecl *D = *I;
2358 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2359 if (isa<UsingShadowDecl>(D))
2360 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2361
2362 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2363 CXXConversionDecl *Conv;
2364 if (ConvTemplate)
2365 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2366 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002367 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002368
2369 // If the conversion function doesn't return a reference type,
2370 // it can't be considered for this conversion unless we're allowed to
2371 // consider rvalues.
2372 // FIXME: Do we need to make sure that we only consider conversion
2373 // candidates with reference-compatible results? That might be needed to
2374 // break recursion.
2375 if ((AllowExplicit || !Conv->isExplicit()) &&
2376 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2377 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002378 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002379 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380 ToType, CandidateSet);
2381 else
John McCalla0296f72010-03-19 07:35:19 +00002382 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002383 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002384 }
2385 }
2386 }
John McCall3696dcb2010-08-17 07:23:57 +00002387 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2388 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002389
2390 SourceLocation DeclLoc = Initializer->getLocStart();
2391
2392 // Perform overload resolution. If it fails, return the failed result.
2393 OverloadCandidateSet::iterator Best;
2394 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002395 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002396 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002399
2400 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002401 if (isa<CXXConversionDecl>(Function))
2402 T2 = Function->getResultType();
2403 else
2404 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002405
2406 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002407 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002408 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002409
2410 // Determine whether we need to perform derived-to-base or
2411 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002412 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002413 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002414 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002415 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002416 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002419 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002421 = S.CompareReferenceRelationship(DeclLoc, T1,
2422 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002423 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002424 if (NewRefRelationship == Sema::Ref_Incompatible) {
2425 // If the type we've converted to is not reference-related to the
2426 // type we're looking for, then there is another conversion step
2427 // we need to perform to produce a temporary of the right type
2428 // that we'll be binding to.
2429 ImplicitConversionSequence ICS;
2430 ICS.setStandard();
2431 ICS.Standard = Best->FinalConversion;
2432 T2 = ICS.Standard.getToType(2);
2433 Sequence.AddConversionSequenceStep(ICS, T2);
2434 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002435 Sequence.AddDerivedToBaseCastStep(
2436 S.Context.getQualifiedType(T1,
2437 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002438 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002439 else if (NewObjCConversion)
2440 Sequence.AddObjCObjectConversionStep(
2441 S.Context.getQualifiedType(T1,
2442 T2.getNonReferenceType().getQualifiers()));
2443
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002444 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002445 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002446
2447 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2448 return OR_Success;
2449}
2450
Sebastian Redld92badf2010-06-30 18:13:39 +00002451/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002452static void TryReferenceInitialization(Sema &S,
2453 const InitializedEntity &Entity,
2454 const InitializationKind &Kind,
2455 Expr *Initializer,
2456 InitializationSequence &Sequence) {
2457 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002458
Douglas Gregor1b303932009-12-22 15:35:07 +00002459 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002461 Qualifiers T1Quals;
2462 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002463 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002464 Qualifiers T2Quals;
2465 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002466 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002467
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002468 // If the initializer is the address of an overloaded function, try
2469 // to resolve the overloaded function. If all goes well, T2 is the
2470 // type of the resulting function.
2471 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002472 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002473 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2474 T1,
John McCall16df1e52010-03-30 21:47:33 +00002475 false,
2476 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 if (!Fn) {
2478 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2479 return;
2480 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002481
John McCall16df1e52010-03-30 21:47:33 +00002482 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002483 cv2T2 = Fn->getType();
2484 T2 = cv2T2.getUnqualifiedType();
2485 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 // Compute some basic properties of the types and the initializer.
2488 bool isLValueRef = DestType->isLValueReferenceType();
2489 bool isRValueRef = !isLValueRef;
2490 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002491 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002492 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002493 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002494 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2495 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002496
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002497 // C++0x [dcl.init.ref]p5:
2498 // A reference to type "cv1 T1" is initialized by an expression of type
2499 // "cv2 T2" as follows:
2500 //
2501 // - If the reference is an lvalue reference and the initializer
2502 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002503 // Note the analogous bullet points for rvlaue refs to functions. Because
2504 // there are no function rvalues in C++, rvalue refs to functions are treated
2505 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002506 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002507 bool T1Function = T1->isFunctionType();
2508 if (isLValueRef || T1Function) {
2509 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2511 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2512 // reference-compatible with "cv2 T2," or
2513 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002514 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002515 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002516 // can occur. However, we do pay attention to whether it is a bit-field
2517 // to decide whether we're actually binding to a temporary created from
2518 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002519 if (DerivedToBase)
2520 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002521 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002522 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002523 else if (ObjCConversion)
2524 Sequence.AddObjCObjectConversionStep(
2525 S.Context.getQualifiedType(T1, T2Quals));
2526
Chandler Carruth04bdce62010-01-12 20:32:25 +00002527 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002528 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002529 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002530 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002531 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 return;
2533 }
2534
2535 // - has a class type (i.e., T2 is a class type), where T1 is not
2536 // reference-related to T2, and can be implicitly converted to an
2537 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2538 // with "cv3 T3" (this conversion is selected by enumerating the
2539 // applicable conversion functions (13.3.1.6) and choosing the best
2540 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002541 // If we have an rvalue ref to function type here, the rhs must be
2542 // an rvalue.
2543 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2544 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002545 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2546 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002547 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002548 Sequence);
2549 if (ConvOvlResult == OR_Success)
2550 return;
John McCall0d1da222010-01-12 00:44:57 +00002551 if (ConvOvlResult != OR_No_Viable_Function) {
2552 Sequence.SetOverloadFailure(
2553 InitializationSequence::FK_ReferenceInitOverloadFailed,
2554 ConvOvlResult);
2555 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002556 }
2557 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002558
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002559 // - Otherwise, the reference shall be an lvalue reference to a
2560 // non-volatile const type (i.e., cv1 shall be const), or the reference
2561 // shall be an rvalue reference and the initializer expression shall
Sebastian Redld92badf2010-06-30 18:13:39 +00002562 // be an rvalue or have a function type.
2563 // We handled the function type stuff above.
Douglas Gregord1e08642010-01-29 19:39:15 +00002564 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002565 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002566 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2567 Sequence.SetOverloadFailure(
2568 InitializationSequence::FK_ReferenceInitOverloadFailed,
2569 ConvOvlResult);
2570 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002571 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002572 ? (RefRelationship == Sema::Ref_Related
2573 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2574 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2575 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2576 else
2577 Sequence.SetFailed(
2578 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002579
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002580 return;
2581 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002582
2583 // - [If T1 is not a function type], if T2 is a class type and
2584 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002585 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002586 // - the initializer expression is an rvalue and "cv1 T1" is
2587 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002588 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002589 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002590 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2591 // compiler the freedom to perform a copy here or bind to the
2592 // object, while C++0x requires that we bind directly to the
2593 // object. Hence, we always bind to the object without making an
2594 // extra copy. However, in C++03 requires that we check for the
2595 // presence of a suitable copy constructor:
2596 //
2597 // The constructor that would be used to make the copy shall
2598 // be callable whether or not the copy is actually done.
2599 if (!S.getLangOptions().CPlusPlus0x)
2600 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2601
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002602 if (DerivedToBase)
2603 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002604 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002605 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002606 else if (ObjCConversion)
2607 Sequence.AddObjCObjectConversionStep(
2608 S.Context.getQualifiedType(T1, T2Quals));
2609
Chandler Carruth04bdce62010-01-12 20:32:25 +00002610 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002611 Sequence.AddQualificationConversionStep(cv1T1,
John McCall2536c6d2010-08-25 10:28:54 +00002612 isXValue ? VK_XValue : VK_RValue);
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002613 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002614 return;
2615 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002616
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002617 // - T1 is not reference-related to T2 and the initializer expression
2618 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2619 // conversion is selected by enumerating the applicable conversion
2620 // functions (13.3.1.6) and choosing the best one through overload
2621 // resolution (13.3)),
2622 if (RefRelationship == Sema::Ref_Incompatible) {
2623 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2624 Kind, Initializer,
2625 /*AllowRValues=*/true,
2626 Sequence);
2627 if (ConvOvlResult)
2628 Sequence.SetOverloadFailure(
2629 InitializationSequence::FK_ReferenceInitOverloadFailed,
2630 ConvOvlResult);
2631
2632 return;
2633 }
2634
2635 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2636 return;
2637 }
2638
2639 // - If the initializer expression is an rvalue, with T2 an array type,
2640 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2641 // is bound to the object represented by the rvalue (see 3.10).
2642 // FIXME: How can an array type be reference-compatible with anything?
2643 // Don't we mean the element types of T1 and T2?
2644
2645 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2646 // from the initializer expression using the rules for a non-reference
2647 // copy initialization (8.5). The reference is then bound to the
2648 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002649
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002650 // Determine whether we are allowed to call explicit constructors or
2651 // explicit conversion operators.
2652 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002653
2654 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2655
2656 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2657 /*SuppressUserConversions*/ false,
2658 AllowExplicit,
2659 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002660 // FIXME: Use the conversion function set stored in ICS to turn
2661 // this into an overloading ambiguity diagnostic. However, we need
2662 // to keep that set as an OverloadCandidateSet rather than as some
2663 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002664 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2665 Sequence.SetOverloadFailure(
2666 InitializationSequence::FK_ReferenceInitOverloadFailed,
2667 ConvOvlResult);
2668 else
2669 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 return;
2671 }
2672
2673 // [...] If T1 is reference-related to T2, cv1 must be the
2674 // same cv-qualification as, or greater cv-qualification
2675 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002676 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2677 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002678 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002679 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002680 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2681 return;
2682 }
2683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002684 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2685 return;
2686}
2687
2688/// \brief Attempt character array initialization from a string literal
2689/// (C++ [dcl.init.string], C99 6.7.8).
2690static void TryStringLiteralInitialization(Sema &S,
2691 const InitializedEntity &Entity,
2692 const InitializationKind &Kind,
2693 Expr *Initializer,
2694 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002695 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002696 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002697}
2698
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002699/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2700/// enumerates the constructors of the initialized entity and performs overload
2701/// resolution to select the best.
2702static void TryConstructorInitialization(Sema &S,
2703 const InitializedEntity &Entity,
2704 const InitializationKind &Kind,
2705 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002706 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002707 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002708 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002709
2710 // Build the candidate set directly in the initialization sequence
2711 // structure, so that it will persist if we fail.
2712 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2713 CandidateSet.clear();
2714
2715 // Determine whether we are allowed to call explicit constructors or
2716 // explicit conversion operators.
2717 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2718 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002719 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002720
2721 // The type we're constructing needs to be complete.
2722 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002723 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002724 return;
2725 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002726
2727 // The type we're converting to is a class type. Enumerate its constructors
2728 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002729 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2730 assert(DestRecordType && "Constructor initialization requires record type");
2731 CXXRecordDecl *DestRecordDecl
2732 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2733
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002734 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002735 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002736 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002737 NamedDecl *D = *Con;
2738 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002739 bool SuppressUserConversions = false;
2740
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002741 // Find the constructor (which may be a template).
2742 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002743 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002744 if (ConstructorTmpl)
2745 Constructor = cast<CXXConstructorDecl>(
2746 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002747 else {
John McCalla0296f72010-03-19 07:35:19 +00002748 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002749
2750 // If we're performing copy initialization using a copy constructor, we
2751 // suppress user-defined conversions on the arguments.
2752 // FIXME: Move constructors?
2753 if (Kind.getKind() == InitializationKind::IK_Copy &&
2754 Constructor->isCopyConstructor())
2755 SuppressUserConversions = true;
2756 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002757
2758 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002759 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002760 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002761 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002762 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002763 Args, NumArgs, CandidateSet,
2764 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002765 else
John McCalla0296f72010-03-19 07:35:19 +00002766 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002767 Args, NumArgs, CandidateSet,
2768 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002769 }
2770 }
2771
2772 SourceLocation DeclLoc = Kind.getLocation();
2773
2774 // Perform overload resolution. If it fails, return the failed result.
2775 OverloadCandidateSet::iterator Best;
2776 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002777 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002778 Sequence.SetOverloadFailure(
2779 InitializationSequence::FK_ConstructorOverloadFailed,
2780 Result);
2781 return;
2782 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002783
2784 // C++0x [dcl.init]p6:
2785 // If a program calls for the default initialization of an object
2786 // of a const-qualified type T, T shall be a class type with a
2787 // user-provided default constructor.
2788 if (Kind.getKind() == InitializationKind::IK_Default &&
2789 Entity.getType().isConstQualified() &&
2790 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2791 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2792 return;
2793 }
2794
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002795 // Add the constructor initialization step. Any cv-qualification conversion is
2796 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002797 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002798 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002799 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002800 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002801}
2802
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002803/// \brief Attempt value initialization (C++ [dcl.init]p7).
2804static void TryValueInitialization(Sema &S,
2805 const InitializedEntity &Entity,
2806 const InitializationKind &Kind,
2807 InitializationSequence &Sequence) {
2808 // C++ [dcl.init]p5:
2809 //
2810 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002811 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002812
2813 // -- if T is an array type, then each element is value-initialized;
2814 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2815 T = AT->getElementType();
2816
2817 if (const RecordType *RT = T->getAs<RecordType>()) {
2818 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2819 // -- if T is a class type (clause 9) with a user-declared
2820 // constructor (12.1), then the default constructor for T is
2821 // called (and the initialization is ill-formed if T has no
2822 // accessible default constructor);
2823 //
2824 // FIXME: we really want to refer to a single subobject of the array,
2825 // but Entity doesn't have a way to capture that (yet).
2826 if (ClassDecl->hasUserDeclaredConstructor())
2827 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2828
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002829 // -- if T is a (possibly cv-qualified) non-union class type
2830 // without a user-provided constructor, then the object is
2831 // zero-initialized and, if T’s implicitly-declared default
2832 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002833 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002834 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002835 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002836 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2837 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002838 }
2839 }
2840
Douglas Gregor1b303932009-12-22 15:35:07 +00002841 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002842 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2843}
2844
Douglas Gregor85dabae2009-12-16 01:38:02 +00002845/// \brief Attempt default initialization (C++ [dcl.init]p6).
2846static void TryDefaultInitialization(Sema &S,
2847 const InitializedEntity &Entity,
2848 const InitializationKind &Kind,
2849 InitializationSequence &Sequence) {
2850 assert(Kind.getKind() == InitializationKind::IK_Default);
2851
2852 // C++ [dcl.init]p6:
2853 // To default-initialize an object of type T means:
2854 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002855 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002856 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2857 DestType = Array->getElementType();
2858
2859 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2860 // constructor for T is called (and the initialization is ill-formed if
2861 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002862 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002863 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2864 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002865 }
2866
2867 // - otherwise, no initialization is performed.
2868 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2869
2870 // If a program calls for the default initialization of an object of
2871 // a const-qualified type T, T shall be a class type with a user-provided
2872 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002873 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002874 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2875}
2876
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002877/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2878/// which enumerates all conversion functions and performs overload resolution
2879/// to select the best.
2880static void TryUserDefinedConversion(Sema &S,
2881 const InitializedEntity &Entity,
2882 const InitializationKind &Kind,
2883 Expr *Initializer,
2884 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002885 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2886
Douglas Gregor1b303932009-12-22 15:35:07 +00002887 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002888 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2889 QualType SourceType = Initializer->getType();
2890 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2891 "Must have a class type to perform a user-defined conversion");
2892
2893 // Build the candidate set directly in the initialization sequence
2894 // structure, so that it will persist if we fail.
2895 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2896 CandidateSet.clear();
2897
2898 // Determine whether we are allowed to call explicit constructors or
2899 // explicit conversion operators.
2900 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2901
2902 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2903 // The type we're converting to is a class type. Enumerate its constructors
2904 // to see if there is a suitable conversion.
2905 CXXRecordDecl *DestRecordDecl
2906 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2907
Douglas Gregord9848152010-04-26 14:36:57 +00002908 // Try to complete the type we're converting to.
2909 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002910 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002911 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002912 Con != ConEnd; ++Con) {
2913 NamedDecl *D = *Con;
2914 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002915
Douglas Gregord9848152010-04-26 14:36:57 +00002916 // Find the constructor (which may be a template).
2917 CXXConstructorDecl *Constructor = 0;
2918 FunctionTemplateDecl *ConstructorTmpl
2919 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002920 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002921 Constructor = cast<CXXConstructorDecl>(
2922 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002923 else
Douglas Gregord9848152010-04-26 14:36:57 +00002924 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002925
2926 if (!Constructor->isInvalidDecl() &&
2927 Constructor->isConvertingConstructor(AllowExplicit)) {
2928 if (ConstructorTmpl)
2929 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2930 /*ExplicitArgs*/ 0,
2931 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002932 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002933 else
2934 S.AddOverloadCandidate(Constructor, FoundDecl,
2935 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002936 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002937 }
2938 }
2939 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002940 }
Eli Friedman78275202009-12-19 08:11:05 +00002941
2942 SourceLocation DeclLoc = Initializer->getLocStart();
2943
Douglas Gregor540c3b02009-12-14 17:27:33 +00002944 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2945 // The type we're converting from is a class type, enumerate its conversion
2946 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002947
Eli Friedman4afe9a32009-12-20 22:12:03 +00002948 // We can only enumerate the conversion functions for a complete type; if
2949 // the type isn't complete, simply skip this step.
2950 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2951 CXXRecordDecl *SourceRecordDecl
2952 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002953
John McCallad371252010-01-20 00:46:10 +00002954 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002955 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002956 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002957 E = Conversions->end();
2958 I != E; ++I) {
2959 NamedDecl *D = *I;
2960 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2961 if (isa<UsingShadowDecl>(D))
2962 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2963
2964 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2965 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002966 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002967 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002968 else
John McCallda4458e2010-03-31 01:36:47 +00002969 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002970
2971 if (AllowExplicit || !Conv->isExplicit()) {
2972 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002973 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002974 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002975 CandidateSet);
2976 else
John McCalla0296f72010-03-19 07:35:19 +00002977 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002978 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002979 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002980 }
2981 }
2982 }
2983
Douglas Gregor540c3b02009-12-14 17:27:33 +00002984 // Perform overload resolution. If it fails, return the failed result.
2985 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002986 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002987 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002988 Sequence.SetOverloadFailure(
2989 InitializationSequence::FK_UserConversionOverloadFailed,
2990 Result);
2991 return;
2992 }
John McCall0d1da222010-01-12 00:44:57 +00002993
Douglas Gregor540c3b02009-12-14 17:27:33 +00002994 FunctionDecl *Function = Best->Function;
2995
2996 if (isa<CXXConstructorDecl>(Function)) {
2997 // Add the user-defined conversion step. Any cv-qualification conversion is
2998 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00002999 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003000 return;
3001 }
3002
3003 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003004 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003005 if (ConvType->getAs<RecordType>()) {
3006 // If we're converting to a class type, there may be an copy if
3007 // the resulting temporary object (possible to create an object of
3008 // a base class type). That copy is not a separate conversion, so
3009 // we just make a note of the actual destination type (possibly a
3010 // base class of the type returned by the conversion function) and
3011 // let the user-defined conversion step handle the conversion.
3012 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3013 return;
3014 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003015
Douglas Gregor5ab11652010-04-17 22:01:05 +00003016 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3017
3018 // If the conversion following the call to the conversion function
3019 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003020 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3021 Best->FinalConversion.Third) {
3022 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003023 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003024 ICS.Standard = Best->FinalConversion;
3025 Sequence.AddConversionSequenceStep(ICS, DestType);
3026 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003027}
3028
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003029InitializationSequence::InitializationSequence(Sema &S,
3030 const InitializedEntity &Entity,
3031 const InitializationKind &Kind,
3032 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003033 unsigned NumArgs)
3034 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003035 ASTContext &Context = S.Context;
3036
3037 // C++0x [dcl.init]p16:
3038 // The semantics of initializers are as follows. The destination type is
3039 // the type of the object or reference being initialized and the source
3040 // type is the type of the initializer expression. The source type is not
3041 // defined when the initializer is a braced-init-list or when it is a
3042 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003043 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003044
3045 if (DestType->isDependentType() ||
3046 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3047 SequenceKind = DependentSequence;
3048 return;
3049 }
3050
3051 QualType SourceType;
3052 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003053 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003054 Initializer = Args[0];
3055 if (!isa<InitListExpr>(Initializer))
3056 SourceType = Initializer->getType();
3057 }
3058
3059 // - If the initializer is a braced-init-list, the object is
3060 // list-initialized (8.5.4).
3061 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3062 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003063 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003064 }
3065
3066 // - If the destination type is a reference type, see 8.5.3.
3067 if (DestType->isReferenceType()) {
3068 // C++0x [dcl.init.ref]p1:
3069 // A variable declared to be a T& or T&&, that is, "reference to type T"
3070 // (8.3.2), shall be initialized by an object, or function, of type T or
3071 // by an object that can be converted into a T.
3072 // (Therefore, multiple arguments are not permitted.)
3073 if (NumArgs != 1)
3074 SetFailed(FK_TooManyInitsForReference);
3075 else
3076 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3077 return;
3078 }
3079
3080 // - If the destination type is an array of characters, an array of
3081 // char16_t, an array of char32_t, or an array of wchar_t, and the
3082 // initializer is a string literal, see 8.5.2.
3083 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3084 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3085 return;
3086 }
3087
3088 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003089 if (Kind.getKind() == InitializationKind::IK_Value ||
3090 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003091 TryValueInitialization(S, Entity, Kind, *this);
3092 return;
3093 }
3094
Douglas Gregor85dabae2009-12-16 01:38:02 +00003095 // Handle default initialization.
3096 if (Kind.getKind() == InitializationKind::IK_Default){
3097 TryDefaultInitialization(S, Entity, Kind, *this);
3098 return;
3099 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003100
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003101 // - Otherwise, if the destination type is an array, the program is
3102 // ill-formed.
3103 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3104 if (AT->getElementType()->isAnyCharacterType())
3105 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3106 else
3107 SetFailed(FK_ArrayNeedsInitList);
3108
3109 return;
3110 }
Eli Friedman78275202009-12-19 08:11:05 +00003111
3112 // Handle initialization in C
3113 if (!S.getLangOptions().CPlusPlus) {
3114 setSequenceKind(CAssignment);
3115 AddCAssignmentStep(DestType);
3116 return;
3117 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003118
3119 // - If the destination type is a (possibly cv-qualified) class type:
3120 if (DestType->isRecordType()) {
3121 // - If the initialization is direct-initialization, or if it is
3122 // copy-initialization where the cv-unqualified version of the
3123 // source type is the same class as, or a derived class of, the
3124 // class of the destination, constructors are considered. [...]
3125 if (Kind.getKind() == InitializationKind::IK_Direct ||
3126 (Kind.getKind() == InitializationKind::IK_Copy &&
3127 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3128 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003129 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003130 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003131 // - Otherwise (i.e., for the remaining copy-initialization cases),
3132 // user-defined conversion sequences that can convert from the source
3133 // type to the destination type or (when a conversion function is
3134 // used) to a derived class thereof are enumerated as described in
3135 // 13.3.1.4, and the best one is chosen through overload resolution
3136 // (13.3).
3137 else
3138 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3139 return;
3140 }
3141
Douglas Gregor85dabae2009-12-16 01:38:02 +00003142 if (NumArgs > 1) {
3143 SetFailed(FK_TooManyInitsForScalar);
3144 return;
3145 }
3146 assert(NumArgs == 1 && "Zero-argument case handled above");
3147
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003148 // - Otherwise, if the source type is a (possibly cv-qualified) class
3149 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003150 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003151 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3152 return;
3153 }
3154
3155 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003156 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003157 // conversions (Clause 4) will be used, if necessary, to convert the
3158 // initializer expression to the cv-unqualified version of the
3159 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003160 if (S.TryImplicitConversion(*this, Entity, Initializer,
3161 /*SuppressUserConversions*/ true,
3162 /*AllowExplicitConversions*/ false,
3163 /*InOverloadResolution*/ false))
3164 SetFailed(InitializationSequence::FK_ConversionFailed);
3165 else
3166 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167}
3168
3169InitializationSequence::~InitializationSequence() {
3170 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3171 StepEnd = Steps.end();
3172 Step != StepEnd; ++Step)
3173 Step->Destroy();
3174}
3175
3176//===----------------------------------------------------------------------===//
3177// Perform initialization
3178//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003179static Sema::AssignmentAction
3180getAssignmentAction(const InitializedEntity &Entity) {
3181 switch(Entity.getKind()) {
3182 case InitializedEntity::EK_Variable:
3183 case InitializedEntity::EK_New:
3184 return Sema::AA_Initializing;
3185
3186 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003187 if (Entity.getDecl() &&
3188 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3189 return Sema::AA_Sending;
3190
Douglas Gregore1314a62009-12-18 05:02:21 +00003191 return Sema::AA_Passing;
3192
3193 case InitializedEntity::EK_Result:
3194 return Sema::AA_Returning;
3195
3196 case InitializedEntity::EK_Exception:
3197 case InitializedEntity::EK_Base:
3198 llvm_unreachable("No assignment action for C++-specific initialization");
3199 break;
3200
3201 case InitializedEntity::EK_Temporary:
3202 // FIXME: Can we tell apart casting vs. converting?
3203 return Sema::AA_Casting;
3204
3205 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003206 case InitializedEntity::EK_ArrayElement:
3207 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003208 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003209 return Sema::AA_Initializing;
3210 }
3211
3212 return Sema::AA_Converting;
3213}
3214
Douglas Gregor95562572010-04-24 23:45:46 +00003215/// \brief Whether we should binding a created object as a temporary when
3216/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003217static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003218 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003219 case InitializedEntity::EK_ArrayElement:
3220 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003221 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003222 case InitializedEntity::EK_New:
3223 case InitializedEntity::EK_Variable:
3224 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003225 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003226 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003227 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003228 return false;
3229
3230 case InitializedEntity::EK_Parameter:
3231 case InitializedEntity::EK_Temporary:
3232 return true;
3233 }
3234
3235 llvm_unreachable("missed an InitializedEntity kind?");
3236}
3237
Douglas Gregor95562572010-04-24 23:45:46 +00003238/// \brief Whether the given entity, when initialized with an object
3239/// created for that initialization, requires destruction.
3240static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3241 switch (Entity.getKind()) {
3242 case InitializedEntity::EK_Member:
3243 case InitializedEntity::EK_Result:
3244 case InitializedEntity::EK_New:
3245 case InitializedEntity::EK_Base:
3246 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003247 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003248 return false;
3249
3250 case InitializedEntity::EK_Variable:
3251 case InitializedEntity::EK_Parameter:
3252 case InitializedEntity::EK_Temporary:
3253 case InitializedEntity::EK_ArrayElement:
3254 case InitializedEntity::EK_Exception:
3255 return true;
3256 }
3257
3258 llvm_unreachable("missed an InitializedEntity kind?");
3259}
3260
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003261/// \brief Make a (potentially elidable) temporary copy of the object
3262/// provided by the given initializer by calling the appropriate copy
3263/// constructor.
3264///
3265/// \param S The Sema object used for type-checking.
3266///
3267/// \param T The type of the temporary object, which must either by
3268/// the type of the initializer expression or a superclass thereof.
3269///
3270/// \param Enter The entity being initialized.
3271///
3272/// \param CurInit The initializer expression.
3273///
3274/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3275/// is permitted in C++03 (but not C++0x) when binding a reference to
3276/// an rvalue.
3277///
3278/// \returns An expression that copies the initializer expression into
3279/// a temporary object, or an error expression if a copy could not be
3280/// created.
John McCalldadc5752010-08-24 06:29:42 +00003281static ExprResult CopyObject(Sema &S,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003282 QualType T,
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003283 const InitializedEntity &Entity,
John McCalldadc5752010-08-24 06:29:42 +00003284 ExprResult CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003285 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003286 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003287 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003288 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003289 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003290 Class = cast<CXXRecordDecl>(Record->getDecl());
3291 if (!Class)
3292 return move(CurInit);
3293
3294 // C++0x [class.copy]p34:
3295 // When certain criteria are met, an implementation is allowed to
3296 // omit the copy/move construction of a class object, even if the
3297 // copy/move constructor and/or destructor for the object have
3298 // side effects. [...]
3299 // - when a temporary class object that has not been bound to a
3300 // reference (12.2) would be copied/moved to a class object
3301 // with the same cv-unqualified type, the copy/move operation
3302 // can be omitted by constructing the temporary object
3303 // directly into the target of the omitted copy/move
3304 //
3305 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003306 // elision for return statements and throw expressions are handled as part
3307 // of constructor initialization, while copy elision for exception handlers
3308 // is handled by the run-time.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003309 bool Elidable = CurInitExpr->isTemporaryObject() &&
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003310 S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
Douglas Gregore1314a62009-12-18 05:02:21 +00003311 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003312 switch (Entity.getKind()) {
3313 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003314 Loc = Entity.getReturnLoc();
3315 break;
3316
3317 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003318 Loc = Entity.getThrowLoc();
3319 break;
3320
3321 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003322 Loc = Entity.getDecl()->getLocation();
3323 break;
3324
Anders Carlsson0bd52402010-01-24 00:19:41 +00003325 case InitializedEntity::EK_ArrayElement:
3326 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003327 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003328 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003329 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003330 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003331 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003332 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003333 Loc = CurInitExpr->getLocStart();
3334 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003335 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003336
3337 // Make sure that the type we are copying is complete.
3338 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3339 return move(CurInit);
3340
Douglas Gregore1314a62009-12-18 05:02:21 +00003341 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003342 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003343 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003344 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003345 Con != ConEnd; ++Con) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003346 // Only consider copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003347 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3348 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor7566e4a2010-04-18 02:16:12 +00003349 !Constructor->isCopyConstructor() ||
3350 !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
Douglas Gregore1314a62009-12-18 05:02:21 +00003351 continue;
John McCalla0296f72010-03-19 07:35:19 +00003352
3353 DeclAccessPair FoundDecl
3354 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3355 S.AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003356 &CurInitExpr, 1, CandidateSet);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003357 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003358
3359 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003360 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003361 case OR_Success:
3362 break;
3363
3364 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003365 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3366 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3367 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003368 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003369 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003370 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003371 if (!IsExtraneousCopy || S.isSFINAEContext())
3372 return S.ExprError();
3373 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003374
3375 case OR_Ambiguous:
3376 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003377 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003378 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003379 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003380 return S.ExprError();
3381
3382 case OR_Deleted:
3383 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003384 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003385 << CurInitExpr->getSourceRange();
3386 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3387 << Best->Function->isDeleted();
3388 return S.ExprError();
3389 }
3390
Douglas Gregor5ab11652010-04-17 22:01:05 +00003391 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003392 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003393 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003394
Anders Carlssona01874b2010-04-21 18:47:17 +00003395 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003396 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003397
3398 if (IsExtraneousCopy) {
3399 // If this is a totally extraneous copy for C++03 reference
3400 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003401 // expression. We don't generate an (elided) copy operation here
3402 // because doing so would require us to pass down a flag to avoid
3403 // infinite recursion, where each step adds another extraneous,
3404 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003405
Douglas Gregor30b52772010-04-18 07:57:34 +00003406 // Instantiate the default arguments of any extra parameters in
3407 // the selected copy constructor, as if we were going to create a
3408 // proper call to the copy constructor.
3409 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3410 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3411 if (S.RequireCompleteType(Loc, Parm->getType(),
3412 S.PDiag(diag::err_call_incomplete_argument)))
3413 break;
3414
3415 // Build the default argument expression; we don't actually care
3416 // if this succeeds or not, because this routine will complain
3417 // if there was a problem.
3418 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3419 }
3420
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003421 return S.Owned(CurInitExpr);
3422 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003423
3424 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003425 // constructor call (we might have derived-to-base conversions, or
3426 // the copy constructor may have default arguments).
Douglas Gregor5ab11652010-04-17 22:01:05 +00003427 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003428 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003429 Loc, ConstructorArgs))
3430 return S.ExprError();
3431
Douglas Gregord0ace022010-04-25 00:55:24 +00003432 // Actually perform the constructor call.
3433 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003434 move_arg(ConstructorArgs),
3435 /*ZeroInit*/ false,
3436 CXXConstructExpr::CK_Complete);
Douglas Gregord0ace022010-04-25 00:55:24 +00003437
3438 // If we're supposed to bind temporaries, do so.
3439 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3440 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3441 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003442}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003443
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003444void InitializationSequence::PrintInitLocationNote(Sema &S,
3445 const InitializedEntity &Entity) {
3446 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3447 if (Entity.getDecl()->getLocation().isInvalid())
3448 return;
3449
3450 if (Entity.getDecl()->getDeclName())
3451 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3452 << Entity.getDecl()->getDeclName();
3453 else
3454 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3455 }
3456}
3457
John McCalldadc5752010-08-24 06:29:42 +00003458ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003459InitializationSequence::Perform(Sema &S,
3460 const InitializedEntity &Entity,
3461 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003462 Action::MultiExprArg Args,
3463 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003464 if (SequenceKind == FailedSequence) {
3465 unsigned NumArgs = Args.size();
3466 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3467 return S.ExprError();
3468 }
3469
3470 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003471 // If the declaration is a non-dependent, incomplete array type
3472 // that has an initializer, then its type will be completed once
3473 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003474 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003475 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003476 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003477 if (const IncompleteArrayType *ArrayT
3478 = S.Context.getAsIncompleteArrayType(DeclType)) {
3479 // FIXME: We don't currently have the ability to accurately
3480 // compute the length of an initializer list without
3481 // performing full type-checking of the initializer list
3482 // (since we have to determine where braces are implicitly
3483 // introduced and such). So, we fall back to making the array
3484 // type a dependently-sized array type with no specified
3485 // bound.
3486 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3487 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003488
Douglas Gregor51e77d52009-12-10 17:56:55 +00003489 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003490 if (DeclaratorDecl *DD = Entity.getDecl()) {
3491 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3492 TypeLoc TL = TInfo->getTypeLoc();
3493 if (IncompleteArrayTypeLoc *ArrayLoc
3494 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3495 Brackets = ArrayLoc->getBracketsRange();
3496 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003497 }
3498
3499 *ResultType
3500 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3501 /*NumElts=*/0,
3502 ArrayT->getSizeModifier(),
3503 ArrayT->getIndexTypeCVRQualifiers(),
3504 Brackets);
3505 }
3506
3507 }
3508 }
3509
Eli Friedmana553d4a2009-12-22 02:35:53 +00003510 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003511 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003512
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003513 if (Args.size() == 0)
3514 return S.Owned((Expr *)0);
3515
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003516 unsigned NumArgs = Args.size();
3517 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3518 SourceLocation(),
3519 (Expr **)Args.release(),
3520 NumArgs,
3521 SourceLocation()));
3522 }
3523
Douglas Gregor85dabae2009-12-16 01:38:02 +00003524 if (SequenceKind == NoInitialization)
3525 return S.Owned((Expr *)0);
3526
Douglas Gregor1b303932009-12-22 15:35:07 +00003527 QualType DestType = Entity.getType().getNonReferenceType();
3528 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003529 // the same as Entity.getDecl()->getType() in cases involving type merging,
3530 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003531 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003532 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003533 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003534
John McCalldadc5752010-08-24 06:29:42 +00003535 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003536
3537 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3538
3539 // For initialization steps that start with a single initializer,
3540 // grab the only argument out the Args and place it into the "current"
3541 // initializer.
3542 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003543 case SK_ResolveAddressOfOverloadedFunction:
3544 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003545 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003546 case SK_CastDerivedToBaseLValue:
3547 case SK_BindReference:
3548 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003549 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003550 case SK_UserConversion:
3551 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003552 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003553 case SK_QualificationConversionRValue:
3554 case SK_ConversionSequence:
3555 case SK_ListInitialization:
3556 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003557 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003558 case SK_ObjCObjectConversion:
Douglas Gregore1314a62009-12-18 05:02:21 +00003559 assert(Args.size() == 1);
John McCalldadc5752010-08-24 06:29:42 +00003560 CurInit = ExprResult(((Expr **)(Args.get()))[0]->Retain());
Douglas Gregore1314a62009-12-18 05:02:21 +00003561 if (CurInit.isInvalid())
3562 return S.ExprError();
3563 break;
3564
3565 case SK_ConstructorInitialization:
3566 case SK_ZeroInitialization:
3567 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003568 }
3569
3570 // Walk through the computed steps for the initialization sequence,
3571 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003572 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003573 for (step_iterator Step = step_begin(), StepEnd = step_end();
3574 Step != StepEnd; ++Step) {
3575 if (CurInit.isInvalid())
3576 return S.ExprError();
3577
3578 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003579 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003580
3581 switch (Step->Kind) {
3582 case SK_ResolveAddressOfOverloadedFunction:
3583 // Overload resolution determined which function invoke; update the
3584 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003585 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003586 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003587 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003588 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003589 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003590 break;
3591
3592 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003593 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003594 case SK_CastDerivedToBaseLValue: {
3595 // We have a derived-to-base cast that produces either an rvalue or an
3596 // lvalue. Perform that cast.
3597
John McCallcf142162010-08-07 06:22:56 +00003598 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003599
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003600 // Casts to inaccessible base classes are allowed with C-style casts.
3601 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3602 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3603 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003604 CurInitExpr->getSourceRange(),
3605 &BasePath, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003606 return S.ExprError();
3607
Douglas Gregor88d292c2010-05-13 16:44:06 +00003608 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3609 QualType T = SourceType;
3610 if (const PointerType *Pointer = T->getAs<PointerType>())
3611 T = Pointer->getPointeeType();
3612 if (const RecordType *RecordTy = T->getAs<RecordType>())
3613 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3614 cast<CXXRecordDecl>(RecordTy->getDecl()));
3615 }
3616
John McCall2536c6d2010-08-25 10:28:54 +00003617 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003618 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003619 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003620 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003621 VK_XValue :
3622 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003623 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3624 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003625 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003626 CurInit.get(),
3627 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003628 break;
3629 }
3630
3631 case SK_BindReference:
3632 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3633 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3634 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003635 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003636 << BitField->getDeclName()
3637 << CurInitExpr->getSourceRange();
3638 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3639 return S.ExprError();
3640 }
Anders Carlssona91be642010-01-29 02:47:33 +00003641
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003642 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003643 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003644 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3645 << Entity.getType().isVolatileQualified()
3646 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003647 PrintInitLocationNote(S, Entity);
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003648 return S.ExprError();
3649 }
3650
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003651 // Reference binding does not have any corresponding ASTs.
3652
3653 // Check exception specifications
3654 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3655 return S.ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003656
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003657 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003658
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003659 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003660 // Reference binding does not have any corresponding ASTs.
3661
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003662 // Check exception specifications
3663 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3664 return S.ExprError();
3665
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003666 break;
3667
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003668 case SK_ExtraneousCopyToTemporary:
3669 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3670 /*IsExtraneousCopy=*/true);
3671 break;
3672
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003673 case SK_UserConversion: {
3674 // We have a user-defined conversion that invokes either a constructor
3675 // or a conversion function.
John McCalle3027922010-08-25 11:45:40 +00003676 CastKind CastKind = CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003677 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003678 FunctionDecl *Fn = Step->Function.Function;
3679 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003680 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003681 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003682 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003684 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003685 SourceLocation Loc = CurInitExpr->getLocStart();
3686 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003687
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003688 // Determine the arguments required to actually perform the constructor
3689 // call.
3690 if (S.CompleteConstructorCall(Constructor,
John McCall37ad5512010-08-23 06:44:23 +00003691 Sema::MultiExprArg(S, &CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003692 Loc, ConstructorArgs))
3693 return S.ExprError();
3694
3695 // Build the an expression that constructs a temporary.
3696 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003697 move_arg(ConstructorArgs),
3698 /*ZeroInit*/ false,
3699 CXXConstructExpr::CK_Complete);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003700 if (CurInit.isInvalid())
3701 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003702
Anders Carlssona01874b2010-04-21 18:47:17 +00003703 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003704 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003705 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706
John McCalle3027922010-08-25 11:45:40 +00003707 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003708 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3709 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3710 S.IsDerivedFrom(SourceType, Class))
3711 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003712
3713 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003714 } else {
3715 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003716 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003717 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003718 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003719 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003720 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003721
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003722 // FIXME: Should we move this initialization into a separate
3723 // derived-to-base conversion? I believe the answer is "no", because
3724 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003725 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003726 FoundFn, Conversion))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 return S.ExprError();
3728
3729 // Do a little dance to make sure that CurInit has the proper
3730 // pointer.
3731 CurInit.release();
3732
3733 // Build the actual call to the conversion function.
John McCall16df1e52010-03-30 21:47:33 +00003734 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3735 Conversion));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003736 if (CurInit.isInvalid() || !CurInit.get())
3737 return S.ExprError();
3738
John McCalle3027922010-08-25 11:45:40 +00003739 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003740
3741 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 }
3743
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003744 bool RequiresCopy = !IsCopy &&
3745 getKind() != InitializationSequence::ReferenceBinding;
3746 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003747 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003748 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3749 CurInitExpr = static_cast<Expr *>(CurInit.get());
3750 QualType T = CurInitExpr->getType();
3751 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003752 CXXDestructorDecl *Destructor
3753 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003754 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3755 S.PDiag(diag::err_access_dtor_temp) << T);
3756 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3757 }
3758 }
3759
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003760 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003761 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003762 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3763 CurInitExpr->getType(),
3764 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003765 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003766
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003767 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003768 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3769 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003770
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003771 break;
3772 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003773
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003774 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003775 case SK_QualificationConversionXValue:
3776 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003777 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003778 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003779 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003780 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003781 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003782 VK_XValue :
3783 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003784 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003785 CurInit.release();
3786 CurInit = S.Owned(CurInitExpr);
3787 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003788 }
3789
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003790 case SK_ConversionSequence: {
3791 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3792
3793 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3794 Sema::AA_Converting, IgnoreBaseAccess))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003795 return S.ExprError();
3796
3797 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003798 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003799 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003800 }
3801
Douglas Gregor51e77d52009-12-10 17:56:55 +00003802 case SK_ListInitialization: {
3803 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3804 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003805 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003806 return S.ExprError();
3807
3808 CurInit.release();
3809 CurInit = S.Owned(InitList);
3810 break;
3811 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003812
3813 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003814 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003815 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003816 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003817
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003818 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003819 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003820 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3821 ? Kind.getEqualLoc()
3822 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003823
3824 if (Kind.getKind() == InitializationKind::IK_Default) {
3825 // Force even a trivial, implicit default constructor to be
3826 // semantically checked. We do this explicitly because we don't build
3827 // the definition for completely trivial constructors.
3828 CXXRecordDecl *ClassDecl = Constructor->getParent();
3829 assert(ClassDecl && "No parent class for constructor.");
3830 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3831 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3832 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3833 }
3834
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003835 // Determine the arguments required to actually perform the constructor
3836 // call.
3837 if (S.CompleteConstructorCall(Constructor, move(Args),
3838 Loc, ConstructorArgs))
3839 return S.ExprError();
3840
Chandler Carruthc9262402010-08-23 07:55:51 +00003841
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003842 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003843 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003844 (Kind.getKind() == InitializationKind::IK_Direct ||
3845 Kind.getKind() == InitializationKind::IK_Value)) {
3846 // An explicitly-constructed temporary, e.g., X(1, 2).
3847 unsigned NumExprs = ConstructorArgs.size();
3848 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003849 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003850 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3851 Constructor,
3852 Entity.getType(),
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003853 Loc,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003854 Exprs,
3855 NumExprs,
Douglas Gregor199db362010-04-27 20:36:09 +00003856 Kind.getParenRange().getEnd(),
3857 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003858 } else {
3859 CXXConstructExpr::ConstructionKind ConstructKind =
3860 CXXConstructExpr::CK_Complete;
3861
3862 if (Entity.getKind() == InitializedEntity::EK_Base) {
3863 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3864 CXXConstructExpr::CK_VirtualBase :
3865 CXXConstructExpr::CK_NonVirtualBase;
3866 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003867
3868 // If the entity allows NRVO, mark the construction as elidable
3869 // unconditionally.
3870 if (Entity.allowsNRVO())
3871 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3872 Constructor, /*Elidable=*/true,
3873 move_arg(ConstructorArgs),
3874 ConstructorInitRequiresZeroInit,
3875 ConstructKind);
3876 else
3877 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3878 Constructor,
3879 move_arg(ConstructorArgs),
3880 ConstructorInitRequiresZeroInit,
3881 ConstructKind);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003882 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003883 if (CurInit.isInvalid())
3884 return S.ExprError();
John McCall760af172010-02-01 03:16:54 +00003885
3886 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003887 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003888 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003889 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003890
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003891 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003892 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003893
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003894 break;
3895 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003896
3897 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003898 step_iterator NextStep = Step;
3899 ++NextStep;
3900 if (NextStep != StepEnd &&
3901 NextStep->Kind == SK_ConstructorInitialization) {
3902 // The need for zero-initialization is recorded directly into
3903 // the call to the object's constructor within the next step.
3904 ConstructorInitRequiresZeroInit = true;
3905 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3906 S.getLangOptions().CPlusPlus &&
3907 !Kind.isImplicitValueInit()) {
Douglas Gregor747eb782010-07-08 06:14:04 +00003908 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(Step->Type,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003909 Kind.getRange().getBegin(),
3910 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003911 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003912 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003913 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003914 break;
3915 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003916
3917 case SK_CAssignment: {
3918 QualType SourceType = CurInitExpr->getType();
3919 Sema::AssignConvertType ConvTy =
3920 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003921
3922 // If this is a call, allow conversion to a transparent union.
3923 if (ConvTy != Sema::Compatible &&
3924 Entity.getKind() == InitializedEntity::EK_Parameter &&
3925 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3926 == Sema::Compatible)
3927 ConvTy = Sema::Compatible;
3928
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003929 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00003930 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3931 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003932 CurInitExpr,
3933 getAssignmentAction(Entity),
3934 &Complained)) {
3935 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003936 return S.ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003937 } else if (Complained)
3938 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00003939
3940 CurInit.release();
3941 CurInit = S.Owned(CurInitExpr);
3942 break;
3943 }
Eli Friedman78275202009-12-19 08:11:05 +00003944
3945 case SK_StringInit: {
3946 QualType Ty = Step->Type;
3947 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3948 break;
3949 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003950
3951 case SK_ObjCObjectConversion:
3952 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003953 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003954 S.CastCategory(CurInitExpr));
3955 CurInit.release();
3956 CurInit = S.Owned(CurInitExpr);
3957 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003958 }
3959 }
3960
3961 return move(CurInit);
3962}
3963
3964//===----------------------------------------------------------------------===//
3965// Diagnose initialization failures
3966//===----------------------------------------------------------------------===//
3967bool InitializationSequence::Diagnose(Sema &S,
3968 const InitializedEntity &Entity,
3969 const InitializationKind &Kind,
3970 Expr **Args, unsigned NumArgs) {
3971 if (SequenceKind != FailedSequence)
3972 return false;
3973
Douglas Gregor1b303932009-12-22 15:35:07 +00003974 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 switch (Failure) {
3976 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003977 // FIXME: Customize for the initialized entity?
3978 if (NumArgs == 0)
3979 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3980 << DestType.getNonReferenceType();
3981 else // FIXME: diagnostic below could be better!
3982 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3983 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003984 break;
3985
3986 case FK_ArrayNeedsInitList:
3987 case FK_ArrayNeedsInitListOrStringLiteral:
3988 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3989 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3990 break;
3991
John McCall16df1e52010-03-30 21:47:33 +00003992 case FK_AddressOfOverloadFailed: {
3993 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003994 S.ResolveAddressOfOverloadedFunction(Args[0],
3995 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00003996 true,
3997 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003998 break;
John McCall16df1e52010-03-30 21:47:33 +00003999 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004000
4001 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004002 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004003 switch (FailedOverloadResult) {
4004 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004005 if (Failure == FK_UserConversionOverloadFailed)
4006 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4007 << Args[0]->getType() << DestType
4008 << Args[0]->getSourceRange();
4009 else
4010 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4011 << DestType << Args[0]->getType()
4012 << Args[0]->getSourceRange();
4013
John McCall5c32be02010-08-24 20:38:10 +00004014 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004015 break;
4016
4017 case OR_No_Viable_Function:
4018 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4019 << Args[0]->getType() << DestType.getNonReferenceType()
4020 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004021 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004022 break;
4023
4024 case OR_Deleted: {
4025 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4026 << Args[0]->getType() << DestType.getNonReferenceType()
4027 << Args[0]->getSourceRange();
4028 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004029 OverloadingResult Ovl
4030 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004031 if (Ovl == OR_Deleted) {
4032 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4033 << Best->Function->isDeleted();
4034 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004035 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004036 }
4037 break;
4038 }
4039
4040 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004041 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004042 break;
4043 }
4044 break;
4045
4046 case FK_NonConstLValueReferenceBindingToTemporary:
4047 case FK_NonConstLValueReferenceBindingToUnrelated:
4048 S.Diag(Kind.getLocation(),
4049 Failure == FK_NonConstLValueReferenceBindingToTemporary
4050 ? diag::err_lvalue_reference_bind_to_temporary
4051 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004052 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 << DestType.getNonReferenceType()
4054 << Args[0]->getType()
4055 << Args[0]->getSourceRange();
4056 break;
4057
4058 case FK_RValueReferenceBindingToLValue:
4059 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4060 << Args[0]->getSourceRange();
4061 break;
4062
4063 case FK_ReferenceInitDropsQualifiers:
4064 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4065 << DestType.getNonReferenceType()
4066 << Args[0]->getType()
4067 << Args[0]->getSourceRange();
4068 break;
4069
4070 case FK_ReferenceInitFailed:
4071 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4072 << DestType.getNonReferenceType()
4073 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4074 << Args[0]->getType()
4075 << Args[0]->getSourceRange();
4076 break;
4077
4078 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004079 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4080 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004081 << DestType
4082 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4083 << Args[0]->getType()
4084 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004085 break;
4086
4087 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004088 SourceRange R;
4089
4090 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4091 R = SourceRange(InitList->getInit(1)->getLocStart(),
4092 InitList->getLocEnd());
4093 else
4094 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004095
4096 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00004097 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004098 break;
4099 }
4100
4101 case FK_ReferenceBindingToInitList:
4102 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4103 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4104 break;
4105
4106 case FK_InitListBadDestinationType:
4107 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4108 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4109 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004110
4111 case FK_ConstructorOverloadFailed: {
4112 SourceRange ArgsRange;
4113 if (NumArgs)
4114 ArgsRange = SourceRange(Args[0]->getLocStart(),
4115 Args[NumArgs - 1]->getLocEnd());
4116
4117 // FIXME: Using "DestType" for the entity we're printing is probably
4118 // bad.
4119 switch (FailedOverloadResult) {
4120 case OR_Ambiguous:
4121 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4122 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004123 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4124 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004125 break;
4126
4127 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004128 if (Kind.getKind() == InitializationKind::IK_Default &&
4129 (Entity.getKind() == InitializedEntity::EK_Base ||
4130 Entity.getKind() == InitializedEntity::EK_Member) &&
4131 isa<CXXConstructorDecl>(S.CurContext)) {
4132 // This is implicit default initialization of a member or
4133 // base within a constructor. If no viable function was
4134 // found, notify the user that she needs to explicitly
4135 // initialize this base/member.
4136 CXXConstructorDecl *Constructor
4137 = cast<CXXConstructorDecl>(S.CurContext);
4138 if (Entity.getKind() == InitializedEntity::EK_Base) {
4139 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4140 << Constructor->isImplicit()
4141 << S.Context.getTypeDeclType(Constructor->getParent())
4142 << /*base=*/0
4143 << Entity.getType();
4144
4145 RecordDecl *BaseDecl
4146 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4147 ->getDecl();
4148 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4149 << S.Context.getTagDeclType(BaseDecl);
4150 } else {
4151 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4152 << Constructor->isImplicit()
4153 << S.Context.getTypeDeclType(Constructor->getParent())
4154 << /*member=*/1
4155 << Entity.getName();
4156 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4157
4158 if (const RecordType *Record
4159 = Entity.getType()->getAs<RecordType>())
4160 S.Diag(Record->getDecl()->getLocation(),
4161 diag::note_previous_decl)
4162 << S.Context.getTagDeclType(Record->getDecl());
4163 }
4164 break;
4165 }
4166
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004167 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4168 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004169 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004170 break;
4171
4172 case OR_Deleted: {
4173 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4174 << true << DestType << ArgsRange;
4175 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004176 OverloadingResult Ovl
4177 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004178 if (Ovl == OR_Deleted) {
4179 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4180 << Best->Function->isDeleted();
4181 } else {
4182 llvm_unreachable("Inconsistent overload resolution?");
4183 }
4184 break;
4185 }
4186
4187 case OR_Success:
4188 llvm_unreachable("Conversion did not fail!");
4189 break;
4190 }
4191 break;
4192 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004193
4194 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004195 if (Entity.getKind() == InitializedEntity::EK_Member &&
4196 isa<CXXConstructorDecl>(S.CurContext)) {
4197 // This is implicit default-initialization of a const member in
4198 // a constructor. Complain that it needs to be explicitly
4199 // initialized.
4200 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4201 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4202 << Constructor->isImplicit()
4203 << S.Context.getTypeDeclType(Constructor->getParent())
4204 << /*const=*/1
4205 << Entity.getName();
4206 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4207 << Entity.getName();
4208 } else {
4209 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4210 << DestType << (bool)DestType->getAs<RecordType>();
4211 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004212 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004213
4214 case FK_Incomplete:
4215 S.RequireCompleteType(Kind.getLocation(), DestType,
4216 diag::err_init_incomplete_type);
4217 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004218 }
4219
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004220 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004221 return true;
4222}
Douglas Gregore1314a62009-12-18 05:02:21 +00004223
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004224void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4225 switch (SequenceKind) {
4226 case FailedSequence: {
4227 OS << "Failed sequence: ";
4228 switch (Failure) {
4229 case FK_TooManyInitsForReference:
4230 OS << "too many initializers for reference";
4231 break;
4232
4233 case FK_ArrayNeedsInitList:
4234 OS << "array requires initializer list";
4235 break;
4236
4237 case FK_ArrayNeedsInitListOrStringLiteral:
4238 OS << "array requires initializer list or string literal";
4239 break;
4240
4241 case FK_AddressOfOverloadFailed:
4242 OS << "address of overloaded function failed";
4243 break;
4244
4245 case FK_ReferenceInitOverloadFailed:
4246 OS << "overload resolution for reference initialization failed";
4247 break;
4248
4249 case FK_NonConstLValueReferenceBindingToTemporary:
4250 OS << "non-const lvalue reference bound to temporary";
4251 break;
4252
4253 case FK_NonConstLValueReferenceBindingToUnrelated:
4254 OS << "non-const lvalue reference bound to unrelated type";
4255 break;
4256
4257 case FK_RValueReferenceBindingToLValue:
4258 OS << "rvalue reference bound to an lvalue";
4259 break;
4260
4261 case FK_ReferenceInitDropsQualifiers:
4262 OS << "reference initialization drops qualifiers";
4263 break;
4264
4265 case FK_ReferenceInitFailed:
4266 OS << "reference initialization failed";
4267 break;
4268
4269 case FK_ConversionFailed:
4270 OS << "conversion failed";
4271 break;
4272
4273 case FK_TooManyInitsForScalar:
4274 OS << "too many initializers for scalar";
4275 break;
4276
4277 case FK_ReferenceBindingToInitList:
4278 OS << "referencing binding to initializer list";
4279 break;
4280
4281 case FK_InitListBadDestinationType:
4282 OS << "initializer list for non-aggregate, non-scalar type";
4283 break;
4284
4285 case FK_UserConversionOverloadFailed:
4286 OS << "overloading failed for user-defined conversion";
4287 break;
4288
4289 case FK_ConstructorOverloadFailed:
4290 OS << "constructor overloading failed";
4291 break;
4292
4293 case FK_DefaultInitOfConst:
4294 OS << "default initialization of a const variable";
4295 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004296
4297 case FK_Incomplete:
4298 OS << "initialization of incomplete type";
4299 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004300 }
4301 OS << '\n';
4302 return;
4303 }
4304
4305 case DependentSequence:
4306 OS << "Dependent sequence: ";
4307 return;
4308
4309 case UserDefinedConversion:
4310 OS << "User-defined conversion sequence: ";
4311 break;
4312
4313 case ConstructorInitialization:
4314 OS << "Constructor initialization sequence: ";
4315 break;
4316
4317 case ReferenceBinding:
4318 OS << "Reference binding: ";
4319 break;
4320
4321 case ListInitialization:
4322 OS << "List initialization: ";
4323 break;
4324
4325 case ZeroInitialization:
4326 OS << "Zero initialization\n";
4327 return;
4328
4329 case NoInitialization:
4330 OS << "No initialization\n";
4331 return;
4332
4333 case StandardConversion:
4334 OS << "Standard conversion: ";
4335 break;
4336
4337 case CAssignment:
4338 OS << "C assignment: ";
4339 break;
4340
4341 case StringInit:
4342 OS << "String initialization: ";
4343 break;
4344 }
4345
4346 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4347 if (S != step_begin()) {
4348 OS << " -> ";
4349 }
4350
4351 switch (S->Kind) {
4352 case SK_ResolveAddressOfOverloadedFunction:
4353 OS << "resolve address of overloaded function";
4354 break;
4355
4356 case SK_CastDerivedToBaseRValue:
4357 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4358 break;
4359
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004360 case SK_CastDerivedToBaseXValue:
4361 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4362 break;
4363
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004364 case SK_CastDerivedToBaseLValue:
4365 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4366 break;
4367
4368 case SK_BindReference:
4369 OS << "bind reference to lvalue";
4370 break;
4371
4372 case SK_BindReferenceToTemporary:
4373 OS << "bind reference to a temporary";
4374 break;
4375
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004376 case SK_ExtraneousCopyToTemporary:
4377 OS << "extraneous C++03 copy to temporary";
4378 break;
4379
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004380 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004381 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004382 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004383
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004384 case SK_QualificationConversionRValue:
4385 OS << "qualification conversion (rvalue)";
4386
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004387 case SK_QualificationConversionXValue:
4388 OS << "qualification conversion (xvalue)";
4389
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004390 case SK_QualificationConversionLValue:
4391 OS << "qualification conversion (lvalue)";
4392 break;
4393
4394 case SK_ConversionSequence:
4395 OS << "implicit conversion sequence (";
4396 S->ICS->DebugPrint(); // FIXME: use OS
4397 OS << ")";
4398 break;
4399
4400 case SK_ListInitialization:
4401 OS << "list initialization";
4402 break;
4403
4404 case SK_ConstructorInitialization:
4405 OS << "constructor initialization";
4406 break;
4407
4408 case SK_ZeroInitialization:
4409 OS << "zero initialization";
4410 break;
4411
4412 case SK_CAssignment:
4413 OS << "C assignment";
4414 break;
4415
4416 case SK_StringInit:
4417 OS << "string initialization";
4418 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004419
4420 case SK_ObjCObjectConversion:
4421 OS << "Objective-C object conversion";
4422 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004423 }
4424 }
4425}
4426
4427void InitializationSequence::dump() const {
4428 dump(llvm::errs());
4429}
4430
Douglas Gregore1314a62009-12-18 05:02:21 +00004431//===----------------------------------------------------------------------===//
4432// Initialization helper functions
4433//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004434ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004435Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4436 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004437 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004438 if (Init.isInvalid())
4439 return ExprError();
4440
4441 Expr *InitE = (Expr *)Init.get();
4442 assert(InitE && "No initialization expression?");
4443
4444 if (EqualLoc.isInvalid())
4445 EqualLoc = InitE->getLocStart();
4446
4447 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4448 EqualLoc);
4449 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4450 Init.release();
John McCall37ad5512010-08-23 06:44:23 +00004451 return Seq.Perform(*this, Entity, Kind, MultiExprArg(*this, &InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004452}