blob: 9593489b806374db25d26c174fd1348e26ee53e2 [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//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Chris Lattnerd8b741c82009-02-24 23:10:27 +000069static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
70 // Get the length of the string as parsed.
71 uint64_t StrLength =
72 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
73
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnerd8b741c82009-02-24 23:10:27 +000075 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +000076 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000077 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000078 // being initialized to a string literal.
79 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000080 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000081 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000082 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
83 ConstVal,
84 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 }
Mike Stump11289f42009-09-09 15:08:12 +000087
Eli Friedman893abe42009-05-29 18:22:49 +000088 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000089
Eli Friedman893abe42009-05-29 18:22:49 +000090 // C99 6.7.8p14. We have an array of character type with known size. However,
91 // the size may be smaller or larger than the string we are initializing.
92 // FIXME: Avoid truncation for 64-bit length strings.
93 if (StrLength-1 > CAT->getSize().getZExtValue())
94 S.Diag(Str->getSourceRange().getBegin(),
95 diag::warn_initializer_string_for_char_array_too_long)
96 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000097
Eli Friedman893abe42009-05-29 18:22:49 +000098 // Set the type to the actual size that we are initializing. If we have
99 // something like:
100 // char x[1] = "foo";
101 // then this will set the string literal's type to char[1].
102 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000103}
104
Chris Lattner0cb78032009-02-24 22:27:37 +0000105//===----------------------------------------------------------------------===//
106// Semantic checking for initializer lists.
107//===----------------------------------------------------------------------===//
108
Douglas Gregorcde232f2009-01-29 01:05:33 +0000109/// @brief Semantic checking for initializer lists.
110///
111/// The InitListChecker class contains a set of routines that each
112/// handle the initialization of a certain kind of entity, e.g.,
113/// arrays, vectors, struct/union types, scalars, etc. The
114/// InitListChecker itself performs a recursive walk of the subobject
115/// structure of the type to be initialized, while stepping through
116/// the initializer list one element at a time. The IList and Index
117/// parameters to each of the Check* routines contain the active
118/// (syntactic) initializer list and the index into that initializer
119/// list that represents the current initializer. Each routine is
120/// responsible for moving that Index forward as it consumes elements.
121///
122/// Each Check* routine also has a StructuredList/StructuredIndex
123/// arguments, which contains the current the "structured" (semantic)
124/// initializer list and the index into that initializer list where we
125/// are copying initializers as we map them over to the semantic
126/// list. Once we have completed our recursive walk of the subobject
127/// structure, we will have constructed a full semantic initializer
128/// list.
129///
130/// C99 designators cause changes in the initializer list traversal,
131/// because they make the initialization "jump" into a specific
132/// subobject and then continue the initialization from that
133/// point. CheckDesignatedInitializer() recursively steps into the
134/// designated subobject and manages backing out the recursion to
135/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000136namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000137class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000138 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000139 bool hadError;
140 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
141 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000142
Anders Carlsson6cabf312010-01-23 23:23:01 +0000143 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000144 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000145 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000146 unsigned &StructuredIndex,
147 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000148 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000149 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000150 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000151 unsigned &StructuredIndex,
152 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000153 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000154 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000155 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000156 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000157 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000158 unsigned &StructuredIndex,
159 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000160 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000161 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000162 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000163 InitListExpr *StructuredList,
164 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000165 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000166 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000167 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000168 InitListExpr *StructuredList,
169 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000170 void CheckReferenceType(const InitializedEntity &Entity,
171 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000172 unsigned &Index,
173 InitListExpr *StructuredList,
174 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000175 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000176 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000180 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000181 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000182 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
191 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000192 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000193 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000194 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000195 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 RecordDecl::field_iterator *NextField,
197 llvm::APSInt *NextElementIndex,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000201 bool FinishSubobjectInit,
202 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
204 QualType CurrentObjectType,
205 InitListExpr *StructuredList,
206 unsigned StructuredIndex,
207 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000208 void UpdateStructuredListElement(InitListExpr *StructuredList,
209 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000210 Expr *expr);
211 int numArrayElements(QualType DeclType);
212 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000213
Douglas Gregor2bb07652009-12-22 00:05:34 +0000214 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
215 const InitializedEntity &ParentEntity,
216 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000217 void FillInValueInitializations(const InitializedEntity &Entity,
218 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000219public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000220 InitListChecker(Sema &S, const InitializedEntity &Entity,
221 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool HadError() { return hadError; }
223
224 // @brief Retrieves the fully-structured initializer list used for
225 // semantic analysis and code generation.
226 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
227};
Chris Lattner9ececce2009-02-24 22:48:58 +0000228} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000229
Douglas Gregor2bb07652009-12-22 00:05:34 +0000230void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
231 const InitializedEntity &ParentEntity,
232 InitListExpr *ILE,
233 bool &RequiresSecondPass) {
234 SourceLocation Loc = ILE->getSourceRange().getBegin();
235 unsigned NumInits = ILE->getNumInits();
236 InitializedEntity MemberEntity
237 = InitializedEntity::InitializeMember(Field, &ParentEntity);
238 if (Init >= NumInits || !ILE->getInit(Init)) {
239 // FIXME: We probably don't need to handle references
240 // specially here, since value-initialization of references is
241 // handled in InitializationSequence.
242 if (Field->getType()->isReferenceType()) {
243 // C++ [dcl.init.aggr]p9:
244 // If an incomplete or empty initializer-list leaves a
245 // member of reference type uninitialized, the program is
246 // ill-formed.
247 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
248 << Field->getType()
249 << ILE->getSyntacticForm()->getSourceRange();
250 SemaRef.Diag(Field->getLocation(),
251 diag::note_uninit_reference_member);
252 hadError = true;
253 return;
254 }
255
256 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
257 true);
258 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
259 if (!InitSeq) {
260 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
261 hadError = true;
262 return;
263 }
264
John McCalldadc5752010-08-24 06:29:42 +0000265 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000266 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000267 if (MemberInit.isInvalid()) {
268 hadError = true;
269 return;
270 }
271
272 if (hadError) {
273 // Do nothing
274 } else if (Init < NumInits) {
275 ILE->setInit(Init, MemberInit.takeAs<Expr>());
276 } else if (InitSeq.getKind()
277 == InitializationSequence::ConstructorInitialization) {
278 // Value-initialization requires a constructor call, so
279 // extend the initializer list to include the constructor
280 // call and make a note that we'll need to take another pass
281 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000282 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000283 RequiresSecondPass = true;
284 }
285 } else if (InitListExpr *InnerILE
286 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
287 FillInValueInitializations(MemberEntity, InnerILE,
288 RequiresSecondPass);
289}
290
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000291/// Recursively replaces NULL values within the given initializer list
292/// with expressions that perform value-initialization of the
293/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000294void
295InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
296 InitListExpr *ILE,
297 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000298 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000299 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000300 SourceLocation Loc = ILE->getSourceRange().getBegin();
301 if (ILE->getSyntacticForm())
302 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000303
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000304 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000305 if (RType->getDecl()->isUnion() &&
306 ILE->getInitializedFieldInUnion())
307 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
308 Entity, ILE, RequiresSecondPass);
309 else {
310 unsigned Init = 0;
311 for (RecordDecl::field_iterator
312 Field = RType->getDecl()->field_begin(),
313 FieldEnd = RType->getDecl()->field_end();
314 Field != FieldEnd; ++Field) {
315 if (Field->isUnnamedBitfield())
316 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000317
Douglas Gregor2bb07652009-12-22 00:05:34 +0000318 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000319 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000320
321 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
322 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000323 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000324
Douglas Gregor2bb07652009-12-22 00:05:34 +0000325 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000326
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327 // Only look at the first initialization of a union.
328 if (RType->getDecl()->isUnion())
329 break;
330 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000331 }
332
333 return;
Mike Stump11289f42009-09-09 15:08:12 +0000334 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000335
336 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000337
Douglas Gregor723796a2009-12-16 06:35:08 +0000338 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000339 unsigned NumInits = ILE->getNumInits();
340 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000341 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000342 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000343 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
344 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000345 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
346 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000347 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000348 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000349 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000350 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
351 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000352 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000353 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000354
Douglas Gregor723796a2009-12-16 06:35:08 +0000355
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000356 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000357 if (hadError)
358 return;
359
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000360 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
361 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000362 ElementEntity.setElementIndex(Init);
363
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000364 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000365 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
366 true);
367 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
368 if (!InitSeq) {
369 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000370 hadError = true;
371 return;
372 }
373
John McCalldadc5752010-08-24 06:29:42 +0000374 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000375 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000377 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 return;
379 }
380
381 if (hadError) {
382 // Do nothing
383 } else if (Init < NumInits) {
384 ILE->setInit(Init, ElementInit.takeAs<Expr>());
385 } else if (InitSeq.getKind()
386 == InitializationSequence::ConstructorInitialization) {
387 // Value-initialization requires a constructor call, so
388 // extend the initializer list to include the constructor
389 // call and make a note that we'll need to take another pass
390 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000391 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000392 RequiresSecondPass = true;
393 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000394 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000395 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
396 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000397 }
398}
399
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000400
Douglas Gregor723796a2009-12-16 06:35:08 +0000401InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
402 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000403 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000404 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000405
Eli Friedman23a9e312008-05-19 19:16:24 +0000406 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000407 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000408 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000409 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson6cabf312010-01-23 23:23:01 +0000410 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000411 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000412 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000413
Douglas Gregor723796a2009-12-16 06:35:08 +0000414 if (!hadError) {
415 bool RequiresSecondPass = false;
416 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000417 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 FillInValueInitializations(Entity, FullyStructuredList,
419 RequiresSecondPass);
420 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000421}
422
423int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000424 // FIXME: use a proper constant
425 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000426 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000427 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000428 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
429 }
430 return maxElements;
431}
432
433int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000434 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000435 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000436 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000437 Field = structDecl->field_begin(),
438 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000439 Field != FieldEnd; ++Field) {
440 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
441 ++InitializableMembers;
442 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000443 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000444 return std::min(InitializableMembers, 1);
445 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000446}
447
Anders Carlsson6cabf312010-01-23 23:23:01 +0000448void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000449 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000450 QualType T, unsigned &Index,
451 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000452 unsigned &StructuredIndex,
453 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000454 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000455
Steve Narofff8ecff22008-05-01 22:18:59 +0000456 if (T->isArrayType())
457 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000458 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000459 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000460 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000461 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000462 else
463 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000464
Eli Friedmane0f832b2008-05-25 13:49:22 +0000465 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000466 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000467 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000469 hadError = true;
470 return;
471 }
472
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000473 // Build a structured initializer list corresponding to this subobject.
474 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000475 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
476 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000477 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
478 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000479 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000480
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000481 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000482 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000483 CheckListElementTypes(Entity, ParentIList, T,
484 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000485 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000486 StructuredSubobjectInitIndex,
487 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000488 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000489 StructuredSubobjectInitList->setType(T);
490
Douglas Gregor5741efb2009-03-01 17:12:46 +0000491 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000492 // range corresponds with the end of the last initializer it used.
493 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000494 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000495 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
496 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
497 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000498
499 // Warn about missing braces.
500 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000501 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
502 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000503 << StructuredSubobjectInitList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000504 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
505 "{")
506 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
Tanya Lattner5cb196e2010-03-07 04:47:12 +0000507 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000508 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000509 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000510}
511
Anders Carlsson6cabf312010-01-23 23:23:01 +0000512void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000513 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000518 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000519 SyntacticToSemantic[IList] = StructuredList;
520 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000521 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
522 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000523 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
524 IList->setType(ExprTy);
525 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000526 if (hadError)
527 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000528
Eli Friedman85f54972008-05-25 13:22:35 +0000529 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000530 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000531 if (StructuredIndex == 1 &&
532 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000533 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000534 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000535 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000536 hadError = true;
537 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000538 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000539 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000540 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000541 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000542 // Don't complain for incomplete types, since we'll get an error
543 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000544 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000545 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000546 CurrentObjectType->isArrayType()? 0 :
547 CurrentObjectType->isVectorType()? 1 :
548 CurrentObjectType->isScalarType()? 2 :
549 CurrentObjectType->isUnionType()? 3 :
550 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000551
552 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000553 if (SemaRef.getLangOptions().CPlusPlus) {
554 DK = diag::err_excess_initializers;
555 hadError = true;
556 }
Nate Begeman425038c2009-07-07 21:53:06 +0000557 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
558 DK = diag::err_excess_initializers;
559 hadError = true;
560 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000561
Chris Lattnerb0912a52009-02-24 22:50:46 +0000562 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000563 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000564 }
565 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000566
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000567 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000568 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000569 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000570 << FixItHint::CreateRemoval(IList->getLocStart())
571 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000572}
573
Anders Carlsson6cabf312010-01-23 23:23:01 +0000574void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000575 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000576 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000577 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000578 unsigned &Index,
579 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000580 unsigned &StructuredIndex,
581 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000582 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000583 CheckScalarType(Entity, IList, DeclType, Index,
584 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000585 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000586 CheckVectorType(Entity, IList, DeclType, Index,
587 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000588 } else if (DeclType->isAggregateType()) {
589 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000590 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000591 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000593 StructuredList, StructuredIndex,
594 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000595 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000596 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000597 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000598 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000599 CheckArrayType(Entity, IList, DeclType, Zero,
600 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000601 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000602 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000603 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000604 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
605 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000606 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000608 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000609 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000610 } else if (DeclType->isRecordType()) {
611 // C++ [dcl.init]p14:
612 // [...] If the class is an aggregate (8.5.1), and the initializer
613 // is a brace-enclosed list, see 8.5.1.
614 //
615 // Note: 8.5.1 is handled below; here, we diagnose the case where
616 // we have an initializer list and a destination type that is not
617 // an aggregate.
618 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000619 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000620 << DeclType << IList->getSourceRange();
621 hadError = true;
622 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000623 CheckReferenceType(Entity, IList, DeclType, Index,
624 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000625 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000626 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
627 << DeclType;
628 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000629 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000630 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
631 << DeclType;
632 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000633 }
634}
635
Anders Carlsson6cabf312010-01-23 23:23:01 +0000636void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000637 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000638 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000639 unsigned &Index,
640 InitListExpr *StructuredList,
641 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000642 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000643 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
644 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000645 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000646 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 = getStructuredSubobjectInit(IList, Index, ElemType,
648 StructuredList, StructuredIndex,
649 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000650 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000651 newStructuredList, newStructuredIndex);
652 ++StructuredIndex;
653 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000654 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
655 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000656 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000657 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000658 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000659 CheckScalarType(Entity, IList, ElemType, Index,
660 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000661 } else if (ElemType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000662 CheckReferenceType(Entity, IList, ElemType, Index,
663 StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000664 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000665 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000666 // C++ [dcl.init.aggr]p12:
667 // All implicit type conversions (clause 4) are considered when
668 // initializing the aggregate member with an ini- tializer from
669 // an initializer-list. If the initializer can initialize a
670 // member, the member is initialized. [...]
Anders Carlsson03068aa2009-08-27 17:18:13 +0000671
Anders Carlsson0bd52402010-01-24 00:19:41 +0000672 // FIXME: Better EqualLoc?
673 InitializationKind Kind =
674 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
675 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
676
677 if (Seq) {
John McCalldadc5752010-08-24 06:29:42 +0000678 ExprResult Result =
John McCallfaf5fb42010-08-26 23:41:50 +0000679 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
Anders Carlsson0bd52402010-01-24 00:19:41 +0000680 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000681 hadError = true;
Anders Carlsson0bd52402010-01-24 00:19:41 +0000682
683 UpdateStructuredListElement(StructuredList, StructuredIndex,
684 Result.takeAs<Expr>());
Douglas Gregord14247a2009-01-30 22:09:00 +0000685 ++Index;
686 return;
687 }
688
689 // Fall through for subaggregate initialization
690 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000691 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000692 //
693 // The initializer for a structure or union object that has
694 // automatic storage duration shall be either an initializer
695 // list as described below, or a single expression that has
696 // compatible structure or union type. In the latter case, the
697 // initial value of the object, including unnamed members, is
698 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000699 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000700 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
John McCall211e6992010-12-04 09:03:57 +0000701 SemaRef.DefaultFunctionArrayLvalueConversion(expr);
Douglas Gregord14247a2009-01-30 22:09:00 +0000702 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
703 ++Index;
704 return;
705 }
706
707 // Fall through for subaggregate initialization
708 }
709
710 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000711 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000712 // [...] Otherwise, if the member is itself a non-empty
713 // subaggregate, brace elision is assumed and the initializer is
714 // considered for the initialization of the first member of
715 // the subaggregate.
716 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000717 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000718 StructuredIndex);
719 ++StructuredIndex;
720 } else {
721 // We cannot initialize this element, so let
722 // PerformCopyInitialization produce the appropriate diagnostic.
Anders Carlssona18f0fb2010-01-30 01:56:32 +0000723 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
724 SemaRef.Owned(expr));
Douglas Gregord14247a2009-01-30 22:09:00 +0000725 hadError = true;
726 ++Index;
727 ++StructuredIndex;
728 }
729 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000730}
731
Anders Carlsson6cabf312010-01-23 23:23:01 +0000732void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000733 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000734 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000735 InitListExpr *StructuredList,
736 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000737 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000738 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000739 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000740 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000741 ++Index;
742 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000743 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000744 }
John McCall643169b2010-11-11 00:46:36 +0000745
746 Expr *expr = IList->getInit(Index);
747 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
748 SemaRef.Diag(SubIList->getLocStart(),
749 diag::warn_many_braces_around_scalar_init)
750 << SubIList->getSourceRange();
751
752 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
753 StructuredIndex);
754 return;
755 } else if (isa<DesignatedInitExpr>(expr)) {
756 SemaRef.Diag(expr->getSourceRange().getBegin(),
757 diag::err_designator_for_scalar_init)
758 << DeclType << expr->getSourceRange();
759 hadError = true;
760 ++Index;
761 ++StructuredIndex;
762 return;
763 }
764
765 ExprResult Result =
766 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
767 SemaRef.Owned(expr));
768
769 Expr *ResultExpr = 0;
770
771 if (Result.isInvalid())
772 hadError = true; // types weren't compatible.
773 else {
774 ResultExpr = Result.takeAs<Expr>();
775
776 if (ResultExpr != expr) {
777 // The type was promoted, update initializer list.
778 IList->setInit(Index, ResultExpr);
779 }
780 }
781 if (hadError)
782 ++StructuredIndex;
783 else
784 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
785 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000786}
787
Anders Carlsson6cabf312010-01-23 23:23:01 +0000788void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
789 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000790 unsigned &Index,
791 InitListExpr *StructuredList,
792 unsigned &StructuredIndex) {
793 if (Index < IList->getNumInits()) {
794 Expr *expr = IList->getInit(Index);
795 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000796 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000797 << DeclType << IList->getSourceRange();
798 hadError = true;
799 ++Index;
800 ++StructuredIndex;
801 return;
Mike Stump11289f42009-09-09 15:08:12 +0000802 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000803
John McCalldadc5752010-08-24 06:29:42 +0000804 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000805 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
806 SemaRef.Owned(expr));
807
808 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000809 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000810
811 expr = Result.takeAs<Expr>();
812 IList->setInit(Index, expr);
813
Douglas Gregord14247a2009-01-30 22:09:00 +0000814 if (hadError)
815 ++StructuredIndex;
816 else
817 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
818 ++Index;
819 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000820 // FIXME: It would be wonderful if we could point at the actual member. In
821 // general, it would be useful to pass location information down the stack,
822 // so that we know the location (or decl) of the "current object" being
823 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000824 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000825 diag::err_init_reference_member_uninitialized)
826 << DeclType
827 << IList->getSourceRange();
828 hadError = true;
829 ++Index;
830 ++StructuredIndex;
831 return;
832 }
833}
834
Anders Carlsson6cabf312010-01-23 23:23:01 +0000835void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000836 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000837 unsigned &Index,
838 InitListExpr *StructuredList,
839 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000840 if (Index >= IList->getNumInits())
841 return;
Mike Stump11289f42009-09-09 15:08:12 +0000842
John McCall6a16b2f2010-10-30 00:11:39 +0000843 const VectorType *VT = DeclType->getAs<VectorType>();
844 unsigned maxElements = VT->getNumElements();
845 unsigned numEltsInit = 0;
846 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000847
John McCall6a16b2f2010-10-30 00:11:39 +0000848 if (!SemaRef.getLangOptions().OpenCL) {
849 // If the initializing element is a vector, try to copy-initialize
850 // instead of breaking it apart (which is doomed to failure anyway).
851 Expr *Init = IList->getInit(Index);
852 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
853 ExprResult Result =
854 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
855 SemaRef.Owned(Init));
856
857 Expr *ResultExpr = 0;
858 if (Result.isInvalid())
859 hadError = true; // types weren't compatible.
860 else {
861 ResultExpr = Result.takeAs<Expr>();
Anders Carlsson6cabf312010-01-23 23:23:01 +0000862
John McCall6a16b2f2010-10-30 00:11:39 +0000863 if (ResultExpr != Init) {
864 // The type was promoted, update initializer list.
865 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000866 }
867 }
John McCall6a16b2f2010-10-30 00:11:39 +0000868 if (hadError)
869 ++StructuredIndex;
870 else
871 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
872 ++Index;
873 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000874 }
Mike Stump11289f42009-09-09 15:08:12 +0000875
John McCall6a16b2f2010-10-30 00:11:39 +0000876 InitializedEntity ElementEntity =
877 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
878
879 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
880 // Don't attempt to go past the end of the init list
881 if (Index >= IList->getNumInits())
882 break;
883
884 ElementEntity.setElementIndex(Index);
885 CheckSubElementType(ElementEntity, IList, elementType, Index,
886 StructuredList, StructuredIndex);
887 }
888 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000889 }
John McCall6a16b2f2010-10-30 00:11:39 +0000890
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 // OpenCL initializers allows vectors to be constructed from vectors.
895 for (unsigned i = 0; i < maxElements; ++i) {
896 // Don't attempt to go past the end of the init list
897 if (Index >= IList->getNumInits())
898 break;
899
900 ElementEntity.setElementIndex(Index);
901
902 QualType IType = IList->getInit(Index)->getType();
903 if (!IType->isVectorType()) {
904 CheckSubElementType(ElementEntity, IList, elementType, Index,
905 StructuredList, StructuredIndex);
906 ++numEltsInit;
907 } else {
908 QualType VecType;
909 const VectorType *IVT = IType->getAs<VectorType>();
910 unsigned numIElts = IVT->getNumElements();
911
912 if (IType->isExtVectorType())
913 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
914 else
915 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000916 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000917 CheckSubElementType(ElementEntity, IList, VecType, Index,
918 StructuredList, StructuredIndex);
919 numEltsInit += numIElts;
920 }
921 }
922
923 // OpenCL requires all elements to be initialized.
924 if (numEltsInit != maxElements)
925 if (SemaRef.getLangOptions().OpenCL)
926 SemaRef.Diag(IList->getSourceRange().getBegin(),
927 diag::err_vector_incorrect_num_initializers)
928 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000929}
930
Anders Carlsson6cabf312010-01-23 23:23:01 +0000931void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000932 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000933 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000934 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000935 unsigned &Index,
936 InitListExpr *StructuredList,
937 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000938 // Check for the special-case of initializing an array with a string.
939 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000940 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
941 SemaRef.Context)) {
942 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000943 // We place the string literal directly into the resulting
944 // initializer list. This is the only place where the structure
945 // of the structured initializer list doesn't match exactly,
946 // because doing so would involve allocating one character
947 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000948 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000949 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000950 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000951 return;
952 }
953 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000954 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000955 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000956 // Check for VLAs; in standard C it would be possible to check this
957 // earlier, but I don't know where clang accepts VLAs (gcc accepts
958 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000959 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000960 diag::err_variable_object_no_init)
961 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000962 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000963 ++Index;
964 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000965 return;
966 }
967
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000968 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000969 llvm::APSInt maxElements(elementIndex.getBitWidth(),
970 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000971 bool maxElementsKnown = false;
972 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000973 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000974 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +0000975 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000976 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000977 maxElementsKnown = true;
978 }
979
Chris Lattnerb0912a52009-02-24 22:50:46 +0000980 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000981 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000982 while (Index < IList->getNumInits()) {
983 Expr *Init = IList->getInit(Index);
984 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000985 // If we're not the subobject that matches up with the '{' for
986 // the designator, we shouldn't be handling the
987 // designator. Return immediately.
988 if (!SubobjectIsDesignatorContext)
989 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000990
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000991 // Handle this designated initializer. elementIndex will be
992 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000993 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000994 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000995 StructuredList, StructuredIndex, true,
996 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000997 hadError = true;
998 continue;
999 }
1000
Douglas Gregor033d1252009-01-23 16:54:12 +00001001 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001002 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001003 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001004 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001005 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001006
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001007 // If the array is of incomplete type, keep track of the number of
1008 // elements in the initializer.
1009 if (!maxElementsKnown && elementIndex > maxElements)
1010 maxElements = elementIndex;
1011
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001012 continue;
1013 }
1014
1015 // If we know the maximum number of elements, and we've already
1016 // hit it, stop consuming elements in the initializer list.
1017 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001018 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001019
Anders Carlsson6cabf312010-01-23 23:23:01 +00001020 InitializedEntity ElementEntity =
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001021 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001022 Entity);
1023 // Check this element.
1024 CheckSubElementType(ElementEntity, IList, elementType, Index,
1025 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001026 ++elementIndex;
1027
1028 // If the array is of incomplete type, keep track of the number of
1029 // elements in the initializer.
1030 if (!maxElementsKnown && elementIndex > maxElements)
1031 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001032 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001033 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001034 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001035 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001036 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001037 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001038 // Sizing an array implicitly to zero is not allowed by ISO C,
1039 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001040 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001041 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001042 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001043
Mike Stump11289f42009-09-09 15:08:12 +00001044 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001045 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001046 }
1047}
1048
Anders Carlsson6cabf312010-01-23 23:23:01 +00001049void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001050 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001051 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001052 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001053 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001054 unsigned &Index,
1055 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001056 unsigned &StructuredIndex,
1057 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001058 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001059
Eli Friedman23a9e312008-05-19 19:16:24 +00001060 // If the record is invalid, some of it's members are invalid. To avoid
1061 // confusion, we forgo checking the intializer for the entire record.
1062 if (structDecl->isInvalidDecl()) {
1063 hadError = true;
1064 return;
Mike Stump11289f42009-09-09 15:08:12 +00001065 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001066
1067 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1068 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001069 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001070 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001071 Field != FieldEnd; ++Field) {
1072 if (Field->getDeclName()) {
1073 StructuredList->setInitializedFieldInUnion(*Field);
1074 break;
1075 }
1076 }
1077 return;
1078 }
1079
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001080 // If structDecl is a forward declaration, this loop won't do
1081 // anything except look at designated initializers; That's okay,
1082 // because an error should get printed out elsewhere. It might be
1083 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001084 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001085 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001086 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001087 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001088 while (Index < IList->getNumInits()) {
1089 Expr *Init = IList->getInit(Index);
1090
1091 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001092 // If we're not the subobject that matches up with the '{' for
1093 // the designator, we shouldn't be handling the
1094 // designator. Return immediately.
1095 if (!SubobjectIsDesignatorContext)
1096 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001097
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001098 // Handle this designated initializer. Field will be updated to
1099 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001100 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001101 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001102 StructuredList, StructuredIndex,
1103 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001104 hadError = true;
1105
Douglas Gregora9add4e2009-02-12 19:00:39 +00001106 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001107
1108 // Disable check for missing fields when designators are used.
1109 // This matches gcc behaviour.
1110 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001111 continue;
1112 }
1113
1114 if (Field == FieldEnd) {
1115 // We've run out of fields. We're done.
1116 break;
1117 }
1118
Douglas Gregora9add4e2009-02-12 19:00:39 +00001119 // We've already initialized a member of a union. We're done.
1120 if (InitializedSomething && DeclType->isUnionType())
1121 break;
1122
Douglas Gregor91f84212008-12-11 16:49:14 +00001123 // If we've hit the flexible array member at the end, we're done.
1124 if (Field->getType()->isIncompleteArrayType())
1125 break;
1126
Douglas Gregor51695702009-01-29 16:53:55 +00001127 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001128 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001129 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001130 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001131 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001132
Anders Carlsson6cabf312010-01-23 23:23:01 +00001133 InitializedEntity MemberEntity =
1134 InitializedEntity::InitializeMember(*Field, &Entity);
1135 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1136 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001137 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001138
1139 if (DeclType->isUnionType()) {
1140 // Initialize the first field within the union.
1141 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001142 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001143
1144 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001145 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001146
John McCalle40b58e2010-03-11 19:32:38 +00001147 // Emit warnings for missing struct field initializers.
Douglas Gregor8fba4f22010-06-18 21:43:10 +00001148 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001149 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1150 // It is possible we have one or more unnamed bitfields remaining.
1151 // Find first (if any) named field and emit warning.
1152 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1153 it != end; ++it) {
1154 if (!it->isUnnamedBitfield()) {
1155 SemaRef.Diag(IList->getSourceRange().getEnd(),
1156 diag::warn_missing_field_initializers) << it->getName();
1157 break;
1158 }
1159 }
1160 }
1161
Mike Stump11289f42009-09-09 15:08:12 +00001162 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001163 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001164 return;
1165
1166 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001167 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001168 (!isa<InitListExpr>(IList->getInit(Index)) ||
1169 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001170 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001171 diag::err_flexible_array_init_nonempty)
1172 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001173 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001174 << *Field;
1175 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001176 ++Index;
1177 return;
1178 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001179 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001180 diag::ext_flexible_array_init)
1181 << IList->getInit(Index)->getSourceRange().getBegin();
1182 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1183 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001184 }
1185
Anders Carlsson6cabf312010-01-23 23:23:01 +00001186 InitializedEntity MemberEntity =
1187 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlssondbb25a32010-01-23 20:47:59 +00001188
Anders Carlsson6cabf312010-01-23 23:23:01 +00001189 if (isa<InitListExpr>(IList->getInit(Index)))
1190 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1191 StructuredList, StructuredIndex);
1192 else
1193 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001194 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001195}
Steve Narofff8ecff22008-05-01 22:18:59 +00001196
Douglas Gregord5846a12009-04-15 06:41:24 +00001197/// \brief Expand a field designator that refers to a member of an
1198/// anonymous struct or union into a series of field designators that
1199/// refers to the field within the appropriate subobject.
1200///
Douglas Gregord5846a12009-04-15 06:41:24 +00001201static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001202 DesignatedInitExpr *DIE,
1203 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001204 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001205 typedef DesignatedInitExpr::Designator Designator;
1206
Douglas Gregord5846a12009-04-15 06:41:24 +00001207 // Build the replacement designators.
1208 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001209 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1210 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1211 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001212 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001213 DIE->getDesignator(DesigIdx)->getDotLoc(),
1214 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1215 else
1216 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1217 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001218 assert(isa<FieldDecl>(*PI));
1219 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001220 }
1221
1222 // Expand the current designator into the set of replacement
1223 // designators, so we have a full subobject path down to where the
1224 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001225 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001226 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001227}
Mike Stump11289f42009-09-09 15:08:12 +00001228
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001229/// \brief Given an implicit anonymous field, search the IndirectField that
1230/// corresponds to FieldName.
1231static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1232 IdentifierInfo *FieldName) {
1233 assert(AnonField->isAnonymousStructOrUnion());
1234 Decl *NextDecl = AnonField->getNextDeclInContext();
1235 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1236 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1237 return IF;
1238 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001239 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001240 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001241}
1242
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001243/// @brief Check the well-formedness of a C99 designated initializer.
1244///
1245/// Determines whether the designated initializer @p DIE, which
1246/// resides at the given @p Index within the initializer list @p
1247/// IList, is well-formed for a current object of type @p DeclType
1248/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001249/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001250/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001251///
1252/// @param IList The initializer list in which this designated
1253/// initializer occurs.
1254///
Douglas Gregora5324162009-04-15 04:56:10 +00001255/// @param DIE The designated initializer expression.
1256///
1257/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001258///
1259/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1260/// into which the designation in @p DIE should refer.
1261///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001262/// @param NextField If non-NULL and the first designator in @p DIE is
1263/// a field, this will be set to the field declaration corresponding
1264/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001265///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001266/// @param NextElementIndex If non-NULL and the first designator in @p
1267/// DIE is an array designator or GNU array-range designator, this
1268/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001269///
1270/// @param Index Index into @p IList where the designated initializer
1271/// @p DIE occurs.
1272///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001273/// @param StructuredList The initializer list expression that
1274/// describes all of the subobject initializers in the order they'll
1275/// actually be initialized.
1276///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001277/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001278bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001279InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001280 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001281 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001282 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001283 QualType &CurrentObjectType,
1284 RecordDecl::field_iterator *NextField,
1285 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001286 unsigned &Index,
1287 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001288 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001289 bool FinishSubobjectInit,
1290 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001291 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001292 // Check the actual initialization for the designated object type.
1293 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001294
1295 // Temporarily remove the designator expression from the
1296 // initializer list that the child calls see, so that we don't try
1297 // to re-process the designator.
1298 unsigned OldIndex = Index;
1299 IList->setInit(OldIndex, DIE->getInit());
1300
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001301 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001302 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001303
1304 // Restore the designated initializer expression in the syntactic
1305 // form of the initializer list.
1306 if (IList->getInit(OldIndex) != DIE->getInit())
1307 DIE->setInit(IList->getInit(OldIndex));
1308 IList->setInit(OldIndex, DIE);
1309
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001310 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001311 }
1312
Douglas Gregora5324162009-04-15 04:56:10 +00001313 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001314 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001315 "Need a non-designated initializer list to start from");
1316
Douglas Gregora5324162009-04-15 04:56:10 +00001317 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001318 // Determine the structural initializer list that corresponds to the
1319 // current subobject.
1320 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001321 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001322 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001323 SourceRange(D->getStartLocation(),
1324 DIE->getSourceRange().getEnd()));
1325 assert(StructuredList && "Expected a structured initializer list");
1326
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001327 if (D->isFieldDesignator()) {
1328 // C99 6.7.8p7:
1329 //
1330 // If a designator has the form
1331 //
1332 // . identifier
1333 //
1334 // then the current object (defined below) shall have
1335 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001336 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001337 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001338 if (!RT) {
1339 SourceLocation Loc = D->getDotLoc();
1340 if (Loc.isInvalid())
1341 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001342 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1343 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001344 ++Index;
1345 return true;
1346 }
1347
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001348 // Note: we perform a linear search of the fields here, despite
1349 // the fact that we have a faster lookup method, because we always
1350 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001351 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001352 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001353 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001354 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001355 Field = RT->getDecl()->field_begin(),
1356 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001357 for (; Field != FieldEnd; ++Field) {
1358 if (Field->isUnnamedBitfield())
1359 continue;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001360
1361 // If we find a field representing an anonymous field, look in the
1362 // IndirectFieldDecl that follow for the designated initializer.
1363 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1364 if (IndirectFieldDecl *IF =
1365 FindIndirectFieldDesignator(*Field, FieldName)) {
1366 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1367 D = DIE->getDesignator(DesigIdx);
1368 break;
1369 }
1370 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001371 if (KnownField && KnownField == *Field)
1372 break;
1373 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001374 break;
1375
1376 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001377 }
1378
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001379 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001380 // There was no normal field in the struct with the designated
1381 // name. Perform another lookup for this name, which may find
1382 // something that we can't designate (e.g., a member function),
1383 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001384 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001385 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001386 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001387 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001388 // Name lookup didn't find anything. Determine whether this
1389 // was a typo for another field name.
1390 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1391 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001392 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1393 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001394 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001395 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001396 ->Equals(RT->getDecl())) {
1397 SemaRef.Diag(D->getFieldLoc(),
1398 diag::err_field_designator_unknown_suggest)
1399 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001400 << FixItHint::CreateReplacement(D->getFieldLoc(),
1401 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001402 SemaRef.Diag(ReplacementField->getLocation(),
1403 diag::note_previous_decl)
1404 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001405 } else {
1406 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1407 << FieldName << CurrentObjectType;
1408 ++Index;
1409 return true;
1410 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001411 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001412
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001413 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001414 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001415 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001416 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001417 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001418 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001419 ++Index;
1420 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001421 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001422
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001423 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001424 // The replacement field comes from typo correction; find it
1425 // in the list of fields.
1426 FieldIndex = 0;
1427 Field = RT->getDecl()->field_begin();
1428 for (; Field != FieldEnd; ++Field) {
1429 if (Field->isUnnamedBitfield())
1430 continue;
1431
1432 if (ReplacementField == *Field ||
1433 Field->getIdentifier() == ReplacementField->getIdentifier())
1434 break;
1435
1436 ++FieldIndex;
1437 }
1438 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001439 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001440
1441 // All of the fields of a union are located at the same place in
1442 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001443 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001444 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001445 StructuredList->setInitializedFieldInUnion(*Field);
1446 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001447
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001448 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001449 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001450
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001451 // Make sure that our non-designated initializer list has space
1452 // for a subobject corresponding to this field.
1453 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001454 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001455
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001456 // This designator names a flexible array member.
1457 if (Field->getType()->isIncompleteArrayType()) {
1458 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001459 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 // We can't designate an object within the flexible array
1461 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001462 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001463 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001464 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001465 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001466 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001467 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001468 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001469 << *Field;
1470 Invalid = true;
1471 }
1472
Chris Lattner001b29c2010-10-10 17:49:49 +00001473 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1474 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001475 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001476 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001477 diag::err_flexible_array_init_needs_braces)
1478 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001479 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 << *Field;
1481 Invalid = true;
1482 }
1483
1484 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001485 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001486 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001487 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001488 diag::err_flexible_array_init_nonempty)
1489 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001490 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 << *Field;
1492 Invalid = true;
1493 }
1494
1495 if (Invalid) {
1496 ++Index;
1497 return true;
1498 }
1499
1500 // Initialize the array.
1501 bool prevHadError = hadError;
1502 unsigned newStructuredIndex = FieldIndex;
1503 unsigned OldIndex = Index;
1504 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001505
1506 InitializedEntity MemberEntity =
1507 InitializedEntity::InitializeMember(*Field, &Entity);
1508 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001509 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001510
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001511 IList->setInit(OldIndex, DIE);
1512 if (hadError && !prevHadError) {
1513 ++Field;
1514 ++FieldIndex;
1515 if (NextField)
1516 *NextField = Field;
1517 StructuredIndex = FieldIndex;
1518 return true;
1519 }
1520 } else {
1521 // Recurse to check later designated subobjects.
1522 QualType FieldType = (*Field)->getType();
1523 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001524
1525 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001526 InitializedEntity::InitializeMember(*Field, &Entity);
1527 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001528 FieldType, 0, 0, Index,
1529 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001530 true, false))
1531 return true;
1532 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001533
1534 // Find the position of the next field to be initialized in this
1535 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001536 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001537 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001538
1539 // If this the first designator, our caller will continue checking
1540 // the rest of this struct/class/union subobject.
1541 if (IsFirstDesignator) {
1542 if (NextField)
1543 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001544 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001545 return false;
1546 }
1547
Douglas Gregor17bd0942009-01-28 23:36:17 +00001548 if (!FinishSubobjectInit)
1549 return false;
1550
Douglas Gregord5846a12009-04-15 06:41:24 +00001551 // We've already initialized something in the union; we're done.
1552 if (RT->getDecl()->isUnion())
1553 return hadError;
1554
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001555 // Check the remaining fields within this class/struct/union subobject.
1556 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001557
Anders Carlsson6cabf312010-01-23 23:23:01 +00001558 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001559 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001560 return hadError && !prevHadError;
1561 }
1562
1563 // C99 6.7.8p6:
1564 //
1565 // If a designator has the form
1566 //
1567 // [ constant-expression ]
1568 //
1569 // then the current object (defined below) shall have array
1570 // type and the expression shall be an integer constant
1571 // expression. If the array is of unknown size, any
1572 // nonnegative value is valid.
1573 //
1574 // Additionally, cope with the GNU extension that permits
1575 // designators of the form
1576 //
1577 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001578 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001579 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001580 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001581 << CurrentObjectType;
1582 ++Index;
1583 return true;
1584 }
1585
1586 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001587 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1588 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001590 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001591 DesignatedEndIndex = DesignatedStartIndex;
1592 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001594
Mike Stump11289f42009-09-09 15:08:12 +00001595
1596 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001597 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001598 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001599 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001600 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001601
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001602 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001603 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001604 }
1605
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 if (isa<ConstantArrayType>(AT)) {
1607 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001608 DesignatedStartIndex
1609 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001610 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001611 DesignatedEndIndex
1612 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001613 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1614 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001615 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001616 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001617 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001618 << IndexExpr->getSourceRange();
1619 ++Index;
1620 return true;
1621 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001622 } else {
1623 // Make sure the bit-widths and signedness match.
1624 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001625 DesignatedEndIndex
1626 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001627 else if (DesignatedStartIndex.getBitWidth() <
1628 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001629 DesignatedStartIndex
1630 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001631 DesignatedStartIndex.setIsUnsigned(true);
1632 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001635 // Make sure that our non-designated initializer list has space
1636 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001637 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001638 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001639 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001640
Douglas Gregor17bd0942009-01-28 23:36:17 +00001641 // Repeatedly perform subobject initializations in the range
1642 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001643
Douglas Gregor17bd0942009-01-28 23:36:17 +00001644 // Move to the next designator
1645 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1646 unsigned OldIndex = Index;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001647
1648 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001649 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001650
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651 while (DesignatedStartIndex <= DesignatedEndIndex) {
1652 // Recurse to check later designated subobjects.
1653 QualType ElementType = AT->getElementType();
1654 Index = OldIndex;
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001655
1656 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001657 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001658 ElementType, 0, 0, Index,
1659 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001660 (DesignatedStartIndex == DesignatedEndIndex),
1661 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001662 return true;
1663
1664 // Move to the next index in the array that we'll be initializing.
1665 ++DesignatedStartIndex;
1666 ElementIndex = DesignatedStartIndex.getZExtValue();
1667 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001668
1669 // If this the first designator, our caller will continue checking
1670 // the rest of this array subobject.
1671 if (IsFirstDesignator) {
1672 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001674 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001675 return false;
1676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Douglas Gregor17bd0942009-01-28 23:36:17 +00001678 if (!FinishSubobjectInit)
1679 return false;
1680
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001681 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001682 bool prevHadError = hadError;
Anders Carlsson6cabf312010-01-23 23:23:01 +00001683 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001684 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001685 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001686 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001687}
1688
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689// Get the structured initializer list for a subobject of type
1690// @p CurrentObjectType.
1691InitListExpr *
1692InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1693 QualType CurrentObjectType,
1694 InitListExpr *StructuredList,
1695 unsigned StructuredIndex,
1696 SourceRange InitRange) {
1697 Expr *ExistingInit = 0;
1698 if (!StructuredList)
1699 ExistingInit = SyntacticToSemantic[IList];
1700 else if (StructuredIndex < StructuredList->getNumInits())
1701 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001702
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001703 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1704 return Result;
1705
1706 if (ExistingInit) {
1707 // We are creating an initializer list that initializes the
1708 // subobjects of the current object, but there was already an
1709 // initialization that completely initialized the current
1710 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001711 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001712 // struct X { int a, b; };
1713 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001714 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001715 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1716 // designated initializer re-initializes the whole
1717 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001718 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001719 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001720 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001721 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001722 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001723 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001724 << ExistingInit->getSourceRange();
1725 }
1726
Mike Stump11289f42009-09-09 15:08:12 +00001727 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001728 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1729 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001730 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001731
Douglas Gregora8a089b2010-07-13 18:40:04 +00001732 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001733
Douglas Gregor6d00c992009-03-20 23:58:33 +00001734 // Pre-allocate storage for the structured initializer list.
1735 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001736 unsigned NumInits = 0;
1737 if (!StructuredList)
1738 NumInits = IList->getNumInits();
1739 else if (Index < IList->getNumInits()) {
1740 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1741 NumInits = SubList->getNumInits();
1742 }
1743
Mike Stump11289f42009-09-09 15:08:12 +00001744 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001745 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1746 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1747 NumElements = CAType->getSize().getZExtValue();
1748 // Simple heuristic so that we don't allocate a very large
1749 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001750 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001751 NumElements = 0;
1752 }
John McCall9dd450b2009-09-21 23:43:11 +00001753 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001754 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001755 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001756 RecordDecl *RDecl = RType->getDecl();
1757 if (RDecl->isUnion())
1758 NumElements = 1;
1759 else
Mike Stump11289f42009-09-09 15:08:12 +00001760 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001761 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001762 }
1763
Douglas Gregor221c9a52009-03-21 18:13:52 +00001764 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001765 NumElements = IList->getNumInits();
1766
Ted Kremenekac034612010-04-13 23:39:13 +00001767 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001768
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001769 // Link this new initializer list into the structured initializer
1770 // lists.
1771 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001772 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773 else {
1774 Result->setSyntacticForm(IList);
1775 SyntacticToSemantic[IList] = Result;
1776 }
1777
1778 return Result;
1779}
1780
1781/// Update the initializer at index @p StructuredIndex within the
1782/// structured initializer list to the value @p expr.
1783void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1784 unsigned &StructuredIndex,
1785 Expr *expr) {
1786 // No structured initializer list to update
1787 if (!StructuredList)
1788 return;
1789
Ted Kremenekac034612010-04-13 23:39:13 +00001790 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1791 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001792 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001793 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 diag::warn_initializer_overrides)
1795 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001796 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001797 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001798 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001799 << PrevInit->getSourceRange();
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001802 ++StructuredIndex;
1803}
1804
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001805/// Check that the given Index expression is a valid array designator
1806/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001807/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001808/// and produces a reasonable diagnostic if there is a
1809/// failure. Returns true if there was an error, false otherwise. If
1810/// everything went okay, Value will receive the value of the constant
1811/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001812static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001813CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001814 SourceLocation Loc = Index->getSourceRange().getBegin();
1815
1816 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001817 if (S.VerifyIntegerConstantExpression(Index, &Value))
1818 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001819
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001820 if (Value.isSigned() && Value.isNegative())
1821 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001822 << Value.toString(10) << Index->getSourceRange();
1823
Douglas Gregor51650d32009-01-23 21:04:18 +00001824 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001825 return false;
1826}
1827
John McCalldadc5752010-08-24 06:29:42 +00001828ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001829 SourceLocation Loc,
1830 bool GNUSyntax,
1831 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001832 typedef DesignatedInitExpr::Designator ASTDesignator;
1833
1834 bool Invalid = false;
1835 llvm::SmallVector<ASTDesignator, 32> Designators;
1836 llvm::SmallVector<Expr *, 32> InitExpressions;
1837
1838 // Build designators and check array designator expressions.
1839 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1840 const Designator &D = Desig.getDesignator(Idx);
1841 switch (D.getKind()) {
1842 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001843 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001844 D.getFieldLoc()));
1845 break;
1846
1847 case Designator::ArrayDesignator: {
1848 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1849 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001850 if (!Index->isTypeDependent() &&
1851 !Index->isValueDependent() &&
1852 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001853 Invalid = true;
1854 else {
1855 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001856 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001857 D.getRBracketLoc()));
1858 InitExpressions.push_back(Index);
1859 }
1860 break;
1861 }
1862
1863 case Designator::ArrayRangeDesignator: {
1864 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1865 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1866 llvm::APSInt StartValue;
1867 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001868 bool StartDependent = StartIndex->isTypeDependent() ||
1869 StartIndex->isValueDependent();
1870 bool EndDependent = EndIndex->isTypeDependent() ||
1871 EndIndex->isValueDependent();
1872 if ((!StartDependent &&
1873 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1874 (!EndDependent &&
1875 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001876 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001877 else {
1878 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001879 if (StartDependent || EndDependent) {
1880 // Nothing to compute.
1881 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001882 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001883 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001884 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001885
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001886 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001887 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001888 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001889 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1890 Invalid = true;
1891 } else {
1892 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001893 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001894 D.getEllipsisLoc(),
1895 D.getRBracketLoc()));
1896 InitExpressions.push_back(StartIndex);
1897 InitExpressions.push_back(EndIndex);
1898 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001899 }
1900 break;
1901 }
1902 }
1903 }
1904
1905 if (Invalid || Init.isInvalid())
1906 return ExprError();
1907
1908 // Clear out the expressions within the designation.
1909 Desig.ClearExprs(*this);
1910
1911 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001912 = DesignatedInitExpr::Create(Context,
1913 Designators.data(), Designators.size(),
1914 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001915 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc124e592011-01-16 16:13:16 +00001916
1917 if (getLangOptions().CPlusPlus)
1918 Diag(DIE->getLocStart(), diag::ext_designated_init)
1919 << DIE->getSourceRange();
1920
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001921 return Owned(DIE);
1922}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001923
Douglas Gregor723796a2009-12-16 06:35:08 +00001924bool Sema::CheckInitList(const InitializedEntity &Entity,
1925 InitListExpr *&InitList, QualType &DeclType) {
1926 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001927 if (!CheckInitList.HadError())
1928 InitList = CheckInitList.getFullyStructuredList();
1929
1930 return CheckInitList.HadError();
1931}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001932
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001933//===----------------------------------------------------------------------===//
1934// Initialization entity
1935//===----------------------------------------------------------------------===//
1936
Douglas Gregor723796a2009-12-16 06:35:08 +00001937InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1938 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001939 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001940{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001941 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1942 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001943 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001944 } else {
1945 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001946 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001947 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001948}
1949
1950InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001951 CXXBaseSpecifier *Base,
1952 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001953{
1954 InitializedEntity Result;
1955 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001956 Result.Base = reinterpret_cast<uintptr_t>(Base);
1957 if (IsInheritedVirtualBase)
1958 Result.Base |= 0x01;
1959
Douglas Gregor1b303932009-12-22 15:35:07 +00001960 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001961 return Result;
1962}
1963
Douglas Gregor85dabae2009-12-16 01:38:02 +00001964DeclarationName InitializedEntity::getName() const {
1965 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001966 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001967 if (!VariableOrMember)
1968 return DeclarationName();
1969 // Fall through
1970
1971 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001972 case EK_Member:
1973 return VariableOrMember->getDeclName();
1974
1975 case EK_Result:
1976 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001977 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001978 case EK_Temporary:
1979 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001980 case EK_ArrayElement:
1981 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001982 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001983 return DeclarationName();
1984 }
1985
1986 // Silence GCC warning
1987 return DeclarationName();
1988}
1989
Douglas Gregora4b592a2009-12-19 03:01:41 +00001990DeclaratorDecl *InitializedEntity::getDecl() const {
1991 switch (getKind()) {
1992 case EK_Variable:
1993 case EK_Parameter:
1994 case EK_Member:
1995 return VariableOrMember;
1996
1997 case EK_Result:
1998 case EK_Exception:
1999 case EK_New:
2000 case EK_Temporary:
2001 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002002 case EK_ArrayElement:
2003 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002004 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002005 return 0;
2006 }
2007
2008 // Silence GCC warning
2009 return 0;
2010}
2011
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002012bool InitializedEntity::allowsNRVO() const {
2013 switch (getKind()) {
2014 case EK_Result:
2015 case EK_Exception:
2016 return LocAndNRVO.NRVO;
2017
2018 case EK_Variable:
2019 case EK_Parameter:
2020 case EK_Member:
2021 case EK_New:
2022 case EK_Temporary:
2023 case EK_Base:
2024 case EK_ArrayElement:
2025 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002026 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002027 break;
2028 }
2029
2030 return false;
2031}
2032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002033//===----------------------------------------------------------------------===//
2034// Initialization sequence
2035//===----------------------------------------------------------------------===//
2036
2037void InitializationSequence::Step::Destroy() {
2038 switch (Kind) {
2039 case SK_ResolveAddressOfOverloadedFunction:
2040 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002041 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002042 case SK_CastDerivedToBaseLValue:
2043 case SK_BindReference:
2044 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002045 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002046 case SK_UserConversion:
2047 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002048 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002049 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002050 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002051 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002052 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002053 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002054 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002055 case SK_ObjCObjectConversion:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002056 break;
2057
2058 case SK_ConversionSequence:
2059 delete ICS;
2060 }
2061}
2062
Douglas Gregor838fcc32010-03-26 20:14:36 +00002063bool InitializationSequence::isDirectReferenceBinding() const {
2064 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2065}
2066
2067bool InitializationSequence::isAmbiguous() const {
2068 if (getKind() != FailedSequence)
2069 return false;
2070
2071 switch (getFailureKind()) {
2072 case FK_TooManyInitsForReference:
2073 case FK_ArrayNeedsInitList:
2074 case FK_ArrayNeedsInitListOrStringLiteral:
2075 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2076 case FK_NonConstLValueReferenceBindingToTemporary:
2077 case FK_NonConstLValueReferenceBindingToUnrelated:
2078 case FK_RValueReferenceBindingToLValue:
2079 case FK_ReferenceInitDropsQualifiers:
2080 case FK_ReferenceInitFailed:
2081 case FK_ConversionFailed:
2082 case FK_TooManyInitsForScalar:
2083 case FK_ReferenceBindingToInitList:
2084 case FK_InitListBadDestinationType:
2085 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002086 case FK_Incomplete:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002087 return false;
2088
2089 case FK_ReferenceInitOverloadFailed:
2090 case FK_UserConversionOverloadFailed:
2091 case FK_ConstructorOverloadFailed:
2092 return FailedOverloadResult == OR_Ambiguous;
2093 }
2094
2095 return false;
2096}
2097
Douglas Gregorb33eed02010-04-16 22:09:46 +00002098bool InitializationSequence::isConstructorInitialization() const {
2099 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2100}
2101
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002102void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002103 FunctionDecl *Function,
2104 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002105 Step S;
2106 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2107 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002108 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002109 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002110 Steps.push_back(S);
2111}
2112
2113void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002114 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002115 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002116 switch (VK) {
2117 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2118 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2119 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002120 default: llvm_unreachable("No such category");
2121 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002122 S.Type = BaseType;
2123 Steps.push_back(S);
2124}
2125
2126void InitializationSequence::AddReferenceBindingStep(QualType T,
2127 bool BindingTemporary) {
2128 Step S;
2129 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2130 S.Type = T;
2131 Steps.push_back(S);
2132}
2133
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002134void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2135 Step S;
2136 S.Kind = SK_ExtraneousCopyToTemporary;
2137 S.Type = T;
2138 Steps.push_back(S);
2139}
2140
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002141void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002142 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002143 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002144 Step S;
2145 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002146 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002147 S.Function.Function = Function;
2148 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002149 Steps.push_back(S);
2150}
2151
2152void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002153 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002154 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002155 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002156 switch (VK) {
2157 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002158 S.Kind = SK_QualificationConversionRValue;
2159 break;
John McCall2536c6d2010-08-25 10:28:54 +00002160 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002161 S.Kind = SK_QualificationConversionXValue;
2162 break;
John McCall2536c6d2010-08-25 10:28:54 +00002163 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002164 S.Kind = SK_QualificationConversionLValue;
2165 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002166 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002167 S.Type = Ty;
2168 Steps.push_back(S);
2169}
2170
2171void InitializationSequence::AddConversionSequenceStep(
2172 const ImplicitConversionSequence &ICS,
2173 QualType T) {
2174 Step S;
2175 S.Kind = SK_ConversionSequence;
2176 S.Type = T;
2177 S.ICS = new ImplicitConversionSequence(ICS);
2178 Steps.push_back(S);
2179}
2180
Douglas Gregor51e77d52009-12-10 17:56:55 +00002181void InitializationSequence::AddListInitializationStep(QualType T) {
2182 Step S;
2183 S.Kind = SK_ListInitialization;
2184 S.Type = T;
2185 Steps.push_back(S);
2186}
2187
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002188void
2189InitializationSequence::AddConstructorInitializationStep(
2190 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002191 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002192 QualType T) {
2193 Step S;
2194 S.Kind = SK_ConstructorInitialization;
2195 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002196 S.Function.Function = Constructor;
2197 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002198 Steps.push_back(S);
2199}
2200
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002201void InitializationSequence::AddZeroInitializationStep(QualType T) {
2202 Step S;
2203 S.Kind = SK_ZeroInitialization;
2204 S.Type = T;
2205 Steps.push_back(S);
2206}
2207
Douglas Gregore1314a62009-12-18 05:02:21 +00002208void InitializationSequence::AddCAssignmentStep(QualType T) {
2209 Step S;
2210 S.Kind = SK_CAssignment;
2211 S.Type = T;
2212 Steps.push_back(S);
2213}
2214
Eli Friedman78275202009-12-19 08:11:05 +00002215void InitializationSequence::AddStringInitStep(QualType T) {
2216 Step S;
2217 S.Kind = SK_StringInit;
2218 S.Type = T;
2219 Steps.push_back(S);
2220}
2221
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002222void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2223 Step S;
2224 S.Kind = SK_ObjCObjectConversion;
2225 S.Type = T;
2226 Steps.push_back(S);
2227}
2228
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002229void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2230 OverloadingResult Result) {
2231 SequenceKind = FailedSequence;
2232 this->Failure = Failure;
2233 this->FailedOverloadResult = Result;
2234}
2235
2236//===----------------------------------------------------------------------===//
2237// Attempt initialization
2238//===----------------------------------------------------------------------===//
2239
2240/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002241static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002242 const InitializedEntity &Entity,
2243 const InitializationKind &Kind,
2244 InitListExpr *InitList,
2245 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002246 // FIXME: We only perform rudimentary checking of list
2247 // initializations at this point, then assume that any list
2248 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002249 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002250 // do all of the necessary checking. C++0x initializer lists will
2251 // force us to perform more checking here.
2252 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2253
Douglas Gregor1b303932009-12-22 15:35:07 +00002254 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002255
2256 // C++ [dcl.init]p13:
2257 // If T is a scalar type, then a declaration of the form
2258 //
2259 // T x = { a };
2260 //
2261 // is equivalent to
2262 //
2263 // T x = a;
2264 if (DestType->isScalarType()) {
2265 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2266 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2267 return;
2268 }
2269
2270 // Assume scalar initialization from a single value works.
2271 } else if (DestType->isAggregateType()) {
2272 // Assume aggregate initialization works.
2273 } else if (DestType->isVectorType()) {
2274 // Assume vector initialization works.
2275 } else if (DestType->isReferenceType()) {
2276 // FIXME: C++0x defines behavior for this.
2277 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2278 return;
2279 } else if (DestType->isRecordType()) {
2280 // FIXME: C++0x defines behavior for this
2281 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2282 }
2283
2284 // Add a general "list initialization" step.
2285 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002286}
2287
2288/// \brief Try a reference initialization that involves calling a conversion
2289/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002290static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2291 const InitializedEntity &Entity,
2292 const InitializationKind &Kind,
2293 Expr *Initializer,
2294 bool AllowRValues,
2295 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002296 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002297 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2298 QualType T1 = cv1T1.getUnqualifiedType();
2299 QualType cv2T2 = Initializer->getType();
2300 QualType T2 = cv2T2.getUnqualifiedType();
2301
2302 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002303 bool ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002304 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002305 T1, T2, DerivedToBase,
2306 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002307 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002308 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002309 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002310
2311 // Build the candidate set directly in the initialization sequence
2312 // structure, so that it will persist if we fail.
2313 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2314 CandidateSet.clear();
2315
2316 // Determine whether we are allowed to call explicit constructors or
2317 // explicit conversion operators.
2318 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2319
2320 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002321 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2322 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002323 // The type we're converting to is a class type. Enumerate its constructors
2324 // to see if there is a suitable conversion.
2325 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002326
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002327 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002328 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002329 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002330 NamedDecl *D = *Con;
2331 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2332
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002333 // Find the constructor (which may be a template).
2334 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002335 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002336 if (ConstructorTmpl)
2337 Constructor = cast<CXXConstructorDecl>(
2338 ConstructorTmpl->getTemplatedDecl());
2339 else
John McCalla0296f72010-03-19 07:35:19 +00002340 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002341
2342 if (!Constructor->isInvalidDecl() &&
2343 Constructor->isConvertingConstructor(AllowExplicit)) {
2344 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002345 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002346 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002347 &Initializer, 1, CandidateSet,
2348 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002349 else
John McCalla0296f72010-03-19 07:35:19 +00002350 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002351 &Initializer, 1, CandidateSet,
2352 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002353 }
2354 }
2355 }
John McCall3696dcb2010-08-17 07:23:57 +00002356 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2357 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002358
Douglas Gregor496e8b342010-05-07 19:42:26 +00002359 const RecordType *T2RecordType = 0;
2360 if ((T2RecordType = T2->getAs<RecordType>()) &&
2361 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002362 // The type we're converting from is a class type, enumerate its conversion
2363 // functions.
2364 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2365
2366 // Determine the type we are converting to. If we are allowed to
2367 // convert to an rvalue, take the type that the destination type
2368 // refers to.
2369 QualType ToType = AllowRValues? cv1T1 : DestType;
2370
John McCallad371252010-01-20 00:46:10 +00002371 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002372 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002373 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2374 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002375 NamedDecl *D = *I;
2376 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2377 if (isa<UsingShadowDecl>(D))
2378 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2379
2380 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2381 CXXConversionDecl *Conv;
2382 if (ConvTemplate)
2383 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2384 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002385 Conv = cast<CXXConversionDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002386
2387 // If the conversion function doesn't return a reference type,
2388 // it can't be considered for this conversion unless we're allowed to
2389 // consider rvalues.
2390 // FIXME: Do we need to make sure that we only consider conversion
2391 // candidates with reference-compatible results? That might be needed to
2392 // break recursion.
2393 if ((AllowExplicit || !Conv->isExplicit()) &&
2394 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2395 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002396 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002397 ActingDC, Initializer,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002398 ToType, CandidateSet);
2399 else
John McCalla0296f72010-03-19 07:35:19 +00002400 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregore6d276a2010-02-26 01:17:27 +00002401 Initializer, ToType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002402 }
2403 }
2404 }
John McCall3696dcb2010-08-17 07:23:57 +00002405 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2406 return OR_No_Viable_Function;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002407
2408 SourceLocation DeclLoc = Initializer->getLocStart();
2409
2410 // Perform overload resolution. If it fails, return the failed result.
2411 OverloadCandidateSet::iterator Best;
2412 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002413 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002414 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002415
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002416 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002417
2418 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 if (isa<CXXConversionDecl>(Function))
2420 T2 = Function->getResultType();
2421 else
2422 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002423
2424 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002425 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002426 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002427
2428 // Determine whether we need to perform derived-to-base or
2429 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002430 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002431 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002432 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002433 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002434 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002435
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002436 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002437 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002438 Sema::ReferenceCompareResult NewRefRelationship
Douglas Gregora8a089b2010-07-13 18:40:04 +00002439 = S.CompareReferenceRelationship(DeclLoc, T1,
2440 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002441 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002442 if (NewRefRelationship == Sema::Ref_Incompatible) {
2443 // If the type we've converted to is not reference-related to the
2444 // type we're looking for, then there is another conversion step
2445 // we need to perform to produce a temporary of the right type
2446 // that we'll be binding to.
2447 ImplicitConversionSequence ICS;
2448 ICS.setStandard();
2449 ICS.Standard = Best->FinalConversion;
2450 T2 = ICS.Standard.getToType(2);
2451 Sequence.AddConversionSequenceStep(ICS, T2);
2452 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002453 Sequence.AddDerivedToBaseCastStep(
2454 S.Context.getQualifiedType(T1,
2455 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002456 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002457 else if (NewObjCConversion)
2458 Sequence.AddObjCObjectConversionStep(
2459 S.Context.getQualifiedType(T1,
2460 T2.getNonReferenceType().getQualifiers()));
2461
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002462 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002463 Sequence.AddQualificationConversionStep(cv1T1, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464
2465 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2466 return OR_Success;
2467}
2468
Sebastian Redld92badf2010-06-30 18:13:39 +00002469/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002470static void TryReferenceInitialization(Sema &S,
2471 const InitializedEntity &Entity,
2472 const InitializationKind &Kind,
2473 Expr *Initializer,
2474 InitializationSequence &Sequence) {
2475 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002476
Douglas Gregor1b303932009-12-22 15:35:07 +00002477 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002479 Qualifiers T1Quals;
2480 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002481 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002482 Qualifiers T2Quals;
2483 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002484 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002486 // If the initializer is the address of an overloaded function, try
2487 // to resolve the overloaded function. If all goes well, T2 is the
2488 // type of the resulting function.
2489 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002490 DeclAccessPair Found;
Douglas Gregorbcd62532010-11-08 15:20:28 +00002491 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2492 T1,
2493 false,
2494 Found)) {
2495 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2496 cv2T2 = Fn->getType();
2497 T2 = cv2T2.getUnqualifiedType();
2498 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002499 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2500 return;
2501 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002502 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002503
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002504 // Compute some basic properties of the types and the initializer.
2505 bool isLValueRef = DestType->isLValueReferenceType();
2506 bool isRValueRef = !isLValueRef;
2507 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002508 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002509 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002510 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002511 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2512 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002513
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002514 // C++0x [dcl.init.ref]p5:
2515 // A reference to type "cv1 T1" is initialized by an expression of type
2516 // "cv2 T2" as follows:
2517 //
2518 // - If the reference is an lvalue reference and the initializer
2519 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002520 // Note the analogous bullet points for rvlaue refs to functions. Because
2521 // there are no function rvalues in C++, rvalue refs to functions are treated
2522 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002523 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002524 bool T1Function = T1->isFunctionType();
2525 if (isLValueRef || T1Function) {
2526 if (InitCategory.isLValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002527 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2528 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2529 // reference-compatible with "cv2 T2," or
2530 //
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002531 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002533 // can occur. However, we do pay attention to whether it is a bit-field
2534 // to decide whether we're actually binding to a temporary created from
2535 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002536 if (DerivedToBase)
2537 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002538 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002539 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002540 else if (ObjCConversion)
2541 Sequence.AddObjCObjectConversionStep(
2542 S.Context.getQualifiedType(T1, T2Quals));
2543
Chandler Carruth04bdce62010-01-12 20:32:25 +00002544 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002545 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002546 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002547 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002548 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002549 return;
2550 }
2551
2552 // - has a class type (i.e., T2 is a class type), where T1 is not
2553 // reference-related to T2, and can be implicitly converted to an
2554 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2555 // with "cv3 T3" (this conversion is selected by enumerating the
2556 // applicable conversion functions (13.3.1.6) and choosing the best
2557 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002558 // If we have an rvalue ref to function type here, the rhs must be
2559 // an rvalue.
2560 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2561 (isLValueRef || InitCategory.isRValue())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002562 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2563 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002564 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002565 Sequence);
2566 if (ConvOvlResult == OR_Success)
2567 return;
John McCall0d1da222010-01-12 00:44:57 +00002568 if (ConvOvlResult != OR_No_Viable_Function) {
2569 Sequence.SetOverloadFailure(
2570 InitializationSequence::FK_ReferenceInitOverloadFailed,
2571 ConvOvlResult);
2572 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002573 }
2574 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002575
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002576 // - Otherwise, the reference shall be an lvalue reference to a
2577 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002578 // shall be an rvalue reference.
Douglas Gregord1e08642010-01-29 19:39:15 +00002579 if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
Sebastian Redld92badf2010-06-30 18:13:39 +00002580 (isRValueRef && InitCategory.isRValue()))) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002581 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2582 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2583 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002584 Sequence.SetOverloadFailure(
2585 InitializationSequence::FK_ReferenceInitOverloadFailed,
2586 ConvOvlResult);
2587 else if (isLValueRef)
Sebastian Redld92badf2010-06-30 18:13:39 +00002588 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002589 ? (RefRelationship == Sema::Ref_Related
2590 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2591 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2592 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2593 else
2594 Sequence.SetFailed(
2595 InitializationSequence::FK_RValueReferenceBindingToLValue);
Sebastian Redld92badf2010-06-30 18:13:39 +00002596
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002597 return;
2598 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002599
2600 // - [If T1 is not a function type], if T2 is a class type and
2601 if (!T1Function && T2->isRecordType()) {
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002602 bool isXValue = InitCategory.isXValue();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002603 // - the initializer expression is an rvalue and "cv1 T1" is
2604 // reference-compatible with "cv2 T2", or
Sebastian Redld92badf2010-06-30 18:13:39 +00002605 if (InitCategory.isRValue() &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002606 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002607 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2608 // compiler the freedom to perform a copy here or bind to the
2609 // object, while C++0x requires that we bind directly to the
2610 // object. Hence, we always bind to the object without making an
2611 // extra copy. However, in C++03 requires that we check for the
2612 // presence of a suitable copy constructor:
2613 //
2614 // The constructor that would be used to make the copy shall
2615 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002616 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002617 Sequence.AddExtraneousCopyToTemporary(cv2T2);
2618
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002619 if (DerivedToBase)
2620 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002621 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002622 isXValue ? VK_XValue : VK_RValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002623 else if (ObjCConversion)
2624 Sequence.AddObjCObjectConversionStep(
2625 S.Context.getQualifiedType(T1, T2Quals));
2626
Chandler Carruth04bdce62010-01-12 20:32:25 +00002627 if (T1Quals != T2Quals)
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002628 Sequence.AddQualificationConversionStep(cv1T1,
John McCall2536c6d2010-08-25 10:28:54 +00002629 isXValue ? VK_XValue : VK_RValue);
Sebastian Redlae8cbb72010-07-26 17:52:21 +00002630 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/!isXValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002631 return;
2632 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002633
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002634 // - T1 is not reference-related to T2 and the initializer expression
2635 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2636 // conversion is selected by enumerating the applicable conversion
2637 // functions (13.3.1.6) and choosing the best one through overload
2638 // resolution (13.3)),
2639 if (RefRelationship == Sema::Ref_Incompatible) {
2640 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2641 Kind, Initializer,
2642 /*AllowRValues=*/true,
2643 Sequence);
2644 if (ConvOvlResult)
2645 Sequence.SetOverloadFailure(
2646 InitializationSequence::FK_ReferenceInitOverloadFailed,
2647 ConvOvlResult);
2648
2649 return;
2650 }
2651
2652 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2653 return;
2654 }
2655
2656 // - If the initializer expression is an rvalue, with T2 an array type,
2657 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2658 // is bound to the object represented by the rvalue (see 3.10).
2659 // FIXME: How can an array type be reference-compatible with anything?
2660 // Don't we mean the element types of T1 and T2?
2661
2662 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2663 // from the initializer expression using the rules for a non-reference
2664 // copy initialization (8.5). The reference is then bound to the
2665 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002666
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002667 // Determine whether we are allowed to call explicit constructors or
2668 // explicit conversion operators.
2669 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002670
2671 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2672
2673 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2674 /*SuppressUserConversions*/ false,
2675 AllowExplicit,
2676 /*FIXME:InOverloadResolution=*/false)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677 // FIXME: Use the conversion function set stored in ICS to turn
2678 // this into an overloading ambiguity diagnostic. However, we need
2679 // to keep that set as an OverloadCandidateSet rather than as some
2680 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002681 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2682 Sequence.SetOverloadFailure(
2683 InitializationSequence::FK_ReferenceInitOverloadFailed,
2684 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002685 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2686 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002687 else
2688 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002689 return;
2690 }
2691
2692 // [...] If T1 is reference-related to T2, cv1 must be the
2693 // same cv-qualification as, or greater cv-qualification
2694 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002695 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2696 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002697 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002698 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002699 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2700 return;
2701 }
2702
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002703 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2704 return;
2705}
2706
2707/// \brief Attempt character array initialization from a string literal
2708/// (C++ [dcl.init.string], C99 6.7.8).
2709static void TryStringLiteralInitialization(Sema &S,
2710 const InitializedEntity &Entity,
2711 const InitializationKind &Kind,
2712 Expr *Initializer,
2713 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002714 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002715 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002716}
2717
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002718/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2719/// enumerates the constructors of the initialized entity and performs overload
2720/// resolution to select the best.
2721static void TryConstructorInitialization(Sema &S,
2722 const InitializedEntity &Entity,
2723 const InitializationKind &Kind,
2724 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002725 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002727 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002728
2729 // Build the candidate set directly in the initialization sequence
2730 // structure, so that it will persist if we fail.
2731 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2732 CandidateSet.clear();
2733
2734 // Determine whether we are allowed to call explicit constructors or
2735 // explicit conversion operators.
2736 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2737 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002738 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002739
2740 // The type we're constructing needs to be complete.
2741 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002742 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002743 return;
2744 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002745
2746 // The type we're converting to is a class type. Enumerate its constructors
2747 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002748 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2749 assert(DestRecordType && "Constructor initialization requires record type");
2750 CXXRecordDecl *DestRecordDecl
2751 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2752
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002753 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002754 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002755 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002756 NamedDecl *D = *Con;
2757 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002758 bool SuppressUserConversions = false;
2759
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002760 // Find the constructor (which may be a template).
2761 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002762 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002763 if (ConstructorTmpl)
2764 Constructor = cast<CXXConstructorDecl>(
2765 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002766 else {
John McCalla0296f72010-03-19 07:35:19 +00002767 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002768
2769 // If we're performing copy initialization using a copy constructor, we
2770 // suppress user-defined conversions on the arguments.
2771 // FIXME: Move constructors?
2772 if (Kind.getKind() == InitializationKind::IK_Copy &&
2773 Constructor->isCopyConstructor())
2774 SuppressUserConversions = true;
2775 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002776
2777 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002778 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002779 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002780 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002781 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002782 Args, NumArgs, CandidateSet,
2783 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002784 else
John McCalla0296f72010-03-19 07:35:19 +00002785 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002786 Args, NumArgs, CandidateSet,
2787 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002788 }
2789 }
2790
2791 SourceLocation DeclLoc = Kind.getLocation();
2792
2793 // Perform overload resolution. If it fails, return the failed result.
2794 OverloadCandidateSet::iterator Best;
2795 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002796 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002797 Sequence.SetOverloadFailure(
2798 InitializationSequence::FK_ConstructorOverloadFailed,
2799 Result);
2800 return;
2801 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002802
2803 // C++0x [dcl.init]p6:
2804 // If a program calls for the default initialization of an object
2805 // of a const-qualified type T, T shall be a class type with a
2806 // user-provided default constructor.
2807 if (Kind.getKind() == InitializationKind::IK_Default &&
2808 Entity.getType().isConstQualified() &&
2809 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2810 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2811 return;
2812 }
2813
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002814 // Add the constructor initialization step. Any cv-qualification conversion is
2815 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002816 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002817 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002818 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002819 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002820}
2821
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002822/// \brief Attempt value initialization (C++ [dcl.init]p7).
2823static void TryValueInitialization(Sema &S,
2824 const InitializedEntity &Entity,
2825 const InitializationKind &Kind,
2826 InitializationSequence &Sequence) {
2827 // C++ [dcl.init]p5:
2828 //
2829 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002830 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002831
2832 // -- if T is an array type, then each element is value-initialized;
2833 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2834 T = AT->getElementType();
2835
2836 if (const RecordType *RT = T->getAs<RecordType>()) {
2837 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2838 // -- if T is a class type (clause 9) with a user-declared
2839 // constructor (12.1), then the default constructor for T is
2840 // called (and the initialization is ill-formed if T has no
2841 // accessible default constructor);
2842 //
2843 // FIXME: we really want to refer to a single subobject of the array,
2844 // but Entity doesn't have a way to capture that (yet).
2845 if (ClassDecl->hasUserDeclaredConstructor())
2846 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2847
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002848 // -- if T is a (possibly cv-qualified) non-union class type
2849 // without a user-provided constructor, then the object is
2850 // zero-initialized and, if T’s implicitly-declared default
2851 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002852 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002853 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002854 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002855 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2856 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002857 }
2858 }
2859
Douglas Gregor1b303932009-12-22 15:35:07 +00002860 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002861 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2862}
2863
Douglas Gregor85dabae2009-12-16 01:38:02 +00002864/// \brief Attempt default initialization (C++ [dcl.init]p6).
2865static void TryDefaultInitialization(Sema &S,
2866 const InitializedEntity &Entity,
2867 const InitializationKind &Kind,
2868 InitializationSequence &Sequence) {
2869 assert(Kind.getKind() == InitializationKind::IK_Default);
2870
2871 // C++ [dcl.init]p6:
2872 // To default-initialize an object of type T means:
2873 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002874 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002875 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2876 DestType = Array->getElementType();
2877
2878 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2879 // constructor for T is called (and the initialization is ill-formed if
2880 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002881 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002882 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2883 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002884 }
2885
2886 // - otherwise, no initialization is performed.
2887 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2888
2889 // If a program calls for the default initialization of an object of
2890 // a const-qualified type T, T shall be a class type with a user-provided
2891 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002892 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002893 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2894}
2895
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002896/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2897/// which enumerates all conversion functions and performs overload resolution
2898/// to select the best.
2899static void TryUserDefinedConversion(Sema &S,
2900 const InitializedEntity &Entity,
2901 const InitializationKind &Kind,
2902 Expr *Initializer,
2903 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002904 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2905
Douglas Gregor1b303932009-12-22 15:35:07 +00002906 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002907 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2908 QualType SourceType = Initializer->getType();
2909 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2910 "Must have a class type to perform a user-defined conversion");
2911
2912 // Build the candidate set directly in the initialization sequence
2913 // structure, so that it will persist if we fail.
2914 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2915 CandidateSet.clear();
2916
2917 // Determine whether we are allowed to call explicit constructors or
2918 // explicit conversion operators.
2919 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2920
2921 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2922 // The type we're converting to is a class type. Enumerate its constructors
2923 // to see if there is a suitable conversion.
2924 CXXRecordDecl *DestRecordDecl
2925 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2926
Douglas Gregord9848152010-04-26 14:36:57 +00002927 // Try to complete the type we're converting to.
2928 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002929 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002930 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002931 Con != ConEnd; ++Con) {
2932 NamedDecl *D = *Con;
2933 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002934
Douglas Gregord9848152010-04-26 14:36:57 +00002935 // Find the constructor (which may be a template).
2936 CXXConstructorDecl *Constructor = 0;
2937 FunctionTemplateDecl *ConstructorTmpl
2938 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002939 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002940 Constructor = cast<CXXConstructorDecl>(
2941 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00002942 else
Douglas Gregord9848152010-04-26 14:36:57 +00002943 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord9848152010-04-26 14:36:57 +00002944
2945 if (!Constructor->isInvalidDecl() &&
2946 Constructor->isConvertingConstructor(AllowExplicit)) {
2947 if (ConstructorTmpl)
2948 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2949 /*ExplicitArgs*/ 0,
2950 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002951 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002952 else
2953 S.AddOverloadCandidate(Constructor, FoundDecl,
2954 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00002955 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00002956 }
2957 }
2958 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002959 }
Eli Friedman78275202009-12-19 08:11:05 +00002960
2961 SourceLocation DeclLoc = Initializer->getLocStart();
2962
Douglas Gregor540c3b02009-12-14 17:27:33 +00002963 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2964 // The type we're converting from is a class type, enumerate its conversion
2965 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002966
Eli Friedman4afe9a32009-12-20 22:12:03 +00002967 // We can only enumerate the conversion functions for a complete type; if
2968 // the type isn't complete, simply skip this step.
2969 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2970 CXXRecordDecl *SourceRecordDecl
2971 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002972
John McCallad371252010-01-20 00:46:10 +00002973 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002974 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002975 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002976 E = Conversions->end();
2977 I != E; ++I) {
2978 NamedDecl *D = *I;
2979 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2980 if (isa<UsingShadowDecl>(D))
2981 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2982
2983 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2984 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002985 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002986 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002987 else
John McCallda4458e2010-03-31 01:36:47 +00002988 Conv = cast<CXXConversionDecl>(D);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002989
2990 if (AllowExplicit || !Conv->isExplicit()) {
2991 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002992 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002993 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00002994 CandidateSet);
2995 else
John McCalla0296f72010-03-19 07:35:19 +00002996 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00002997 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00002998 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002999 }
3000 }
3001 }
3002
Douglas Gregor540c3b02009-12-14 17:27:33 +00003003 // Perform overload resolution. If it fails, return the failed result.
3004 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003005 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003006 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003007 Sequence.SetOverloadFailure(
3008 InitializationSequence::FK_UserConversionOverloadFailed,
3009 Result);
3010 return;
3011 }
John McCall0d1da222010-01-12 00:44:57 +00003012
Douglas Gregor540c3b02009-12-14 17:27:33 +00003013 FunctionDecl *Function = Best->Function;
3014
3015 if (isa<CXXConstructorDecl>(Function)) {
3016 // Add the user-defined conversion step. Any cv-qualification conversion is
3017 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003018 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003019 return;
3020 }
3021
3022 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003023 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003024 if (ConvType->getAs<RecordType>()) {
3025 // If we're converting to a class type, there may be an copy if
3026 // the resulting temporary object (possible to create an object of
3027 // a base class type). That copy is not a separate conversion, so
3028 // we just make a note of the actual destination type (possibly a
3029 // base class of the type returned by the conversion function) and
3030 // let the user-defined conversion step handle the conversion.
3031 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3032 return;
3033 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003034
Douglas Gregor5ab11652010-04-17 22:01:05 +00003035 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
3036
3037 // If the conversion following the call to the conversion function
3038 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003039 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3040 Best->FinalConversion.Third) {
3041 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003042 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003043 ICS.Standard = Best->FinalConversion;
3044 Sequence.AddConversionSequenceStep(ICS, DestType);
3045 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003046}
3047
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003048InitializationSequence::InitializationSequence(Sema &S,
3049 const InitializedEntity &Entity,
3050 const InitializationKind &Kind,
3051 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003052 unsigned NumArgs)
3053 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003054 ASTContext &Context = S.Context;
3055
3056 // C++0x [dcl.init]p16:
3057 // The semantics of initializers are as follows. The destination type is
3058 // the type of the object or reference being initialized and the source
3059 // type is the type of the initializer expression. The source type is not
3060 // defined when the initializer is a braced-init-list or when it is a
3061 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003062 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003063
3064 if (DestType->isDependentType() ||
3065 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3066 SequenceKind = DependentSequence;
3067 return;
3068 }
3069
John McCalled75c092010-12-07 22:54:16 +00003070 for (unsigned I = 0; I != NumArgs; ++I)
3071 if (Args[I]->getObjectKind() == OK_ObjCProperty)
3072 S.ConvertPropertyForRValue(Args[I]);
3073
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003074 QualType SourceType;
3075 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003076 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003077 Initializer = Args[0];
3078 if (!isa<InitListExpr>(Initializer))
3079 SourceType = Initializer->getType();
3080 }
3081
3082 // - If the initializer is a braced-init-list, the object is
3083 // list-initialized (8.5.4).
3084 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3085 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003086 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003087 }
3088
3089 // - If the destination type is a reference type, see 8.5.3.
3090 if (DestType->isReferenceType()) {
3091 // C++0x [dcl.init.ref]p1:
3092 // A variable declared to be a T& or T&&, that is, "reference to type T"
3093 // (8.3.2), shall be initialized by an object, or function, of type T or
3094 // by an object that can be converted into a T.
3095 // (Therefore, multiple arguments are not permitted.)
3096 if (NumArgs != 1)
3097 SetFailed(FK_TooManyInitsForReference);
3098 else
3099 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3100 return;
3101 }
3102
3103 // - If the destination type is an array of characters, an array of
3104 // char16_t, an array of char32_t, or an array of wchar_t, and the
3105 // initializer is a string literal, see 8.5.2.
3106 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3107 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3108 return;
3109 }
3110
3111 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003112 if (Kind.getKind() == InitializationKind::IK_Value ||
3113 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003114 TryValueInitialization(S, Entity, Kind, *this);
3115 return;
3116 }
3117
Douglas Gregor85dabae2009-12-16 01:38:02 +00003118 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003119 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003120 TryDefaultInitialization(S, Entity, Kind, *this);
3121 return;
3122 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003123
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003124 // - Otherwise, if the destination type is an array, the program is
3125 // ill-formed.
3126 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3127 if (AT->getElementType()->isAnyCharacterType())
3128 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3129 else
3130 SetFailed(FK_ArrayNeedsInitList);
3131
3132 return;
3133 }
Eli Friedman78275202009-12-19 08:11:05 +00003134
3135 // Handle initialization in C
3136 if (!S.getLangOptions().CPlusPlus) {
3137 setSequenceKind(CAssignment);
3138 AddCAssignmentStep(DestType);
3139 return;
3140 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003141
3142 // - If the destination type is a (possibly cv-qualified) class type:
3143 if (DestType->isRecordType()) {
3144 // - If the initialization is direct-initialization, or if it is
3145 // copy-initialization where the cv-unqualified version of the
3146 // source type is the same class as, or a derived class of, the
3147 // class of the destination, constructors are considered. [...]
3148 if (Kind.getKind() == InitializationKind::IK_Direct ||
3149 (Kind.getKind() == InitializationKind::IK_Copy &&
3150 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3151 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003152 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003153 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003154 // - Otherwise (i.e., for the remaining copy-initialization cases),
3155 // user-defined conversion sequences that can convert from the source
3156 // type to the destination type or (when a conversion function is
3157 // used) to a derived class thereof are enumerated as described in
3158 // 13.3.1.4, and the best one is chosen through overload resolution
3159 // (13.3).
3160 else
3161 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3162 return;
3163 }
3164
Douglas Gregor85dabae2009-12-16 01:38:02 +00003165 if (NumArgs > 1) {
3166 SetFailed(FK_TooManyInitsForScalar);
3167 return;
3168 }
3169 assert(NumArgs == 1 && "Zero-argument case handled above");
3170
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003171 // - Otherwise, if the source type is a (possibly cv-qualified) class
3172 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003173 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003174 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3175 return;
3176 }
3177
3178 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003179 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003180 // conversions (Clause 4) will be used, if necessary, to convert the
3181 // initializer expression to the cv-unqualified version of the
3182 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003183 if (S.TryImplicitConversion(*this, Entity, Initializer,
3184 /*SuppressUserConversions*/ true,
3185 /*AllowExplicitConversions*/ false,
3186 /*InOverloadResolution*/ false))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003187 {
John McCalled75c092010-12-07 22:54:16 +00003188 if (Initializer->getType() == Context.OverloadTy)
Douglas Gregore81f58e2010-11-08 03:40:48 +00003189 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3190 else
3191 SetFailed(InitializationSequence::FK_ConversionFailed);
3192 }
John McCallec6f4e92010-06-04 02:29:22 +00003193 else
3194 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003195}
3196
3197InitializationSequence::~InitializationSequence() {
3198 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3199 StepEnd = Steps.end();
3200 Step != StepEnd; ++Step)
3201 Step->Destroy();
3202}
3203
3204//===----------------------------------------------------------------------===//
3205// Perform initialization
3206//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003207static Sema::AssignmentAction
3208getAssignmentAction(const InitializedEntity &Entity) {
3209 switch(Entity.getKind()) {
3210 case InitializedEntity::EK_Variable:
3211 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003212 case InitializedEntity::EK_Exception:
3213 case InitializedEntity::EK_Base:
Douglas Gregore1314a62009-12-18 05:02:21 +00003214 return Sema::AA_Initializing;
3215
3216 case InitializedEntity::EK_Parameter:
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003217 if (Entity.getDecl() &&
3218 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3219 return Sema::AA_Sending;
3220
Douglas Gregore1314a62009-12-18 05:02:21 +00003221 return Sema::AA_Passing;
3222
3223 case InitializedEntity::EK_Result:
3224 return Sema::AA_Returning;
3225
Douglas Gregore1314a62009-12-18 05:02:21 +00003226 case InitializedEntity::EK_Temporary:
3227 // FIXME: Can we tell apart casting vs. converting?
3228 return Sema::AA_Casting;
3229
3230 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003231 case InitializedEntity::EK_ArrayElement:
3232 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003233 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003234 return Sema::AA_Initializing;
3235 }
3236
3237 return Sema::AA_Converting;
3238}
3239
Douglas Gregor95562572010-04-24 23:45:46 +00003240/// \brief Whether we should binding a created object as a temporary when
3241/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003242static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003243 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003244 case InitializedEntity::EK_ArrayElement:
3245 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003246 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003247 case InitializedEntity::EK_New:
3248 case InitializedEntity::EK_Variable:
3249 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003250 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003251 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003252 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003253 return false;
3254
3255 case InitializedEntity::EK_Parameter:
3256 case InitializedEntity::EK_Temporary:
3257 return true;
3258 }
3259
3260 llvm_unreachable("missed an InitializedEntity kind?");
3261}
3262
Douglas Gregor95562572010-04-24 23:45:46 +00003263/// \brief Whether the given entity, when initialized with an object
3264/// created for that initialization, requires destruction.
3265static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3266 switch (Entity.getKind()) {
3267 case InitializedEntity::EK_Member:
3268 case InitializedEntity::EK_Result:
3269 case InitializedEntity::EK_New:
3270 case InitializedEntity::EK_Base:
3271 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003272 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003273 return false;
3274
3275 case InitializedEntity::EK_Variable:
3276 case InitializedEntity::EK_Parameter:
3277 case InitializedEntity::EK_Temporary:
3278 case InitializedEntity::EK_ArrayElement:
3279 case InitializedEntity::EK_Exception:
3280 return true;
3281 }
3282
3283 llvm_unreachable("missed an InitializedEntity kind?");
3284}
3285
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003286/// \brief Make a (potentially elidable) temporary copy of the object
3287/// provided by the given initializer by calling the appropriate copy
3288/// constructor.
3289///
3290/// \param S The Sema object used for type-checking.
3291///
3292/// \param T The type of the temporary object, which must either by
3293/// the type of the initializer expression or a superclass thereof.
3294///
3295/// \param Enter The entity being initialized.
3296///
3297/// \param CurInit The initializer expression.
3298///
3299/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3300/// is permitted in C++03 (but not C++0x) when binding a reference to
3301/// an rvalue.
3302///
3303/// \returns An expression that copies the initializer expression into
3304/// a temporary object, or an error expression if a copy could not be
3305/// created.
John McCalldadc5752010-08-24 06:29:42 +00003306static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003307 QualType T,
3308 const InitializedEntity &Entity,
3309 ExprResult CurInit,
3310 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003311 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003312 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003313 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003314 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003315 Class = cast<CXXRecordDecl>(Record->getDecl());
3316 if (!Class)
3317 return move(CurInit);
3318
3319 // C++0x [class.copy]p34:
3320 // When certain criteria are met, an implementation is allowed to
3321 // omit the copy/move construction of a class object, even if the
3322 // copy/move constructor and/or destructor for the object have
3323 // side effects. [...]
3324 // - when a temporary class object that has not been bound to a
3325 // reference (12.2) would be copied/moved to a class object
3326 // with the same cv-unqualified type, the copy/move operation
3327 // can be omitted by constructing the temporary object
3328 // directly into the target of the omitted copy/move
3329 //
3330 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003331 // elision for return statements and throw expressions are handled as part
3332 // of constructor initialization, while copy elision for exception handlers
3333 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003334 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003335 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003336 switch (Entity.getKind()) {
3337 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003338 Loc = Entity.getReturnLoc();
3339 break;
3340
3341 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003342 Loc = Entity.getThrowLoc();
3343 break;
3344
3345 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003346 Loc = Entity.getDecl()->getLocation();
3347 break;
3348
Anders Carlsson0bd52402010-01-24 00:19:41 +00003349 case InitializedEntity::EK_ArrayElement:
3350 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003351 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003352 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003353 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003354 case InitializedEntity::EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003355 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003356 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003357 Loc = CurInitExpr->getLocStart();
3358 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003359 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003360
3361 // Make sure that the type we are copying is complete.
3362 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3363 return move(CurInit);
3364
Douglas Gregore1314a62009-12-18 05:02:21 +00003365 // Perform overload resolution using the class's copy constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003366 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003367 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003368 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003369 Con != ConEnd; ++Con) {
Douglas Gregorcbd07102010-11-12 03:34:06 +00003370 // Only consider copy constructors and constructor templates. Per
3371 // C++0x [dcl.init]p16, second bullet to class types, this
3372 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003373 CXXConstructorDecl *Constructor = 0;
3374
3375 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
3376 // Handle copy constructors, only.
3377 if (!Constructor || Constructor->isInvalidDecl() ||
3378 !Constructor->isCopyConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003379 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003380 continue;
3381
3382 DeclAccessPair FoundDecl
3383 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3384 S.AddOverloadCandidate(Constructor, FoundDecl,
3385 &CurInitExpr, 1, CandidateSet);
3386 continue;
3387 }
3388
3389 // Handle constructor templates.
3390 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3391 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003392 continue;
John McCalla0296f72010-03-19 07:35:19 +00003393
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003394 Constructor = cast<CXXConstructorDecl>(
3395 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003396 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003397 continue;
3398
3399 // FIXME: Do we need to limit this to copy-constructor-like
3400 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003401 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003402 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3403 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3404 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003405 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003406
3407 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00003408 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003409 case OR_Success:
3410 break;
3411
3412 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003413 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3414 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3415 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003416 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003417 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003418 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003419 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003420 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003421 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003422
3423 case OR_Ambiguous:
3424 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003425 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003426 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003427 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003428 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003429
3430 case OR_Deleted:
3431 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003432 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003433 << CurInitExpr->getSourceRange();
3434 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3435 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003436 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003437 }
3438
Douglas Gregor5ab11652010-04-17 22:01:05 +00003439 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003440 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003441 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003442
Anders Carlssona01874b2010-04-21 18:47:17 +00003443 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003444 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003445
3446 if (IsExtraneousCopy) {
3447 // If this is a totally extraneous copy for C++03 reference
3448 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003449 // expression. We don't generate an (elided) copy operation here
3450 // because doing so would require us to pass down a flag to avoid
3451 // infinite recursion, where each step adds another extraneous,
3452 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003453
Douglas Gregor30b52772010-04-18 07:57:34 +00003454 // Instantiate the default arguments of any extra parameters in
3455 // the selected copy constructor, as if we were going to create a
3456 // proper call to the copy constructor.
3457 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3458 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3459 if (S.RequireCompleteType(Loc, Parm->getType(),
3460 S.PDiag(diag::err_call_incomplete_argument)))
3461 break;
3462
3463 // Build the default argument expression; we don't actually care
3464 // if this succeeds or not, because this routine will complain
3465 // if there was a problem.
3466 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3467 }
3468
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003469 return S.Owned(CurInitExpr);
3470 }
Douglas Gregor5ab11652010-04-17 22:01:05 +00003471
3472 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003473 // constructor call (we might have derived-to-base conversions, or
3474 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003475 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003476 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003477 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003478
Douglas Gregord0ace022010-04-25 00:55:24 +00003479 // Actually perform the constructor call.
3480 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003481 move_arg(ConstructorArgs),
3482 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003483 CXXConstructExpr::CK_Complete,
3484 SourceRange());
Douglas Gregord0ace022010-04-25 00:55:24 +00003485
3486 // If we're supposed to bind temporaries, do so.
3487 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3488 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3489 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003490}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003491
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003492void InitializationSequence::PrintInitLocationNote(Sema &S,
3493 const InitializedEntity &Entity) {
3494 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3495 if (Entity.getDecl()->getLocation().isInvalid())
3496 return;
3497
3498 if (Entity.getDecl()->getDeclName())
3499 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3500 << Entity.getDecl()->getDeclName();
3501 else
3502 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3503 }
3504}
3505
John McCalldadc5752010-08-24 06:29:42 +00003506ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507InitializationSequence::Perform(Sema &S,
3508 const InitializedEntity &Entity,
3509 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003510 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003511 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003512 if (SequenceKind == FailedSequence) {
3513 unsigned NumArgs = Args.size();
3514 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003515 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003516 }
3517
3518 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003519 // If the declaration is a non-dependent, incomplete array type
3520 // that has an initializer, then its type will be completed once
3521 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003522 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003523 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003524 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003525 if (const IncompleteArrayType *ArrayT
3526 = S.Context.getAsIncompleteArrayType(DeclType)) {
3527 // FIXME: We don't currently have the ability to accurately
3528 // compute the length of an initializer list without
3529 // performing full type-checking of the initializer list
3530 // (since we have to determine where braces are implicitly
3531 // introduced and such). So, we fall back to making the array
3532 // type a dependently-sized array type with no specified
3533 // bound.
3534 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3535 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003536
Douglas Gregor51e77d52009-12-10 17:56:55 +00003537 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003538 if (DeclaratorDecl *DD = Entity.getDecl()) {
3539 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3540 TypeLoc TL = TInfo->getTypeLoc();
3541 if (IncompleteArrayTypeLoc *ArrayLoc
3542 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3543 Brackets = ArrayLoc->getBracketsRange();
3544 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003545 }
3546
3547 *ResultType
3548 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3549 /*NumElts=*/0,
3550 ArrayT->getSizeModifier(),
3551 ArrayT->getIndexTypeCVRQualifiers(),
3552 Brackets);
3553 }
3554
3555 }
3556 }
3557
Eli Friedmana553d4a2009-12-22 02:35:53 +00003558 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003559 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003560
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003561 if (Args.size() == 0)
3562 return S.Owned((Expr *)0);
3563
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003564 unsigned NumArgs = Args.size();
3565 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3566 SourceLocation(),
3567 (Expr **)Args.release(),
3568 NumArgs,
3569 SourceLocation()));
3570 }
3571
Douglas Gregor85dabae2009-12-16 01:38:02 +00003572 if (SequenceKind == NoInitialization)
3573 return S.Owned((Expr *)0);
3574
Douglas Gregor1b303932009-12-22 15:35:07 +00003575 QualType DestType = Entity.getType().getNonReferenceType();
3576 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003577 // the same as Entity.getDecl()->getType() in cases involving type merging,
3578 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003579 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003580 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003581 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582
John McCalldadc5752010-08-24 06:29:42 +00003583 ExprResult CurInit = S.Owned((Expr *)0);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003584
3585 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3586
3587 // For initialization steps that start with a single initializer,
3588 // grab the only argument out the Args and place it into the "current"
3589 // initializer.
3590 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003591 case SK_ResolveAddressOfOverloadedFunction:
3592 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003593 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003594 case SK_CastDerivedToBaseLValue:
3595 case SK_BindReference:
3596 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003597 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003598 case SK_UserConversion:
3599 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003600 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003601 case SK_QualificationConversionRValue:
3602 case SK_ConversionSequence:
3603 case SK_ListInitialization:
3604 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003605 case SK_StringInit:
John McCall34376a62010-12-04 03:47:34 +00003606 case SK_ObjCObjectConversion: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003607 assert(Args.size() == 1);
John McCall34376a62010-12-04 03:47:34 +00003608 Expr *CurInitExpr = Args.get()[0];
3609 if (!CurInitExpr) return ExprError();
3610
3611 // Read from a property when initializing something with it.
3612 if (CurInitExpr->getObjectKind() == OK_ObjCProperty)
3613 S.ConvertPropertyForRValue(CurInitExpr);
3614
3615 CurInit = ExprResult(CurInitExpr);
Douglas Gregore1314a62009-12-18 05:02:21 +00003616 break;
John McCall34376a62010-12-04 03:47:34 +00003617 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003618
3619 case SK_ConstructorInitialization:
3620 case SK_ZeroInitialization:
3621 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003622 }
3623
3624 // Walk through the computed steps for the initialization sequence,
3625 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003626 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627 for (step_iterator Step = step_begin(), StepEnd = step_end();
3628 Step != StepEnd; ++Step) {
3629 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003630 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003631
John McCall34376a62010-12-04 03:47:34 +00003632 Expr *CurInitExpr = CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003633 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003634
3635 switch (Step->Kind) {
3636 case SK_ResolveAddressOfOverloadedFunction:
3637 // Overload resolution determined which function invoke; update the
3638 // initializer to reflect that choice.
John McCall16df1e52010-03-30 21:47:33 +00003639 S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003640 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003641 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003642 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003643 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003644 break;
3645
3646 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003647 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 case SK_CastDerivedToBaseLValue: {
3649 // We have a derived-to-base cast that produces either an rvalue or an
3650 // lvalue. Perform that cast.
3651
John McCallcf142162010-08-07 06:22:56 +00003652 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003653
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003654 // Casts to inaccessible base classes are allowed with C-style casts.
3655 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3656 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3657 CurInitExpr->getLocStart(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003658 CurInitExpr->getSourceRange(),
3659 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003660 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661
Douglas Gregor88d292c2010-05-13 16:44:06 +00003662 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3663 QualType T = SourceType;
3664 if (const PointerType *Pointer = T->getAs<PointerType>())
3665 T = Pointer->getPointeeType();
3666 if (const RecordType *RecordTy = T->getAs<RecordType>())
3667 S.MarkVTableUsed(CurInitExpr->getLocStart(),
3668 cast<CXXRecordDecl>(RecordTy->getDecl()));
3669 }
3670
John McCall2536c6d2010-08-25 10:28:54 +00003671 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003672 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003673 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003674 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003675 VK_XValue :
3676 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003677 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3678 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003679 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003680 CurInit.get(),
3681 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003682 break;
3683 }
3684
3685 case SK_BindReference:
3686 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3687 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3688 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003689 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003690 << BitField->getDeclName()
3691 << CurInitExpr->getSourceRange();
3692 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003693 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003694 }
Anders Carlssona91be642010-01-29 02:47:33 +00003695
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003696 if (CurInitExpr->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003697 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003698 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3699 << Entity.getType().isVolatileQualified()
3700 << CurInitExpr->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003701 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003702 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003703 }
3704
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003705 // Reference binding does not have any corresponding ASTs.
3706
3707 // Check exception specifications
3708 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003709 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003710
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003711 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003712
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003713 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003714 // Reference binding does not have any corresponding ASTs.
3715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003716 // Check exception specifications
3717 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003718 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003719
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003720 break;
3721
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003722 case SK_ExtraneousCopyToTemporary:
3723 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3724 /*IsExtraneousCopy=*/true);
3725 break;
3726
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 case SK_UserConversion: {
3728 // We have a user-defined conversion that invokes either a constructor
3729 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00003730 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00003731 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003732 FunctionDecl *Fn = Step->Function.Function;
3733 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003734 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003735 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003736 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003737 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003738 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003739 SourceLocation Loc = CurInitExpr->getLocStart();
3740 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003741
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 // Determine the arguments required to actually perform the constructor
3743 // call.
3744 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00003745 MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003746 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003747 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003748
3749 // Build the an expression that constructs a temporary.
3750 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003751 move_arg(ConstructorArgs),
3752 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003753 CXXConstructExpr::CK_Complete,
3754 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003755 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003756 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003757
Anders Carlssona01874b2010-04-21 18:47:17 +00003758 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003759 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003760 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003761
John McCalle3027922010-08-25 11:45:40 +00003762 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003763 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3764 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3765 S.IsDerivedFrom(SourceType, Class))
3766 IsCopy = true;
Douglas Gregor95562572010-04-24 23:45:46 +00003767
3768 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003769 } else {
3770 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003771 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003772 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John McCall1064d7e2010-03-16 05:22:47 +00003773 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
John McCalla0296f72010-03-19 07:35:19 +00003774 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003775 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003776
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003777 // FIXME: Should we move this initialization into a separate
3778 // derived-to-base conversion? I believe the answer is "no", because
3779 // we don't want to turn off access control here for c-style casts.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003780 if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00003781 FoundFn, Conversion))
John McCallfaf5fb42010-08-26 23:41:50 +00003782 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003783
3784 // Do a little dance to make sure that CurInit has the proper
3785 // pointer.
3786 CurInit.release();
3787
3788 // Build the actual call to the conversion function.
Douglas Gregor668443e2011-01-20 00:18:04 +00003789 CurInit = S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003790 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003791 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003792
John McCalle3027922010-08-25 11:45:40 +00003793 CastKind = CK_UserDefinedConversion;
Douglas Gregor95562572010-04-24 23:45:46 +00003794
3795 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003796 }
3797
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003798 bool RequiresCopy = !IsCopy &&
3799 getKind() != InitializationSequence::ReferenceBinding;
3800 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003801 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003802 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3803 CurInitExpr = static_cast<Expr *>(CurInit.get());
3804 QualType T = CurInitExpr->getType();
3805 if (const RecordType *Record = T->getAs<RecordType>()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00003806 CXXDestructorDecl *Destructor
3807 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
Douglas Gregor95562572010-04-24 23:45:46 +00003808 S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3809 S.PDiag(diag::err_access_dtor_temp) << T);
3810 S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003811 S.DiagnoseUseOfDecl(Destructor, CurInitExpr->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003812 }
3813 }
3814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003815 CurInitExpr = CurInit.takeAs<Expr>();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003816 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003817 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3818 CurInitExpr->getType(),
3819 CastKind, CurInitExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00003820 IsLvalue ? VK_LValue : VK_RValue));
Douglas Gregore1314a62009-12-18 05:02:21 +00003821
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003822 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003823 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3824 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003825
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003826 break;
3827 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003828
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003829 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003830 case SK_QualificationConversionXValue:
3831 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003833 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003834 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003835 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003836 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003837 VK_XValue :
3838 VK_RValue);
John McCalle3027922010-08-25 11:45:40 +00003839 S.ImpCastExprToType(CurInitExpr, Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 CurInit.release();
3841 CurInit = S.Owned(CurInitExpr);
3842 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003843 }
3844
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003845 case SK_ConversionSequence: {
3846 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3847
3848 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003849 getAssignmentAction(Entity),
3850 IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003851 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003852
3853 CurInit.release();
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003854 CurInit = S.Owned(CurInitExpr);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003855 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003856 }
3857
Douglas Gregor51e77d52009-12-10 17:56:55 +00003858 case SK_ListInitialization: {
3859 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3860 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003861 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003862 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003863
3864 CurInit.release();
3865 CurInit = S.Owned(InitList);
3866 break;
3867 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003868
3869 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003870 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003871 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003872 = cast<CXXConstructorDecl>(Step->Function.Function);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003873
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003874 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003875 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003876 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3877 ? Kind.getEqualLoc()
3878 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003879
3880 if (Kind.getKind() == InitializationKind::IK_Default) {
3881 // Force even a trivial, implicit default constructor to be
3882 // semantically checked. We do this explicitly because we don't build
3883 // the definition for completely trivial constructors.
3884 CXXRecordDecl *ClassDecl = Constructor->getParent();
3885 assert(ClassDecl && "No parent class for constructor.");
3886 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3887 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3888 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3889 }
3890
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003891 // Determine the arguments required to actually perform the constructor
3892 // call.
3893 if (S.CompleteConstructorCall(Constructor, move(Args),
3894 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003895 return ExprError();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003896
Chandler Carruthc9262402010-08-23 07:55:51 +00003897
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003898 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00003899 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003900 (Kind.getKind() == InitializationKind::IK_Direct ||
3901 Kind.getKind() == InitializationKind::IK_Value)) {
3902 // An explicitly-constructed temporary, e.g., X(1, 2).
3903 unsigned NumExprs = ConstructorArgs.size();
3904 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00003905 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003906 S.DiagnoseUseOfDecl(Constructor, Loc);
3907
Douglas Gregor2b88c112010-09-08 00:15:04 +00003908 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3909 if (!TSInfo)
3910 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
3911
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003912 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3913 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00003914 TSInfo,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00003915 Exprs,
3916 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00003917 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00003918 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003919 } else {
3920 CXXConstructExpr::ConstructionKind ConstructKind =
3921 CXXConstructExpr::CK_Complete;
3922
3923 if (Entity.getKind() == InitializedEntity::EK_Base) {
3924 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3925 CXXConstructExpr::CK_VirtualBase :
3926 CXXConstructExpr::CK_NonVirtualBase;
3927 }
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003928
Chandler Carruth01718152010-10-25 08:47:36 +00003929 // Only get the parenthesis range if it is a direct construction.
3930 SourceRange parenRange =
3931 Kind.getKind() == InitializationKind::IK_Direct ?
3932 Kind.getParenRange() : SourceRange();
3933
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003934 // If the entity allows NRVO, mark the construction as elidable
3935 // unconditionally.
3936 if (Entity.allowsNRVO())
3937 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3938 Constructor, /*Elidable=*/true,
3939 move_arg(ConstructorArgs),
3940 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00003941 ConstructKind,
3942 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003943 else
3944 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3945 Constructor,
3946 move_arg(ConstructorArgs),
3947 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00003948 ConstructKind,
3949 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00003950 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003951 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003952 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003953
3954 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00003955 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003956 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003957 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
Douglas Gregore1314a62009-12-18 05:02:21 +00003958
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003959 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003960 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003961
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003962 break;
3963 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003964
3965 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003966 step_iterator NextStep = Step;
3967 ++NextStep;
3968 if (NextStep != StepEnd &&
3969 NextStep->Kind == SK_ConstructorInitialization) {
3970 // The need for zero-initialization is recorded directly into
3971 // the call to the object's constructor within the next step.
3972 ConstructorInitRequiresZeroInit = true;
3973 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3974 S.getLangOptions().CPlusPlus &&
3975 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00003976 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
3977 if (!TSInfo)
3978 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
3979 Kind.getRange().getBegin());
3980
3981 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
3982 TSInfo->getType().getNonLValueExprType(S.Context),
3983 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003984 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003985 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003986 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003987 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003988 break;
3989 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003990
3991 case SK_CAssignment: {
3992 QualType SourceType = CurInitExpr->getType();
3993 Sema::AssignConvertType ConvTy =
3994 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003995
3996 // If this is a call, allow conversion to a transparent union.
3997 if (ConvTy != Sema::Compatible &&
3998 Entity.getKind() == InitializedEntity::EK_Parameter &&
3999 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
4000 == Sema::Compatible)
4001 ConvTy = Sema::Compatible;
4002
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004003 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004004 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4005 Step->Type, SourceType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004006 CurInitExpr,
4007 getAssignmentAction(Entity),
4008 &Complained)) {
4009 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004010 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004011 } else if (Complained)
4012 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004013
4014 CurInit.release();
4015 CurInit = S.Owned(CurInitExpr);
4016 break;
4017 }
Eli Friedman78275202009-12-19 08:11:05 +00004018
4019 case SK_StringInit: {
4020 QualType Ty = Step->Type;
4021 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
4022 break;
4023 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004024
4025 case SK_ObjCObjectConversion:
4026 S.ImpCastExprToType(CurInitExpr, Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004027 CK_ObjCObjectLValueCast,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004028 S.CastCategory(CurInitExpr));
4029 CurInit.release();
4030 CurInit = S.Owned(CurInitExpr);
4031 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004032 }
4033 }
John McCall1f425642010-11-11 03:21:53 +00004034
4035 // Diagnose non-fatal problems with the completed initialization.
4036 if (Entity.getKind() == InitializedEntity::EK_Member &&
4037 cast<FieldDecl>(Entity.getDecl())->isBitField())
4038 S.CheckBitFieldInitialization(Kind.getLocation(),
4039 cast<FieldDecl>(Entity.getDecl()),
4040 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004041
4042 return move(CurInit);
4043}
4044
4045//===----------------------------------------------------------------------===//
4046// Diagnose initialization failures
4047//===----------------------------------------------------------------------===//
4048bool InitializationSequence::Diagnose(Sema &S,
4049 const InitializedEntity &Entity,
4050 const InitializationKind &Kind,
4051 Expr **Args, unsigned NumArgs) {
4052 if (SequenceKind != FailedSequence)
4053 return false;
4054
Douglas Gregor1b303932009-12-22 15:35:07 +00004055 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004056 switch (Failure) {
4057 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004058 // FIXME: Customize for the initialized entity?
4059 if (NumArgs == 0)
4060 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4061 << DestType.getNonReferenceType();
4062 else // FIXME: diagnostic below could be better!
4063 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4064 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004065 break;
4066
4067 case FK_ArrayNeedsInitList:
4068 case FK_ArrayNeedsInitListOrStringLiteral:
4069 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4070 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4071 break;
4072
John McCall16df1e52010-03-30 21:47:33 +00004073 case FK_AddressOfOverloadFailed: {
4074 DeclAccessPair Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004075 S.ResolveAddressOfOverloadedFunction(Args[0],
4076 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004077 true,
4078 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004079 break;
John McCall16df1e52010-03-30 21:47:33 +00004080 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004081
4082 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004083 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004084 switch (FailedOverloadResult) {
4085 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004086 if (Failure == FK_UserConversionOverloadFailed)
4087 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4088 << Args[0]->getType() << DestType
4089 << Args[0]->getSourceRange();
4090 else
4091 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4092 << DestType << Args[0]->getType()
4093 << Args[0]->getSourceRange();
4094
John McCall5c32be02010-08-24 20:38:10 +00004095 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004096 break;
4097
4098 case OR_No_Viable_Function:
4099 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4100 << Args[0]->getType() << DestType.getNonReferenceType()
4101 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004102 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004103 break;
4104
4105 case OR_Deleted: {
4106 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4107 << Args[0]->getType() << DestType.getNonReferenceType()
4108 << Args[0]->getSourceRange();
4109 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004110 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004111 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4112 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004113 if (Ovl == OR_Deleted) {
4114 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4115 << Best->Function->isDeleted();
4116 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004117 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004118 }
4119 break;
4120 }
4121
4122 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004123 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004124 break;
4125 }
4126 break;
4127
4128 case FK_NonConstLValueReferenceBindingToTemporary:
4129 case FK_NonConstLValueReferenceBindingToUnrelated:
4130 S.Diag(Kind.getLocation(),
4131 Failure == FK_NonConstLValueReferenceBindingToTemporary
4132 ? diag::err_lvalue_reference_bind_to_temporary
4133 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004134 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004135 << DestType.getNonReferenceType()
4136 << Args[0]->getType()
4137 << Args[0]->getSourceRange();
4138 break;
4139
4140 case FK_RValueReferenceBindingToLValue:
4141 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
4142 << Args[0]->getSourceRange();
4143 break;
4144
4145 case FK_ReferenceInitDropsQualifiers:
4146 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4147 << DestType.getNonReferenceType()
4148 << Args[0]->getType()
4149 << Args[0]->getSourceRange();
4150 break;
4151
4152 case FK_ReferenceInitFailed:
4153 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4154 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004155 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156 << Args[0]->getType()
4157 << Args[0]->getSourceRange();
4158 break;
4159
4160 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00004161 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4162 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004163 << DestType
John McCall086a4642010-11-24 05:12:34 +00004164 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004165 << Args[0]->getType()
4166 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004167 break;
4168
4169 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004170 SourceRange R;
4171
4172 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004173 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004174 InitList->getLocEnd());
Douglas Gregor8ec51732010-09-08 21:40:08 +00004175 else
4176 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004177
Douglas Gregor8ec51732010-09-08 21:40:08 +00004178 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4179 if (Kind.isCStyleOrFunctionalCast())
4180 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4181 << R;
4182 else
4183 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4184 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004185 break;
4186 }
4187
4188 case FK_ReferenceBindingToInitList:
4189 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4190 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4191 break;
4192
4193 case FK_InitListBadDestinationType:
4194 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4195 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4196 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004197
4198 case FK_ConstructorOverloadFailed: {
4199 SourceRange ArgsRange;
4200 if (NumArgs)
4201 ArgsRange = SourceRange(Args[0]->getLocStart(),
4202 Args[NumArgs - 1]->getLocEnd());
4203
4204 // FIXME: Using "DestType" for the entity we're printing is probably
4205 // bad.
4206 switch (FailedOverloadResult) {
4207 case OR_Ambiguous:
4208 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4209 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004210 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4211 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004212 break;
4213
4214 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004215 if (Kind.getKind() == InitializationKind::IK_Default &&
4216 (Entity.getKind() == InitializedEntity::EK_Base ||
4217 Entity.getKind() == InitializedEntity::EK_Member) &&
4218 isa<CXXConstructorDecl>(S.CurContext)) {
4219 // This is implicit default initialization of a member or
4220 // base within a constructor. If no viable function was
4221 // found, notify the user that she needs to explicitly
4222 // initialize this base/member.
4223 CXXConstructorDecl *Constructor
4224 = cast<CXXConstructorDecl>(S.CurContext);
4225 if (Entity.getKind() == InitializedEntity::EK_Base) {
4226 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4227 << Constructor->isImplicit()
4228 << S.Context.getTypeDeclType(Constructor->getParent())
4229 << /*base=*/0
4230 << Entity.getType();
4231
4232 RecordDecl *BaseDecl
4233 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4234 ->getDecl();
4235 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4236 << S.Context.getTagDeclType(BaseDecl);
4237 } else {
4238 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4239 << Constructor->isImplicit()
4240 << S.Context.getTypeDeclType(Constructor->getParent())
4241 << /*member=*/1
4242 << Entity.getName();
4243 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4244
4245 if (const RecordType *Record
4246 = Entity.getType()->getAs<RecordType>())
4247 S.Diag(Record->getDecl()->getLocation(),
4248 diag::note_previous_decl)
4249 << S.Context.getTagDeclType(Record->getDecl());
4250 }
4251 break;
4252 }
4253
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004254 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4255 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004256 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004257 break;
4258
4259 case OR_Deleted: {
4260 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4261 << true << DestType << ArgsRange;
4262 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004263 OverloadingResult Ovl
4264 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004265 if (Ovl == OR_Deleted) {
4266 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4267 << Best->Function->isDeleted();
4268 } else {
4269 llvm_unreachable("Inconsistent overload resolution?");
4270 }
4271 break;
4272 }
4273
4274 case OR_Success:
4275 llvm_unreachable("Conversion did not fail!");
4276 break;
4277 }
4278 break;
4279 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004280
4281 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004282 if (Entity.getKind() == InitializedEntity::EK_Member &&
4283 isa<CXXConstructorDecl>(S.CurContext)) {
4284 // This is implicit default-initialization of a const member in
4285 // a constructor. Complain that it needs to be explicitly
4286 // initialized.
4287 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4288 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4289 << Constructor->isImplicit()
4290 << S.Context.getTypeDeclType(Constructor->getParent())
4291 << /*const=*/1
4292 << Entity.getName();
4293 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4294 << Entity.getName();
4295 } else {
4296 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4297 << DestType << (bool)DestType->getAs<RecordType>();
4298 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004299 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004300
4301 case FK_Incomplete:
4302 S.RequireCompleteType(Kind.getLocation(), DestType,
4303 diag::err_init_incomplete_type);
4304 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004305 }
4306
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004307 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004308 return true;
4309}
Douglas Gregore1314a62009-12-18 05:02:21 +00004310
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004311void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4312 switch (SequenceKind) {
4313 case FailedSequence: {
4314 OS << "Failed sequence: ";
4315 switch (Failure) {
4316 case FK_TooManyInitsForReference:
4317 OS << "too many initializers for reference";
4318 break;
4319
4320 case FK_ArrayNeedsInitList:
4321 OS << "array requires initializer list";
4322 break;
4323
4324 case FK_ArrayNeedsInitListOrStringLiteral:
4325 OS << "array requires initializer list or string literal";
4326 break;
4327
4328 case FK_AddressOfOverloadFailed:
4329 OS << "address of overloaded function failed";
4330 break;
4331
4332 case FK_ReferenceInitOverloadFailed:
4333 OS << "overload resolution for reference initialization failed";
4334 break;
4335
4336 case FK_NonConstLValueReferenceBindingToTemporary:
4337 OS << "non-const lvalue reference bound to temporary";
4338 break;
4339
4340 case FK_NonConstLValueReferenceBindingToUnrelated:
4341 OS << "non-const lvalue reference bound to unrelated type";
4342 break;
4343
4344 case FK_RValueReferenceBindingToLValue:
4345 OS << "rvalue reference bound to an lvalue";
4346 break;
4347
4348 case FK_ReferenceInitDropsQualifiers:
4349 OS << "reference initialization drops qualifiers";
4350 break;
4351
4352 case FK_ReferenceInitFailed:
4353 OS << "reference initialization failed";
4354 break;
4355
4356 case FK_ConversionFailed:
4357 OS << "conversion failed";
4358 break;
4359
4360 case FK_TooManyInitsForScalar:
4361 OS << "too many initializers for scalar";
4362 break;
4363
4364 case FK_ReferenceBindingToInitList:
4365 OS << "referencing binding to initializer list";
4366 break;
4367
4368 case FK_InitListBadDestinationType:
4369 OS << "initializer list for non-aggregate, non-scalar type";
4370 break;
4371
4372 case FK_UserConversionOverloadFailed:
4373 OS << "overloading failed for user-defined conversion";
4374 break;
4375
4376 case FK_ConstructorOverloadFailed:
4377 OS << "constructor overloading failed";
4378 break;
4379
4380 case FK_DefaultInitOfConst:
4381 OS << "default initialization of a const variable";
4382 break;
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004383
4384 case FK_Incomplete:
4385 OS << "initialization of incomplete type";
4386 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004387 }
4388 OS << '\n';
4389 return;
4390 }
4391
4392 case DependentSequence:
4393 OS << "Dependent sequence: ";
4394 return;
4395
4396 case UserDefinedConversion:
4397 OS << "User-defined conversion sequence: ";
4398 break;
4399
4400 case ConstructorInitialization:
4401 OS << "Constructor initialization sequence: ";
4402 break;
4403
4404 case ReferenceBinding:
4405 OS << "Reference binding: ";
4406 break;
4407
4408 case ListInitialization:
4409 OS << "List initialization: ";
4410 break;
4411
4412 case ZeroInitialization:
4413 OS << "Zero initialization\n";
4414 return;
4415
4416 case NoInitialization:
4417 OS << "No initialization\n";
4418 return;
4419
4420 case StandardConversion:
4421 OS << "Standard conversion: ";
4422 break;
4423
4424 case CAssignment:
4425 OS << "C assignment: ";
4426 break;
4427
4428 case StringInit:
4429 OS << "String initialization: ";
4430 break;
4431 }
4432
4433 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4434 if (S != step_begin()) {
4435 OS << " -> ";
4436 }
4437
4438 switch (S->Kind) {
4439 case SK_ResolveAddressOfOverloadedFunction:
4440 OS << "resolve address of overloaded function";
4441 break;
4442
4443 case SK_CastDerivedToBaseRValue:
4444 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4445 break;
4446
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004447 case SK_CastDerivedToBaseXValue:
4448 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4449 break;
4450
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004451 case SK_CastDerivedToBaseLValue:
4452 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4453 break;
4454
4455 case SK_BindReference:
4456 OS << "bind reference to lvalue";
4457 break;
4458
4459 case SK_BindReferenceToTemporary:
4460 OS << "bind reference to a temporary";
4461 break;
4462
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004463 case SK_ExtraneousCopyToTemporary:
4464 OS << "extraneous C++03 copy to temporary";
4465 break;
4466
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004467 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004468 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004469 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004470
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004471 case SK_QualificationConversionRValue:
4472 OS << "qualification conversion (rvalue)";
4473
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004474 case SK_QualificationConversionXValue:
4475 OS << "qualification conversion (xvalue)";
4476
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004477 case SK_QualificationConversionLValue:
4478 OS << "qualification conversion (lvalue)";
4479 break;
4480
4481 case SK_ConversionSequence:
4482 OS << "implicit conversion sequence (";
4483 S->ICS->DebugPrint(); // FIXME: use OS
4484 OS << ")";
4485 break;
4486
4487 case SK_ListInitialization:
4488 OS << "list initialization";
4489 break;
4490
4491 case SK_ConstructorInitialization:
4492 OS << "constructor initialization";
4493 break;
4494
4495 case SK_ZeroInitialization:
4496 OS << "zero initialization";
4497 break;
4498
4499 case SK_CAssignment:
4500 OS << "C assignment";
4501 break;
4502
4503 case SK_StringInit:
4504 OS << "string initialization";
4505 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004506
4507 case SK_ObjCObjectConversion:
4508 OS << "Objective-C object conversion";
4509 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004510 }
4511 }
4512}
4513
4514void InitializationSequence::dump() const {
4515 dump(llvm::errs());
4516}
4517
Douglas Gregore1314a62009-12-18 05:02:21 +00004518//===----------------------------------------------------------------------===//
4519// Initialization helper functions
4520//===----------------------------------------------------------------------===//
John McCalldadc5752010-08-24 06:29:42 +00004521ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004522Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4523 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004524 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004525 if (Init.isInvalid())
4526 return ExprError();
4527
John McCall1f425642010-11-11 03:21:53 +00004528 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00004529 assert(InitE && "No initialization expression?");
4530
4531 if (EqualLoc.isInvalid())
4532 EqualLoc = InitE->getLocStart();
4533
4534 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4535 EqualLoc);
4536 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4537 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004538 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004539}