blob: 1dff64e85579bb5ab759cf69e6364a7957e6dc99 [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
John McCall66884dd2011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
John McCall66884dd2011-02-21 07:22:22 +000067static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
68 const ArrayType *arrayType = Context.getAsArrayType(declType);
69 if (!arrayType) return 0;
70
71 return IsStringInit(init, arrayType, Context);
72}
73
John McCall5decec92011-02-21 07:57:55 +000074static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
75 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000076 // Get the length of the string as parsed.
77 uint64_t StrLength =
78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
79
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner0cb78032009-02-24 22:27:37 +000081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000082 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000083 // being initialized to a string literal.
84 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000085 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000086 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000087 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
88 ConstVal,
89 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000090 return;
Chris Lattner0cb78032009-02-24 22:27:37 +000091 }
Mike Stump11289f42009-09-09 15:08:12 +000092
Eli Friedman893abe42009-05-29 18:22:49 +000093 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +000094
Eli Friedman554eba92011-04-11 00:23:45 +000095 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +000096 // the size may be smaller or larger than the string we are initializing.
97 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +000098 if (S.getLangOptions().CPlusPlus) {
99 // [dcl.init.string]p2
100 if (StrLength > CAT->getSize().getZExtValue())
101 S.Diag(Str->getSourceRange().getBegin(),
102 diag::err_initializer_string_for_char_array_too_long)
103 << Str->getSourceRange();
104 } else {
105 // C99 6.7.8p14.
106 if (StrLength-1 > CAT->getSize().getZExtValue())
107 S.Diag(Str->getSourceRange().getBegin(),
108 diag::warn_initializer_string_for_char_array_too_long)
109 << Str->getSourceRange();
110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Eli Friedman893abe42009-05-29 18:22:49 +0000112 // Set the type to the actual size that we are initializing. If we have
113 // something like:
114 // char x[1] = "foo";
115 // then this will set the string literal's type to char[1].
116 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000117}
118
Chris Lattner0cb78032009-02-24 22:27:37 +0000119//===----------------------------------------------------------------------===//
120// Semantic checking for initializer lists.
121//===----------------------------------------------------------------------===//
122
Douglas Gregorcde232f2009-01-29 01:05:33 +0000123/// @brief Semantic checking for initializer lists.
124///
125/// The InitListChecker class contains a set of routines that each
126/// handle the initialization of a certain kind of entity, e.g.,
127/// arrays, vectors, struct/union types, scalars, etc. The
128/// InitListChecker itself performs a recursive walk of the subobject
129/// structure of the type to be initialized, while stepping through
130/// the initializer list one element at a time. The IList and Index
131/// parameters to each of the Check* routines contain the active
132/// (syntactic) initializer list and the index into that initializer
133/// list that represents the current initializer. Each routine is
134/// responsible for moving that Index forward as it consumes elements.
135///
136/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000137/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000138/// initializer list and the index into that initializer list where we
139/// are copying initializers as we map them over to the semantic
140/// list. Once we have completed our recursive walk of the subobject
141/// structure, we will have constructed a full semantic initializer
142/// list.
143///
144/// C99 designators cause changes in the initializer list traversal,
145/// because they make the initialization "jump" into a specific
146/// subobject and then continue the initialization from that
147/// point. CheckDesignatedInitializer() recursively steps into the
148/// designated subobject and manages backing out the recursion to
149/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000150namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000151class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000152 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000153 bool hadError;
154 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
155 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000156
Anders Carlsson6cabf312010-01-23 23:23:01 +0000157 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000158 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000159 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000160 unsigned &StructuredIndex,
161 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000162 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000163 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000164 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000165 unsigned &StructuredIndex,
166 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000167 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000168 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000169 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000170 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000171 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000172 unsigned &StructuredIndex,
173 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000174 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000175 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000176 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000177 InitListExpr *StructuredList,
178 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000180 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000181 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000182 InitListExpr *StructuredList,
183 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000184 void CheckReferenceType(const InitializedEntity &Entity,
185 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000186 unsigned &Index,
187 InitListExpr *StructuredList,
188 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000189 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000190 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
192 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000194 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000195 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000198 unsigned &StructuredIndex,
199 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000200 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000201 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000202 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000206 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000207 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000208 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000209 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000210 RecordDecl::field_iterator *NextField,
211 llvm::APSInt *NextElementIndex,
212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000215 bool FinishSubobjectInit,
216 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000217 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
218 QualType CurrentObjectType,
219 InitListExpr *StructuredList,
220 unsigned StructuredIndex,
221 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222 void UpdateStructuredListElement(InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 Expr *expr);
225 int numArrayElements(QualType DeclType);
226 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000227
Douglas Gregor2bb07652009-12-22 00:05:34 +0000228 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
229 const InitializedEntity &ParentEntity,
230 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000231 void FillInValueInitializations(const InitializedEntity &Entity,
232 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000233public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000234 InitListChecker(Sema &S, const InitializedEntity &Entity,
235 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 bool HadError() { return hadError; }
237
238 // @brief Retrieves the fully-structured initializer list used for
239 // semantic analysis and code generation.
240 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
241};
Chris Lattner9ececce2009-02-24 22:48:58 +0000242} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000243
Douglas Gregor2bb07652009-12-22 00:05:34 +0000244void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
245 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000246 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000247 bool &RequiresSecondPass) {
248 SourceLocation Loc = ILE->getSourceRange().getBegin();
249 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000250 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000251 = InitializedEntity::InitializeMember(Field, &ParentEntity);
252 if (Init >= NumInits || !ILE->getInit(Init)) {
253 // FIXME: We probably don't need to handle references
254 // specially here, since value-initialization of references is
255 // handled in InitializationSequence.
256 if (Field->getType()->isReferenceType()) {
257 // C++ [dcl.init.aggr]p9:
258 // If an incomplete or empty initializer-list leaves a
259 // member of reference type uninitialized, the program is
260 // ill-formed.
261 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
262 << Field->getType()
263 << ILE->getSyntacticForm()->getSourceRange();
264 SemaRef.Diag(Field->getLocation(),
265 diag::note_uninit_reference_member);
266 hadError = true;
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269
Douglas Gregor2bb07652009-12-22 00:05:34 +0000270 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
271 true);
272 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
273 if (!InitSeq) {
274 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
275 hadError = true;
276 return;
277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278
John McCalldadc5752010-08-24 06:29:42 +0000279 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000280 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000281 if (MemberInit.isInvalid()) {
282 hadError = true;
283 return;
284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor2bb07652009-12-22 00:05:34 +0000286 if (hadError) {
287 // Do nothing
288 } else if (Init < NumInits) {
289 ILE->setInit(Init, MemberInit.takeAs<Expr>());
290 } else if (InitSeq.getKind()
291 == InitializationSequence::ConstructorInitialization) {
292 // Value-initialization requires a constructor call, so
293 // extend the initializer list to include the constructor
294 // call and make a note that we'll need to take another pass
295 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000296 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000297 RequiresSecondPass = true;
298 }
299 } else if (InitListExpr *InnerILE
300 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301 FillInValueInitializations(MemberEntity, InnerILE,
302 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000303}
304
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000305/// Recursively replaces NULL values within the given initializer list
306/// with expressions that perform value-initialization of the
307/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308void
Douglas Gregor723796a2009-12-16 06:35:08 +0000309InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
310 InitListExpr *ILE,
311 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000312 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000313 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000314 SourceLocation Loc = ILE->getSourceRange().getBegin();
315 if (ILE->getSyntacticForm())
316 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000317
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000318 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000319 if (RType->getDecl()->isUnion() &&
320 ILE->getInitializedFieldInUnion())
321 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
322 Entity, ILE, RequiresSecondPass);
323 else {
324 unsigned Init = 0;
325 for (RecordDecl::field_iterator
326 Field = RType->getDecl()->field_begin(),
327 FieldEnd = RType->getDecl()->field_end();
328 Field != FieldEnd; ++Field) {
329 if (Field->isUnnamedBitfield())
330 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000331
Douglas Gregor2bb07652009-12-22 00:05:34 +0000332 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000333 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000334
335 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
336 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000337 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000338
Douglas Gregor2bb07652009-12-22 00:05:34 +0000339 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000340
Douglas Gregor2bb07652009-12-22 00:05:34 +0000341 // Only look at the first initialization of a union.
342 if (RType->getDecl()->isUnion())
343 break;
344 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000345 }
346
347 return;
Mike Stump11289f42009-09-09 15:08:12 +0000348 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000349
350 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000351
Douglas Gregor723796a2009-12-16 06:35:08 +0000352 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000353 unsigned NumInits = ILE->getNumInits();
354 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000355 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000356 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
358 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000360 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000361 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000362 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000363 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000365 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000366 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000367 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000368
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000370 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000371 if (hadError)
372 return;
373
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000374 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
375 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 ElementEntity.setElementIndex(Init);
377
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000379 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
380 true);
381 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
382 if (!InitSeq) {
383 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000384 hadError = true;
385 return;
386 }
387
John McCalldadc5752010-08-24 06:29:42 +0000388 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000389 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000390 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000391 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000392 return;
393 }
394
395 if (hadError) {
396 // Do nothing
397 } else if (Init < NumInits) {
398 ILE->setInit(Init, ElementInit.takeAs<Expr>());
399 } else if (InitSeq.getKind()
400 == InitializationSequence::ConstructorInitialization) {
401 // Value-initialization requires a constructor call, so
402 // extend the initializer list to include the constructor
403 // call and make a note that we'll need to take another pass
404 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000405 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
Douglas Gregor723796a2009-12-16 06:35:08 +0000406 RequiresSecondPass = true;
407 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000408 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000409 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
410 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000411 }
412}
413
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000414
Douglas Gregor723796a2009-12-16 06:35:08 +0000415InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
416 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000417 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000418 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000419
Eli Friedman23a9e312008-05-19 19:16:24 +0000420 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000421 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000422 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000423 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000424 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000425 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000426 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000427
Douglas Gregor723796a2009-12-16 06:35:08 +0000428 if (!hadError) {
429 bool RequiresSecondPass = false;
430 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000431 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000433 RequiresSecondPass);
434 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000435}
436
437int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000438 // FIXME: use a proper constant
439 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000440 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000441 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000442 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
443 }
444 return maxElements;
445}
446
447int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000448 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000449 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000450 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000451 Field = structDecl->field_begin(),
452 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000453 Field != FieldEnd; ++Field) {
454 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
455 ++InitializableMembers;
456 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000457 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000458 return std::min(InitializableMembers, 1);
459 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000460}
461
Anders Carlsson6cabf312010-01-23 23:23:01 +0000462void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000463 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000464 QualType T, unsigned &Index,
465 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000466 unsigned &StructuredIndex,
467 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000468 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Steve Narofff8ecff22008-05-01 22:18:59 +0000470 if (T->isArrayType())
471 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000472 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000473 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000474 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000475 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000476 else
477 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000478
Eli Friedmane0f832b2008-05-25 13:49:22 +0000479 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000480 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000481 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000482 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000483 hadError = true;
484 return;
485 }
486
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000487 // Build a structured initializer list corresponding to this subobject.
488 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000489 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
490 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000491 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
492 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000493 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000494
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000495 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000496 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000498 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000499 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000500 StructuredSubobjectInitIndex,
501 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000502 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000503 StructuredSubobjectInitList->setType(T);
504
Douglas Gregor5741efb2009-03-01 17:12:46 +0000505 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000506 // range corresponds with the end of the last initializer it used.
507 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000508 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000509 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
510 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000512
Tanya Lattner5029d562010-03-07 04:17:15 +0000513 // Warn about missing braces.
514 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000515 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
516 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000517 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000519 "{")
520 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000522 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000523 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000524}
525
Anders Carlsson6cabf312010-01-23 23:23:01 +0000526void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000527 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000528 unsigned &Index,
529 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000530 unsigned &StructuredIndex,
531 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000532 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000533 SyntacticToSemantic[IList] = StructuredList;
534 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000536 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000537 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
538 IList->setType(ExprTy);
539 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000540 if (hadError)
541 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000542
Eli Friedman85f54972008-05-25 13:22:35 +0000543 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000544 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000545 if (StructuredIndex == 1 &&
546 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000547 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000548 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000549 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000550 hadError = true;
551 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000552 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000553 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000554 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000555 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000556 // Don't complain for incomplete types, since we'll get an error
557 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000558 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000559 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000560 CurrentObjectType->isArrayType()? 0 :
561 CurrentObjectType->isVectorType()? 1 :
562 CurrentObjectType->isScalarType()? 2 :
563 CurrentObjectType->isUnionType()? 3 :
564 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000565
566 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000567 if (SemaRef.getLangOptions().CPlusPlus) {
568 DK = diag::err_excess_initializers;
569 hadError = true;
570 }
Nate Begeman425038c2009-07-07 21:53:06 +0000571 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
572 DK = diag::err_excess_initializers;
573 hadError = true;
574 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000575
Chris Lattnerb0912a52009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000577 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000578 }
579 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000580
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000581 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000582 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000583 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000584 << FixItHint::CreateRemoval(IList->getLocStart())
585 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000586}
587
Anders Carlsson6cabf312010-01-23 23:23:01 +0000588void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000589 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000590 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000591 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 unsigned &Index,
593 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000594 unsigned &StructuredIndex,
595 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000596 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000597 CheckScalarType(Entity, IList, DeclType, Index,
598 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000599 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000601 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000602 } else if (DeclType->isAggregateType()) {
603 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000604 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000605 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000606 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000607 StructuredList, StructuredIndex,
608 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000609 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000610 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000612 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000613 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000614 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000615 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000616 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000617 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000618 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
619 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000620 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000621 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000622 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000623 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 } else if (DeclType->isRecordType()) {
625 // C++ [dcl.init]p14:
626 // [...] If the class is an aggregate (8.5.1), and the initializer
627 // is a brace-enclosed list, see 8.5.1.
628 //
629 // Note: 8.5.1 is handled below; here, we diagnose the case where
630 // we have an initializer list and a destination type that is not
631 // an aggregate.
632 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000634 << DeclType << IList->getSourceRange();
635 hadError = true;
636 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000637 CheckReferenceType(Entity, IList, DeclType, Index,
638 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000639 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000640 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
641 << DeclType;
642 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000643 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000644 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
645 << DeclType;
646 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000647 }
648}
649
Anders Carlsson6cabf312010-01-23 23:23:01 +0000650void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000651 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000652 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000653 unsigned &Index,
654 InitListExpr *StructuredList,
655 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000656 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000657 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
658 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000659 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000660 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000661 = getStructuredSubobjectInit(IList, Index, ElemType,
662 StructuredList, StructuredIndex,
663 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000664 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000665 newStructuredList, newStructuredIndex);
666 ++StructuredIndex;
667 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000668 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000669 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000670 return CheckScalarType(Entity, IList, ElemType, Index,
671 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000672 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000673 return CheckReferenceType(Entity, IList, ElemType, Index,
674 StructuredList, StructuredIndex);
675 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000676
John McCall5decec92011-02-21 07:57:55 +0000677 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
678 // arrayType can be incomplete if we're initializing a flexible
679 // array member. There's nothing we can do with the completed
680 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000681
John McCall5decec92011-02-21 07:57:55 +0000682 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
683 CheckStringInit(Str, ElemType, arrayType, SemaRef);
684 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000685 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000686 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000687 }
John McCall5decec92011-02-21 07:57:55 +0000688
689 // Fall through for subaggregate initialization.
690
691 } else if (SemaRef.getLangOptions().CPlusPlus) {
692 // C++ [dcl.init.aggr]p12:
693 // All implicit type conversions (clause 4) are considered when
694 // initializing the aggregate member with an ini- tializer from
695 // an initializer-list. If the initializer can initialize a
696 // member, the member is initialized. [...]
697
698 // FIXME: Better EqualLoc?
699 InitializationKind Kind =
700 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
701 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
702
703 if (Seq) {
704 ExprResult Result =
705 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
706 if (Result.isInvalid())
707 hadError = true;
708
709 UpdateStructuredListElement(StructuredList, StructuredIndex,
710 Result.takeAs<Expr>());
711 ++Index;
712 return;
713 }
714
715 // Fall through for subaggregate initialization
716 } else {
717 // C99 6.7.8p13:
718 //
719 // The initializer for a structure or union object that has
720 // automatic storage duration shall be either an initializer
721 // list as described below, or a single expression that has
722 // compatible structure or union type. In the latter case, the
723 // initial value of the object, including unnamed members, is
724 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000725 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000726 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000727 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000728 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000729 if (ExprRes.isInvalid())
730 hadError = true;
731 else {
732 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
733 if (ExprRes.isInvalid())
734 hadError = true;
735 }
736 UpdateStructuredListElement(StructuredList, StructuredIndex,
737 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000738 ++Index;
739 return;
740 }
John Wiegley01296292011-04-08 18:41:53 +0000741 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000742 // Fall through for subaggregate initialization
743 }
744
745 // C++ [dcl.init.aggr]p12:
746 //
747 // [...] Otherwise, if the member is itself a non-empty
748 // subaggregate, brace elision is assumed and the initializer is
749 // considered for the initialization of the first member of
750 // the subaggregate.
751 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
752 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
753 StructuredIndex);
754 ++StructuredIndex;
755 } else {
756 // We cannot initialize this element, so let
757 // PerformCopyInitialization produce the appropriate diagnostic.
758 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
759 SemaRef.Owned(expr));
760 hadError = true;
761 ++Index;
762 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000763 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000764}
765
Anders Carlsson6cabf312010-01-23 23:23:01 +0000766void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000767 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000768 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000769 InitListExpr *StructuredList,
770 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000771 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000772 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000773 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000774 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000775 ++Index;
776 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000777 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000778 }
John McCall643169b2010-11-11 00:46:36 +0000779
780 Expr *expr = IList->getInit(Index);
781 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
782 SemaRef.Diag(SubIList->getLocStart(),
783 diag::warn_many_braces_around_scalar_init)
784 << SubIList->getSourceRange();
785
786 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
787 StructuredIndex);
788 return;
789 } else if (isa<DesignatedInitExpr>(expr)) {
790 SemaRef.Diag(expr->getSourceRange().getBegin(),
791 diag::err_designator_for_scalar_init)
792 << DeclType << expr->getSourceRange();
793 hadError = true;
794 ++Index;
795 ++StructuredIndex;
796 return;
797 }
798
799 ExprResult Result =
800 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
801 SemaRef.Owned(expr));
802
803 Expr *ResultExpr = 0;
804
805 if (Result.isInvalid())
806 hadError = true; // types weren't compatible.
807 else {
808 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809
John McCall643169b2010-11-11 00:46:36 +0000810 if (ResultExpr != expr) {
811 // The type was promoted, update initializer list.
812 IList->setInit(Index, ResultExpr);
813 }
814 }
815 if (hadError)
816 ++StructuredIndex;
817 else
818 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
819 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000820}
821
Anders Carlsson6cabf312010-01-23 23:23:01 +0000822void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
823 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000824 unsigned &Index,
825 InitListExpr *StructuredList,
826 unsigned &StructuredIndex) {
827 if (Index < IList->getNumInits()) {
828 Expr *expr = IList->getInit(Index);
829 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000830 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000831 << DeclType << IList->getSourceRange();
832 hadError = true;
833 ++Index;
834 ++StructuredIndex;
835 return;
Mike Stump11289f42009-09-09 15:08:12 +0000836 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000837
John McCalldadc5752010-08-24 06:29:42 +0000838 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000839 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
840 SemaRef.Owned(expr));
841
842 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000843 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000844
845 expr = Result.takeAs<Expr>();
846 IList->setInit(Index, expr);
847
Douglas Gregord14247a2009-01-30 22:09:00 +0000848 if (hadError)
849 ++StructuredIndex;
850 else
851 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
852 ++Index;
853 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000854 // FIXME: It would be wonderful if we could point at the actual member. In
855 // general, it would be useful to pass location information down the stack,
856 // so that we know the location (or decl) of the "current object" being
857 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000858 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000859 diag::err_init_reference_member_uninitialized)
860 << DeclType
861 << IList->getSourceRange();
862 hadError = true;
863 ++Index;
864 ++StructuredIndex;
865 return;
866 }
867}
868
Anders Carlsson6cabf312010-01-23 23:23:01 +0000869void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000870 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000871 unsigned &Index,
872 InitListExpr *StructuredList,
873 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000874 if (Index >= IList->getNumInits())
875 return;
Mike Stump11289f42009-09-09 15:08:12 +0000876
John McCall6a16b2f2010-10-30 00:11:39 +0000877 const VectorType *VT = DeclType->getAs<VectorType>();
878 unsigned maxElements = VT->getNumElements();
879 unsigned numEltsInit = 0;
880 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000881
John McCall6a16b2f2010-10-30 00:11:39 +0000882 if (!SemaRef.getLangOptions().OpenCL) {
883 // If the initializing element is a vector, try to copy-initialize
884 // instead of breaking it apart (which is doomed to failure anyway).
885 Expr *Init = IList->getInit(Index);
886 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
887 ExprResult Result =
888 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
889 SemaRef.Owned(Init));
890
891 Expr *ResultExpr = 0;
892 if (Result.isInvalid())
893 hadError = true; // types weren't compatible.
894 else {
895 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
John McCall6a16b2f2010-10-30 00:11:39 +0000897 if (ResultExpr != Init) {
898 // The type was promoted, update initializer list.
899 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000900 }
901 }
John McCall6a16b2f2010-10-30 00:11:39 +0000902 if (hadError)
903 ++StructuredIndex;
904 else
905 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
906 ++Index;
907 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
John McCall6a16b2f2010-10-30 00:11:39 +0000910 InitializedEntity ElementEntity =
911 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000912
John McCall6a16b2f2010-10-30 00:11:39 +0000913 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
914 // Don't attempt to go past the end of the init list
915 if (Index >= IList->getNumInits())
916 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000917
John McCall6a16b2f2010-10-30 00:11:39 +0000918 ElementEntity.setElementIndex(Index);
919 CheckSubElementType(ElementEntity, IList, elementType, Index,
920 StructuredList, StructuredIndex);
921 }
922 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000923 }
John McCall6a16b2f2010-10-30 00:11:39 +0000924
925 InitializedEntity ElementEntity =
926 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927
John McCall6a16b2f2010-10-30 00:11:39 +0000928 // OpenCL initializers allows vectors to be constructed from vectors.
929 for (unsigned i = 0; i < maxElements; ++i) {
930 // Don't attempt to go past the end of the init list
931 if (Index >= IList->getNumInits())
932 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000933
John McCall6a16b2f2010-10-30 00:11:39 +0000934 ElementEntity.setElementIndex(Index);
935
936 QualType IType = IList->getInit(Index)->getType();
937 if (!IType->isVectorType()) {
938 CheckSubElementType(ElementEntity, IList, elementType, Index,
939 StructuredList, StructuredIndex);
940 ++numEltsInit;
941 } else {
942 QualType VecType;
943 const VectorType *IVT = IType->getAs<VectorType>();
944 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945
John McCall6a16b2f2010-10-30 00:11:39 +0000946 if (IType->isExtVectorType())
947 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
948 else
949 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000950 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000951 CheckSubElementType(ElementEntity, IList, VecType, Index,
952 StructuredList, StructuredIndex);
953 numEltsInit += numIElts;
954 }
955 }
956
957 // OpenCL requires all elements to be initialized.
958 if (numEltsInit != maxElements)
959 if (SemaRef.getLangOptions().OpenCL)
960 SemaRef.Diag(IList->getSourceRange().getBegin(),
961 diag::err_vector_incorrect_num_initializers)
962 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000963}
964
Anders Carlsson6cabf312010-01-23 23:23:01 +0000965void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000966 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000967 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000968 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000969 unsigned &Index,
970 InitListExpr *StructuredList,
971 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +0000972 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
973
Steve Narofff8ecff22008-05-01 22:18:59 +0000974 // Check for the special-case of initializing an array with a string.
975 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +0000976 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000977 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +0000978 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000979 // We place the string literal directly into the resulting
980 // initializer list. This is the only place where the structure
981 // of the structured initializer list doesn't match exactly,
982 // because doing so would involve allocating one character
983 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000984 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000985 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000986 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000987 return;
988 }
989 }
John McCall66884dd2011-02-21 07:22:22 +0000990 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000991 // Check for VLAs; in standard C it would be possible to check this
992 // earlier, but I don't know where clang accepts VLAs (gcc accepts
993 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000994 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000995 diag::err_variable_object_no_init)
996 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000997 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000998 ++Index;
999 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001000 return;
1001 }
1002
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001003 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001004 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1005 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001006 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001007 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001008 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001009 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001010 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001011 maxElementsKnown = true;
1012 }
1013
John McCall66884dd2011-02-21 07:22:22 +00001014 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001015 while (Index < IList->getNumInits()) {
1016 Expr *Init = IList->getInit(Index);
1017 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001018 // If we're not the subobject that matches up with the '{' for
1019 // the designator, we shouldn't be handling the
1020 // designator. Return immediately.
1021 if (!SubobjectIsDesignatorContext)
1022 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001023
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001024 // Handle this designated initializer. elementIndex will be
1025 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001026 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001027 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001028 StructuredList, StructuredIndex, true,
1029 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001030 hadError = true;
1031 continue;
1032 }
1033
Douglas Gregor033d1252009-01-23 16:54:12 +00001034 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001035 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001036 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001037 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001038 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001039
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001040 // If the array is of incomplete type, keep track of the number of
1041 // elements in the initializer.
1042 if (!maxElementsKnown && elementIndex > maxElements)
1043 maxElements = elementIndex;
1044
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001045 continue;
1046 }
1047
1048 // If we know the maximum number of elements, and we've already
1049 // hit it, stop consuming elements in the initializer list.
1050 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001051 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001052
Anders Carlsson6cabf312010-01-23 23:23:01 +00001053 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001055 Entity);
1056 // Check this element.
1057 CheckSubElementType(ElementEntity, IList, elementType, Index,
1058 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001059 ++elementIndex;
1060
1061 // If the array is of incomplete type, keep track of the number of
1062 // elements in the initializer.
1063 if (!maxElementsKnown && elementIndex > maxElements)
1064 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001065 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001066 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001067 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001068 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001069 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001070 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001071 // Sizing an array implicitly to zero is not allowed by ISO C,
1072 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001073 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001074 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001075 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001076
Mike Stump11289f42009-09-09 15:08:12 +00001077 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001078 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001079 }
1080}
1081
Anders Carlsson6cabf312010-01-23 23:23:01 +00001082void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001083 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001084 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001085 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001086 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001087 unsigned &Index,
1088 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001089 unsigned &StructuredIndex,
1090 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001091 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001092
Eli Friedman23a9e312008-05-19 19:16:24 +00001093 // If the record is invalid, some of it's members are invalid. To avoid
1094 // confusion, we forgo checking the intializer for the entire record.
1095 if (structDecl->isInvalidDecl()) {
1096 hadError = true;
1097 return;
Mike Stump11289f42009-09-09 15:08:12 +00001098 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001099
1100 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1101 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001102 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001103 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001104 Field != FieldEnd; ++Field) {
1105 if (Field->getDeclName()) {
1106 StructuredList->setInitializedFieldInUnion(*Field);
1107 break;
1108 }
1109 }
1110 return;
1111 }
1112
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001113 // If structDecl is a forward declaration, this loop won't do
1114 // anything except look at designated initializers; That's okay,
1115 // because an error should get printed out elsewhere. It might be
1116 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001117 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001118 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001119 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001120 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001121 while (Index < IList->getNumInits()) {
1122 Expr *Init = IList->getInit(Index);
1123
1124 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001125 // If we're not the subobject that matches up with the '{' for
1126 // the designator, we shouldn't be handling the
1127 // designator. Return immediately.
1128 if (!SubobjectIsDesignatorContext)
1129 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001130
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001131 // Handle this designated initializer. Field will be updated to
1132 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001133 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001134 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001135 StructuredList, StructuredIndex,
1136 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001137 hadError = true;
1138
Douglas Gregora9add4e2009-02-12 19:00:39 +00001139 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001140
1141 // Disable check for missing fields when designators are used.
1142 // This matches gcc behaviour.
1143 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001144 continue;
1145 }
1146
1147 if (Field == FieldEnd) {
1148 // We've run out of fields. We're done.
1149 break;
1150 }
1151
Douglas Gregora9add4e2009-02-12 19:00:39 +00001152 // We've already initialized a member of a union. We're done.
1153 if (InitializedSomething && DeclType->isUnionType())
1154 break;
1155
Douglas Gregor91f84212008-12-11 16:49:14 +00001156 // If we've hit the flexible array member at the end, we're done.
1157 if (Field->getType()->isIncompleteArrayType())
1158 break;
1159
Douglas Gregor51695702009-01-29 16:53:55 +00001160 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001161 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001162 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001163 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001164 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001165
Anders Carlsson6cabf312010-01-23 23:23:01 +00001166 InitializedEntity MemberEntity =
1167 InitializedEntity::InitializeMember(*Field, &Entity);
1168 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1169 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001170 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001171
1172 if (DeclType->isUnionType()) {
1173 // Initialize the first field within the union.
1174 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001175 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001176
1177 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001178 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001179
John McCalle40b58e2010-03-11 19:32:38 +00001180 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001182 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1183 // It is possible we have one or more unnamed bitfields remaining.
1184 // Find first (if any) named field and emit warning.
1185 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1186 it != end; ++it) {
1187 if (!it->isUnnamedBitfield()) {
1188 SemaRef.Diag(IList->getSourceRange().getEnd(),
1189 diag::warn_missing_field_initializers) << it->getName();
1190 break;
1191 }
1192 }
1193 }
1194
Mike Stump11289f42009-09-09 15:08:12 +00001195 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001196 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001197 return;
1198
1199 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001200 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001201 (!isa<InitListExpr>(IList->getInit(Index)) ||
1202 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001203 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001204 diag::err_flexible_array_init_nonempty)
1205 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001206 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001207 << *Field;
1208 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001209 ++Index;
1210 return;
1211 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001212 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001213 diag::ext_flexible_array_init)
1214 << IList->getInit(Index)->getSourceRange().getBegin();
1215 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1216 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001217 }
1218
Anders Carlsson6cabf312010-01-23 23:23:01 +00001219 InitializedEntity MemberEntity =
1220 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221
Anders Carlsson6cabf312010-01-23 23:23:01 +00001222 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001224 StructuredList, StructuredIndex);
1225 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001226 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001227 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001228}
Steve Narofff8ecff22008-05-01 22:18:59 +00001229
Douglas Gregord5846a12009-04-15 06:41:24 +00001230/// \brief Expand a field designator that refers to a member of an
1231/// anonymous struct or union into a series of field designators that
1232/// refers to the field within the appropriate subobject.
1233///
Douglas Gregord5846a12009-04-15 06:41:24 +00001234static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001235 DesignatedInitExpr *DIE,
1236 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001237 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001238 typedef DesignatedInitExpr::Designator Designator;
1239
Douglas Gregord5846a12009-04-15 06:41:24 +00001240 // Build the replacement designators.
1241 llvm::SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001242 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1243 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1244 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001245 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001246 DIE->getDesignator(DesigIdx)->getDotLoc(),
1247 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1248 else
1249 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1250 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001251 assert(isa<FieldDecl>(*PI));
1252 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001253 }
1254
1255 // Expand the current designator into the set of replacement
1256 // designators, so we have a full subobject path down to where the
1257 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001258 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001259 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001260}
Mike Stump11289f42009-09-09 15:08:12 +00001261
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001263/// corresponds to FieldName.
1264static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1265 IdentifierInfo *FieldName) {
1266 assert(AnonField->isAnonymousStructOrUnion());
1267 Decl *NextDecl = AnonField->getNextDeclInContext();
1268 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1269 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1270 return IF;
1271 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001272 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001273 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001274}
1275
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001276/// @brief Check the well-formedness of a C99 designated initializer.
1277///
1278/// Determines whether the designated initializer @p DIE, which
1279/// resides at the given @p Index within the initializer list @p
1280/// IList, is well-formed for a current object of type @p DeclType
1281/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001282/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001283/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001284///
1285/// @param IList The initializer list in which this designated
1286/// initializer occurs.
1287///
Douglas Gregora5324162009-04-15 04:56:10 +00001288/// @param DIE The designated initializer expression.
1289///
1290/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001291///
1292/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1293/// into which the designation in @p DIE should refer.
1294///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001295/// @param NextField If non-NULL and the first designator in @p DIE is
1296/// a field, this will be set to the field declaration corresponding
1297/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001298///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001299/// @param NextElementIndex If non-NULL and the first designator in @p
1300/// DIE is an array designator or GNU array-range designator, this
1301/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001302///
1303/// @param Index Index into @p IList where the designated initializer
1304/// @p DIE occurs.
1305///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001306/// @param StructuredList The initializer list expression that
1307/// describes all of the subobject initializers in the order they'll
1308/// actually be initialized.
1309///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001310/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001311bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001312InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001313 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001314 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001315 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001316 QualType &CurrentObjectType,
1317 RecordDecl::field_iterator *NextField,
1318 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001319 unsigned &Index,
1320 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001321 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001322 bool FinishSubobjectInit,
1323 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001324 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001325 // Check the actual initialization for the designated object type.
1326 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001327
1328 // Temporarily remove the designator expression from the
1329 // initializer list that the child calls see, so that we don't try
1330 // to re-process the designator.
1331 unsigned OldIndex = Index;
1332 IList->setInit(OldIndex, DIE->getInit());
1333
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001334 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001335 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001336
1337 // Restore the designated initializer expression in the syntactic
1338 // form of the initializer list.
1339 if (IList->getInit(OldIndex) != DIE->getInit())
1340 DIE->setInit(IList->getInit(OldIndex));
1341 IList->setInit(OldIndex, DIE);
1342
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001343 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001344 }
1345
Douglas Gregora5324162009-04-15 04:56:10 +00001346 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001347 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001348 "Need a non-designated initializer list to start from");
1349
Douglas Gregora5324162009-04-15 04:56:10 +00001350 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001351 // Determine the structural initializer list that corresponds to the
1352 // current subobject.
1353 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001354 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001355 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001356 SourceRange(D->getStartLocation(),
1357 DIE->getSourceRange().getEnd()));
1358 assert(StructuredList && "Expected a structured initializer list");
1359
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001360 if (D->isFieldDesignator()) {
1361 // C99 6.7.8p7:
1362 //
1363 // If a designator has the form
1364 //
1365 // . identifier
1366 //
1367 // then the current object (defined below) shall have
1368 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001369 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001370 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001371 if (!RT) {
1372 SourceLocation Loc = D->getDotLoc();
1373 if (Loc.isInvalid())
1374 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001375 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1376 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001377 ++Index;
1378 return true;
1379 }
1380
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001381 // Note: we perform a linear search of the fields here, despite
1382 // the fact that we have a faster lookup method, because we always
1383 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001384 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001385 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001386 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001387 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001388 Field = RT->getDecl()->field_begin(),
1389 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001390 for (; Field != FieldEnd; ++Field) {
1391 if (Field->isUnnamedBitfield())
1392 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001394 // If we find a field representing an anonymous field, look in the
1395 // IndirectFieldDecl that follow for the designated initializer.
1396 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1397 if (IndirectFieldDecl *IF =
1398 FindIndirectFieldDesignator(*Field, FieldName)) {
1399 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1400 D = DIE->getDesignator(DesigIdx);
1401 break;
1402 }
1403 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001404 if (KnownField && KnownField == *Field)
1405 break;
1406 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001407 break;
1408
1409 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001410 }
1411
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001412 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001413 // There was no normal field in the struct with the designated
1414 // name. Perform another lookup for this name, which may find
1415 // something that we can't designate (e.g., a member function),
1416 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001417 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001418 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001419 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001420 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001421 // Name lookup didn't find anything. Determine whether this
1422 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001424 Sema::LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001425 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001426 Sema::CTC_NoKeywords) &&
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001427 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001428 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001429 ->Equals(RT->getDecl())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001430 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001431 diag::err_field_designator_unknown_suggest)
1432 << FieldName << CurrentObjectType << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001433 << FixItHint::CreateReplacement(D->getFieldLoc(),
1434 R.getLookupName().getAsString());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregor6da83622010-01-07 00:17:44 +00001436 diag::note_previous_decl)
1437 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001438 } else {
1439 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1440 << FieldName << CurrentObjectType;
1441 ++Index;
1442 return true;
1443 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001446 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001447 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001448 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001449 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001450 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001451 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001452 ++Index;
1453 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001454 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001455
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001456 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001457 // The replacement field comes from typo correction; find it
1458 // in the list of fields.
1459 FieldIndex = 0;
1460 Field = RT->getDecl()->field_begin();
1461 for (; Field != FieldEnd; ++Field) {
1462 if (Field->isUnnamedBitfield())
1463 continue;
1464
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001466 Field->getIdentifier() == ReplacementField->getIdentifier())
1467 break;
1468
1469 ++FieldIndex;
1470 }
1471 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001472 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001473
1474 // All of the fields of a union are located at the same place in
1475 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001476 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001477 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001478 StructuredList->setInitializedFieldInUnion(*Field);
1479 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001480
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001481 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001482 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001483
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001484 // Make sure that our non-designated initializer list has space
1485 // for a subobject corresponding to this field.
1486 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001487 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001488
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001489 // This designator names a flexible array member.
1490 if (Field->getType()->isIncompleteArrayType()) {
1491 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001492 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001493 // We can't designate an object within the flexible array
1494 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001495 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001496 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001497 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001498 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001499 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001500 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001501 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 << *Field;
1503 Invalid = true;
1504 }
1505
Chris Lattner001b29c2010-10-10 17:49:49 +00001506 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1507 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001508 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001509 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001510 diag::err_flexible_array_init_needs_braces)
1511 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001512 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001513 << *Field;
1514 Invalid = true;
1515 }
1516
1517 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001518 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001519 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001520 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001521 diag::err_flexible_array_init_nonempty)
1522 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001523 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001524 << *Field;
1525 Invalid = true;
1526 }
1527
1528 if (Invalid) {
1529 ++Index;
1530 return true;
1531 }
1532
1533 // Initialize the array.
1534 bool prevHadError = hadError;
1535 unsigned newStructuredIndex = FieldIndex;
1536 unsigned OldIndex = Index;
1537 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001538
1539 InitializedEntity MemberEntity =
1540 InitializedEntity::InitializeMember(*Field, &Entity);
1541 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001542 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001543
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001544 IList->setInit(OldIndex, DIE);
1545 if (hadError && !prevHadError) {
1546 ++Field;
1547 ++FieldIndex;
1548 if (NextField)
1549 *NextField = Field;
1550 StructuredIndex = FieldIndex;
1551 return true;
1552 }
1553 } else {
1554 // Recurse to check later designated subobjects.
1555 QualType FieldType = (*Field)->getType();
1556 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001558 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001559 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001560 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1561 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001562 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001563 true, false))
1564 return true;
1565 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001566
1567 // Find the position of the next field to be initialized in this
1568 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001569 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001570 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571
1572 // If this the first designator, our caller will continue checking
1573 // the rest of this struct/class/union subobject.
1574 if (IsFirstDesignator) {
1575 if (NextField)
1576 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001577 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578 return false;
1579 }
1580
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581 if (!FinishSubobjectInit)
1582 return false;
1583
Douglas Gregord5846a12009-04-15 06:41:24 +00001584 // We've already initialized something in the union; we're done.
1585 if (RT->getDecl()->isUnion())
1586 return hadError;
1587
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001588 // Check the remaining fields within this class/struct/union subobject.
1589 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590
Anders Carlsson6cabf312010-01-23 23:23:01 +00001591 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001592 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 return hadError && !prevHadError;
1594 }
1595
1596 // C99 6.7.8p6:
1597 //
1598 // If a designator has the form
1599 //
1600 // [ constant-expression ]
1601 //
1602 // then the current object (defined below) shall have array
1603 // type and the expression shall be an integer constant
1604 // expression. If the array is of unknown size, any
1605 // nonnegative value is valid.
1606 //
1607 // Additionally, cope with the GNU extension that permits
1608 // designators of the form
1609 //
1610 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001611 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001613 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001614 << CurrentObjectType;
1615 ++Index;
1616 return true;
1617 }
1618
1619 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1621 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001623 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001624 DesignatedEndIndex = DesignatedStartIndex;
1625 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001626 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627
Mike Stump11289f42009-09-09 15:08:12 +00001628 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001629 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001630 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001631 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001632 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001633
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001634 // Codegen can't handle evaluating array range designators that have side
1635 // effects, because we replicate the AST value for each initialized element.
1636 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1637 // elements with something that has a side effect, so codegen can emit an
1638 // "error unsupported" error instead of miscompiling the app.
1639 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1640 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001641 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001642 }
1643
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001644 if (isa<ConstantArrayType>(AT)) {
1645 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001646 DesignatedStartIndex
1647 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001648 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001649 DesignatedEndIndex
1650 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001651 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1652 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001653 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001654 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001655 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001656 << IndexExpr->getSourceRange();
1657 ++Index;
1658 return true;
1659 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001660 } else {
1661 // Make sure the bit-widths and signedness match.
1662 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001663 DesignatedEndIndex
1664 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001665 else if (DesignatedStartIndex.getBitWidth() <
1666 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001667 DesignatedStartIndex
1668 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001669 DesignatedStartIndex.setIsUnsigned(true);
1670 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001673 // Make sure that our non-designated initializer list has space
1674 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001675 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001676 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001677 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001678
Douglas Gregor17bd0942009-01-28 23:36:17 +00001679 // Repeatedly perform subobject initializations in the range
1680 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001681
Douglas Gregor17bd0942009-01-28 23:36:17 +00001682 // Move to the next designator
1683 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1684 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001686 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001687 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001688
Douglas Gregor17bd0942009-01-28 23:36:17 +00001689 while (DesignatedStartIndex <= DesignatedEndIndex) {
1690 // Recurse to check later designated subobjects.
1691 QualType ElementType = AT->getElementType();
1692 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001693
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001694 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001695 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1696 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001697 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001698 (DesignatedStartIndex == DesignatedEndIndex),
1699 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001700 return true;
1701
1702 // Move to the next index in the array that we'll be initializing.
1703 ++DesignatedStartIndex;
1704 ElementIndex = DesignatedStartIndex.getZExtValue();
1705 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001706
1707 // If this the first designator, our caller will continue checking
1708 // the rest of this array subobject.
1709 if (IsFirstDesignator) {
1710 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001711 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001712 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001713 return false;
1714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Douglas Gregor17bd0942009-01-28 23:36:17 +00001716 if (!FinishSubobjectInit)
1717 return false;
1718
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001719 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001720 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001722 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001723 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001724 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001725}
1726
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001727// Get the structured initializer list for a subobject of type
1728// @p CurrentObjectType.
1729InitListExpr *
1730InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1731 QualType CurrentObjectType,
1732 InitListExpr *StructuredList,
1733 unsigned StructuredIndex,
1734 SourceRange InitRange) {
1735 Expr *ExistingInit = 0;
1736 if (!StructuredList)
1737 ExistingInit = SyntacticToSemantic[IList];
1738 else if (StructuredIndex < StructuredList->getNumInits())
1739 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001740
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001741 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1742 return Result;
1743
1744 if (ExistingInit) {
1745 // We are creating an initializer list that initializes the
1746 // subobjects of the current object, but there was already an
1747 // initialization that completely initialized the current
1748 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001749 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001750 // struct X { int a, b; };
1751 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001752 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001753 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1754 // designated initializer re-initializes the whole
1755 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001756 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001757 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001758 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001759 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001760 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001761 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001762 << ExistingInit->getSourceRange();
1763 }
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001766 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1767 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001768 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001769
Douglas Gregora8a089b2010-07-13 18:40:04 +00001770 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001771
Douglas Gregor6d00c992009-03-20 23:58:33 +00001772 // Pre-allocate storage for the structured initializer list.
1773 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001774 unsigned NumInits = 0;
1775 if (!StructuredList)
1776 NumInits = IList->getNumInits();
1777 else if (Index < IList->getNumInits()) {
1778 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1779 NumInits = SubList->getNumInits();
1780 }
1781
Mike Stump11289f42009-09-09 15:08:12 +00001782 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001783 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1784 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1785 NumElements = CAType->getSize().getZExtValue();
1786 // Simple heuristic so that we don't allocate a very large
1787 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001788 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001789 NumElements = 0;
1790 }
John McCall9dd450b2009-09-21 23:43:11 +00001791 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001792 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001793 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001794 RecordDecl *RDecl = RType->getDecl();
1795 if (RDecl->isUnion())
1796 NumElements = 1;
1797 else
Mike Stump11289f42009-09-09 15:08:12 +00001798 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001799 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001800 }
1801
Douglas Gregor221c9a52009-03-21 18:13:52 +00001802 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001803 NumElements = IList->getNumInits();
1804
Ted Kremenekac034612010-04-13 23:39:13 +00001805 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001806
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001807 // Link this new initializer list into the structured initializer
1808 // lists.
1809 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001810 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001811 else {
1812 Result->setSyntacticForm(IList);
1813 SyntacticToSemantic[IList] = Result;
1814 }
1815
1816 return Result;
1817}
1818
1819/// Update the initializer at index @p StructuredIndex within the
1820/// structured initializer list to the value @p expr.
1821void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1822 unsigned &StructuredIndex,
1823 Expr *expr) {
1824 // No structured initializer list to update
1825 if (!StructuredList)
1826 return;
1827
Ted Kremenekac034612010-04-13 23:39:13 +00001828 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1829 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001830 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001831 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001832 diag::warn_initializer_overrides)
1833 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001834 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001835 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001836 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001837 << PrevInit->getSourceRange();
1838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001840 ++StructuredIndex;
1841}
1842
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001843/// Check that the given Index expression is a valid array designator
1844/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001845/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001846/// and produces a reasonable diagnostic if there is a
1847/// failure. Returns true if there was an error, false otherwise. If
1848/// everything went okay, Value will receive the value of the constant
1849/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001850static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001851CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001852 SourceLocation Loc = Index->getSourceRange().getBegin();
1853
1854 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001855 if (S.VerifyIntegerConstantExpression(Index, &Value))
1856 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001857
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001858 if (Value.isSigned() && Value.isNegative())
1859 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001860 << Value.toString(10) << Index->getSourceRange();
1861
Douglas Gregor51650d32009-01-23 21:04:18 +00001862 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001863 return false;
1864}
1865
John McCalldadc5752010-08-24 06:29:42 +00001866ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001867 SourceLocation Loc,
1868 bool GNUSyntax,
1869 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001870 typedef DesignatedInitExpr::Designator ASTDesignator;
1871
1872 bool Invalid = false;
1873 llvm::SmallVector<ASTDesignator, 32> Designators;
1874 llvm::SmallVector<Expr *, 32> InitExpressions;
1875
1876 // Build designators and check array designator expressions.
1877 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1878 const Designator &D = Desig.getDesignator(Idx);
1879 switch (D.getKind()) {
1880 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001881 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001882 D.getFieldLoc()));
1883 break;
1884
1885 case Designator::ArrayDesignator: {
1886 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1887 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001888 if (!Index->isTypeDependent() &&
1889 !Index->isValueDependent() &&
1890 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001891 Invalid = true;
1892 else {
1893 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001894 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001895 D.getRBracketLoc()));
1896 InitExpressions.push_back(Index);
1897 }
1898 break;
1899 }
1900
1901 case Designator::ArrayRangeDesignator: {
1902 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1903 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1904 llvm::APSInt StartValue;
1905 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001906 bool StartDependent = StartIndex->isTypeDependent() ||
1907 StartIndex->isValueDependent();
1908 bool EndDependent = EndIndex->isTypeDependent() ||
1909 EndIndex->isValueDependent();
1910 if ((!StartDependent &&
1911 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1912 (!EndDependent &&
1913 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001914 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001915 else {
1916 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001917 if (StartDependent || EndDependent) {
1918 // Nothing to compute.
1919 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001920 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001921 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001922 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001923
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001924 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001925 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001926 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001927 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1928 Invalid = true;
1929 } else {
1930 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001931 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001932 D.getEllipsisLoc(),
1933 D.getRBracketLoc()));
1934 InitExpressions.push_back(StartIndex);
1935 InitExpressions.push_back(EndIndex);
1936 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001937 }
1938 break;
1939 }
1940 }
1941 }
1942
1943 if (Invalid || Init.isInvalid())
1944 return ExprError();
1945
1946 // Clear out the expressions within the designation.
1947 Desig.ClearExprs(*this);
1948
1949 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001950 = DesignatedInitExpr::Create(Context,
1951 Designators.data(), Designators.size(),
1952 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001953 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Douglas Gregorc124e592011-01-16 16:13:16 +00001955 if (getLangOptions().CPlusPlus)
1956 Diag(DIE->getLocStart(), diag::ext_designated_init)
1957 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001959 return Owned(DIE);
1960}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001961
Douglas Gregor723796a2009-12-16 06:35:08 +00001962bool Sema::CheckInitList(const InitializedEntity &Entity,
1963 InitListExpr *&InitList, QualType &DeclType) {
1964 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001965 if (!CheckInitList.HadError())
1966 InitList = CheckInitList.getFullyStructuredList();
1967
1968 return CheckInitList.HadError();
1969}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001970
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001971//===----------------------------------------------------------------------===//
1972// Initialization entity
1973//===----------------------------------------------------------------------===//
1974
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00001976 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001978{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001979 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1980 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001981 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001982 } else {
1983 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001984 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001985 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001986}
1987
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001989 CXXBaseSpecifier *Base,
1990 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001991{
1992 InitializedEntity Result;
1993 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00001994 Result.Base = reinterpret_cast<uintptr_t>(Base);
1995 if (IsInheritedVirtualBase)
1996 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997
Douglas Gregor1b303932009-12-22 15:35:07 +00001998 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001999 return Result;
2000}
2001
Douglas Gregor85dabae2009-12-16 01:38:02 +00002002DeclarationName InitializedEntity::getName() const {
2003 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00002004 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002005 if (!VariableOrMember)
2006 return DeclarationName();
2007 // Fall through
2008
2009 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002010 case EK_Member:
2011 return VariableOrMember->getDeclName();
2012
2013 case EK_Result:
2014 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002015 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002016 case EK_Temporary:
2017 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002018 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002019 case EK_ArrayElement:
2020 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002021 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002022 return DeclarationName();
2023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
Douglas Gregor85dabae2009-12-16 01:38:02 +00002025 // Silence GCC warning
2026 return DeclarationName();
2027}
2028
Douglas Gregora4b592a2009-12-19 03:01:41 +00002029DeclaratorDecl *InitializedEntity::getDecl() const {
2030 switch (getKind()) {
2031 case EK_Variable:
2032 case EK_Parameter:
2033 case EK_Member:
2034 return VariableOrMember;
2035
2036 case EK_Result:
2037 case EK_Exception:
2038 case EK_New:
2039 case EK_Temporary:
2040 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002041 case EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002042 case EK_ArrayElement:
2043 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002044 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002045 return 0;
2046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Douglas Gregora4b592a2009-12-19 03:01:41 +00002048 // Silence GCC warning
2049 return 0;
2050}
2051
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002052bool InitializedEntity::allowsNRVO() const {
2053 switch (getKind()) {
2054 case EK_Result:
2055 case EK_Exception:
2056 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002057
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002058 case EK_Variable:
2059 case EK_Parameter:
2060 case EK_Member:
2061 case EK_New:
2062 case EK_Temporary:
2063 case EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002064 case EK_Delegation:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002065 case EK_ArrayElement:
2066 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002067 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002068 break;
2069 }
2070
2071 return false;
2072}
2073
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002074//===----------------------------------------------------------------------===//
2075// Initialization sequence
2076//===----------------------------------------------------------------------===//
2077
2078void InitializationSequence::Step::Destroy() {
2079 switch (Kind) {
2080 case SK_ResolveAddressOfOverloadedFunction:
2081 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002082 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002083 case SK_CastDerivedToBaseLValue:
2084 case SK_BindReference:
2085 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002086 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002087 case SK_UserConversion:
2088 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002089 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002090 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002091 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002092 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002093 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002094 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002095 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002096 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002097 case SK_ArrayInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002098 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002099
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002100 case SK_ConversionSequence:
2101 delete ICS;
2102 }
2103}
2104
Douglas Gregor838fcc32010-03-26 20:14:36 +00002105bool InitializationSequence::isDirectReferenceBinding() const {
2106 return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2107}
2108
2109bool InitializationSequence::isAmbiguous() const {
2110 if (getKind() != FailedSequence)
2111 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregor838fcc32010-03-26 20:14:36 +00002113 switch (getFailureKind()) {
2114 case FK_TooManyInitsForReference:
2115 case FK_ArrayNeedsInitList:
2116 case FK_ArrayNeedsInitListOrStringLiteral:
2117 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2118 case FK_NonConstLValueReferenceBindingToTemporary:
2119 case FK_NonConstLValueReferenceBindingToUnrelated:
2120 case FK_RValueReferenceBindingToLValue:
2121 case FK_ReferenceInitDropsQualifiers:
2122 case FK_ReferenceInitFailed:
2123 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002124 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002125 case FK_TooManyInitsForScalar:
2126 case FK_ReferenceBindingToInitList:
2127 case FK_InitListBadDestinationType:
2128 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002129 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002130 case FK_ArrayTypeMismatch:
2131 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002132 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002133
Douglas Gregor838fcc32010-03-26 20:14:36 +00002134 case FK_ReferenceInitOverloadFailed:
2135 case FK_UserConversionOverloadFailed:
2136 case FK_ConstructorOverloadFailed:
2137 return FailedOverloadResult == OR_Ambiguous;
2138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002139
Douglas Gregor838fcc32010-03-26 20:14:36 +00002140 return false;
2141}
2142
Douglas Gregorb33eed02010-04-16 22:09:46 +00002143bool InitializationSequence::isConstructorInitialization() const {
2144 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2145}
2146
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002147void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002148 FunctionDecl *Function,
2149 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002150 Step S;
2151 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2152 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002153 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002154 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002155 Steps.push_back(S);
2156}
2157
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002159 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002160 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002161 switch (VK) {
2162 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2163 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2164 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002165 default: llvm_unreachable("No such category");
2166 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002167 S.Type = BaseType;
2168 Steps.push_back(S);
2169}
2170
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002172 bool BindingTemporary) {
2173 Step S;
2174 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2175 S.Type = T;
2176 Steps.push_back(S);
2177}
2178
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002179void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2180 Step S;
2181 S.Kind = SK_ExtraneousCopyToTemporary;
2182 S.Type = T;
2183 Steps.push_back(S);
2184}
2185
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002186void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002187 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002188 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002189 Step S;
2190 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002191 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002192 S.Function.Function = Function;
2193 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002194 Steps.push_back(S);
2195}
2196
2197void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002198 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002199 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002200 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002201 switch (VK) {
2202 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002203 S.Kind = SK_QualificationConversionRValue;
2204 break;
John McCall2536c6d2010-08-25 10:28:54 +00002205 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002206 S.Kind = SK_QualificationConversionXValue;
2207 break;
John McCall2536c6d2010-08-25 10:28:54 +00002208 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002209 S.Kind = SK_QualificationConversionLValue;
2210 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002211 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212 S.Type = Ty;
2213 Steps.push_back(S);
2214}
2215
2216void InitializationSequence::AddConversionSequenceStep(
2217 const ImplicitConversionSequence &ICS,
2218 QualType T) {
2219 Step S;
2220 S.Kind = SK_ConversionSequence;
2221 S.Type = T;
2222 S.ICS = new ImplicitConversionSequence(ICS);
2223 Steps.push_back(S);
2224}
2225
Douglas Gregor51e77d52009-12-10 17:56:55 +00002226void InitializationSequence::AddListInitializationStep(QualType T) {
2227 Step S;
2228 S.Kind = SK_ListInitialization;
2229 S.Type = T;
2230 Steps.push_back(S);
2231}
2232
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002233void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002234InitializationSequence::AddConstructorInitializationStep(
2235 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002236 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002237 QualType T) {
2238 Step S;
2239 S.Kind = SK_ConstructorInitialization;
2240 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002241 S.Function.Function = Constructor;
2242 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002243 Steps.push_back(S);
2244}
2245
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002246void InitializationSequence::AddZeroInitializationStep(QualType T) {
2247 Step S;
2248 S.Kind = SK_ZeroInitialization;
2249 S.Type = T;
2250 Steps.push_back(S);
2251}
2252
Douglas Gregore1314a62009-12-18 05:02:21 +00002253void InitializationSequence::AddCAssignmentStep(QualType T) {
2254 Step S;
2255 S.Kind = SK_CAssignment;
2256 S.Type = T;
2257 Steps.push_back(S);
2258}
2259
Eli Friedman78275202009-12-19 08:11:05 +00002260void InitializationSequence::AddStringInitStep(QualType T) {
2261 Step S;
2262 S.Kind = SK_StringInit;
2263 S.Type = T;
2264 Steps.push_back(S);
2265}
2266
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002267void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2268 Step S;
2269 S.Kind = SK_ObjCObjectConversion;
2270 S.Type = T;
2271 Steps.push_back(S);
2272}
2273
Douglas Gregore2f943b2011-02-22 18:29:51 +00002274void InitializationSequence::AddArrayInitStep(QualType T) {
2275 Step S;
2276 S.Kind = SK_ArrayInit;
2277 S.Type = T;
2278 Steps.push_back(S);
2279}
2280
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002282 OverloadingResult Result) {
2283 SequenceKind = FailedSequence;
2284 this->Failure = Failure;
2285 this->FailedOverloadResult = Result;
2286}
2287
2288//===----------------------------------------------------------------------===//
2289// Attempt initialization
2290//===----------------------------------------------------------------------===//
2291
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002292/// \brief Attempt list initialization (C++0x [dcl.init.list])
2293static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002294 const InitializedEntity &Entity,
2295 const InitializationKind &Kind,
2296 InitListExpr *InitList,
2297 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002298 // FIXME: We only perform rudimentary checking of list
2299 // initializations at this point, then assume that any list
2300 // initialization of an array, aggregate, or scalar will be
Sebastian Redld559a542010-06-30 16:41:54 +00002301 // well-formed. When we actually "perform" list initialization, we'll
Douglas Gregor51e77d52009-12-10 17:56:55 +00002302 // do all of the necessary checking. C++0x initializer lists will
2303 // force us to perform more checking here.
2304 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2305
Douglas Gregor1b303932009-12-22 15:35:07 +00002306 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002307
2308 // C++ [dcl.init]p13:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002309 // If T is a scalar type, then a declaration of the form
Douglas Gregor51e77d52009-12-10 17:56:55 +00002310 //
2311 // T x = { a };
2312 //
2313 // is equivalent to
2314 //
2315 // T x = a;
2316 if (DestType->isScalarType()) {
2317 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2318 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2319 return;
2320 }
2321
2322 // Assume scalar initialization from a single value works.
2323 } else if (DestType->isAggregateType()) {
2324 // Assume aggregate initialization works.
2325 } else if (DestType->isVectorType()) {
2326 // Assume vector initialization works.
2327 } else if (DestType->isReferenceType()) {
2328 // FIXME: C++0x defines behavior for this.
2329 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2330 return;
2331 } else if (DestType->isRecordType()) {
2332 // FIXME: C++0x defines behavior for this
2333 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2334 }
2335
2336 // Add a general "list initialization" step.
2337 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002338}
2339
2340/// \brief Try a reference initialization that involves calling a conversion
2341/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002342static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2343 const InitializedEntity &Entity,
2344 const InitializationKind &Kind,
2345 Expr *Initializer,
2346 bool AllowRValues,
2347 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002348 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002349 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2350 QualType T1 = cv1T1.getUnqualifiedType();
2351 QualType cv2T2 = Initializer->getType();
2352 QualType T2 = cv2T2.getUnqualifiedType();
2353
2354 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002355 bool ObjCConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002356 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002357 T1, T2, DerivedToBase,
2358 ObjCConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002359 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002360 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002361 (void)ObjCConversion;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002362
2363 // Build the candidate set directly in the initialization sequence
2364 // structure, so that it will persist if we fail.
2365 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2366 CandidateSet.clear();
2367
2368 // Determine whether we are allowed to call explicit constructors or
2369 // explicit conversion operators.
2370 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002371
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002372 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002373 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2374 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002375 // The type we're converting to is a class type. Enumerate its constructors
2376 // to see if there is a suitable conversion.
2377 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002378
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002379 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002380 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002381 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002382 NamedDecl *D = *Con;
2383 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2384
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002385 // Find the constructor (which may be a template).
2386 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002387 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002388 if (ConstructorTmpl)
2389 Constructor = cast<CXXConstructorDecl>(
2390 ConstructorTmpl->getTemplatedDecl());
2391 else
John McCalla0296f72010-03-19 07:35:19 +00002392 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002393
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002394 if (!Constructor->isInvalidDecl() &&
2395 Constructor->isConvertingConstructor(AllowExplicit)) {
2396 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002397 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002398 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002399 &Initializer, 1, CandidateSet,
2400 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002401 else
John McCalla0296f72010-03-19 07:35:19 +00002402 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002403 &Initializer, 1, CandidateSet,
2404 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002407 }
John McCall3696dcb2010-08-17 07:23:57 +00002408 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2409 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410
Douglas Gregor496e8b342010-05-07 19:42:26 +00002411 const RecordType *T2RecordType = 0;
2412 if ((T2RecordType = T2->getAs<RecordType>()) &&
2413 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002414 // The type we're converting from is a class type, enumerate its conversion
2415 // functions.
2416 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2417
John McCallad371252010-01-20 00:46:10 +00002418 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002419 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002420 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2421 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002422 NamedDecl *D = *I;
2423 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2424 if (isa<UsingShadowDecl>(D))
2425 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002426
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002427 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2428 CXXConversionDecl *Conv;
2429 if (ConvTemplate)
2430 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2431 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002432 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002433
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002434 // If the conversion function doesn't return a reference type,
2435 // it can't be considered for this conversion unless we're allowed to
2436 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002437 // FIXME: Do we need to make sure that we only consider conversion
2438 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002439 // break recursion.
2440 if ((AllowExplicit || !Conv->isExplicit()) &&
2441 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2442 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002443 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002444 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002445 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002446 else
John McCalla0296f72010-03-19 07:35:19 +00002447 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002448 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002449 }
2450 }
2451 }
John McCall3696dcb2010-08-17 07:23:57 +00002452 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2453 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002455 SourceLocation DeclLoc = Initializer->getLocStart();
2456
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002458 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002460 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002462
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002463 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002464
Chandler Carruth30141632011-02-25 19:41:05 +00002465 // This is the overload that will actually be used for the initialization, so
2466 // mark it as used.
2467 S.MarkDeclarationReferenced(DeclLoc, Function);
2468
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002469 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002470 if (isa<CXXConversionDecl>(Function))
2471 T2 = Function->getResultType();
2472 else
2473 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002474
2475 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002476 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002477 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002478
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002479 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002480 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002481 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002482 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002483 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002484 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002485 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002486
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002488 bool NewObjCConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002489 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002490 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002491 T2.getNonLValueExprType(S.Context),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002492 NewDerivedToBase, NewObjCConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002493 if (NewRefRelationship == Sema::Ref_Incompatible) {
2494 // If the type we've converted to is not reference-related to the
2495 // type we're looking for, then there is another conversion step
2496 // we need to perform to produce a temporary of the right type
2497 // that we'll be binding to.
2498 ImplicitConversionSequence ICS;
2499 ICS.setStandard();
2500 ICS.Standard = Best->FinalConversion;
2501 T2 = ICS.Standard.getToType(2);
2502 Sequence.AddConversionSequenceStep(ICS, T2);
2503 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002504 Sequence.AddDerivedToBaseCastStep(
2505 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002507 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002508 else if (NewObjCConversion)
2509 Sequence.AddObjCObjectConversionStep(
2510 S.Context.getQualifiedType(T1,
2511 T2.getNonReferenceType().getQualifiers()));
2512
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002513 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002514 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002516 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2517 return OR_Success;
2518}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002519
2520/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2521static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522 const InitializedEntity &Entity,
2523 const InitializationKind &Kind,
2524 Expr *Initializer,
2525 InitializationSequence &Sequence) {
2526 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
Sebastian Redld92badf2010-06-30 18:13:39 +00002527
Douglas Gregor1b303932009-12-22 15:35:07 +00002528 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002529 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002530 Qualifiers T1Quals;
2531 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002533 Qualifiers T2Quals;
2534 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002535 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002536
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002537 // If the initializer is the address of an overloaded function, try
2538 // to resolve the overloaded function. If all goes well, T2 is the
2539 // type of the resulting function.
2540 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002541 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002543 T1,
2544 false,
2545 Found)) {
2546 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2547 cv2T2 = Fn->getType();
2548 T2 = cv2T2.getUnqualifiedType();
2549 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002550 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2551 return;
2552 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002553 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002554
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002555 // Compute some basic properties of the types and the initializer.
2556 bool isLValueRef = DestType->isLValueReferenceType();
2557 bool isRValueRef = !isLValueRef;
2558 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002559 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002560 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002561 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002562 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
2563 ObjCConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002564
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002565 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002567 // "cv2 T2" as follows:
2568 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002570 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002571 // Note the analogous bullet points for rvlaue refs to functions. Because
2572 // there are no function rvalues in C++, rvalue refs to functions are treated
2573 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002574 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002575 bool T1Function = T1->isFunctionType();
2576 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002577 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002578 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002580 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002582 // reference-compatible with "cv2 T2," or
2583 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002584 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002585 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002586 // can occur. However, we do pay attention to whether it is a bit-field
2587 // to decide whether we're actually binding to a temporary created from
2588 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002589 if (DerivedToBase)
2590 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002591 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002592 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002593 else if (ObjCConversion)
2594 Sequence.AddObjCObjectConversionStep(
2595 S.Context.getQualifiedType(T1, T2Quals));
2596
Chandler Carruth04bdce62010-01-12 20:32:25 +00002597 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002598 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002599 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002600 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002601 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002602 return;
2603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604
2605 // - has a class type (i.e., T2 is a class type), where T1 is not
2606 // reference-related to T2, and can be implicitly converted to an
2607 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2608 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002609 // applicable conversion functions (13.3.1.6) and choosing the best
2610 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002611 // If we have an rvalue ref to function type here, the rhs must be
2612 // an rvalue.
2613 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2614 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002616 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002617 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002618 Sequence);
2619 if (ConvOvlResult == OR_Success)
2620 return;
John McCall0d1da222010-01-12 00:44:57 +00002621 if (ConvOvlResult != OR_No_Viable_Function) {
2622 Sequence.SetOverloadFailure(
2623 InitializationSequence::FK_ReferenceInitOverloadFailed,
2624 ConvOvlResult);
2625 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002626 }
2627 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002628
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002629 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002630 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002631 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002632 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002633 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2634 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2635 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002636 Sequence.SetOverloadFailure(
2637 InitializationSequence::FK_ReferenceInitOverloadFailed,
2638 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002639 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002640 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002641 ? (RefRelationship == Sema::Ref_Related
2642 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2643 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2644 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002645
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002646 return;
2647 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002648
Douglas Gregor92e460e2011-01-20 16:44:54 +00002649 // - If the initializer expression
2650 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2651 // "cv1 T1" is reference-compatible with "cv2 T2"
2652 // Note: functions are handled below.
2653 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002654 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002655 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002656 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002657 (InitCategory.isXValue() ||
2658 (InitCategory.isPRValue() && T2->isRecordType()) ||
2659 (InitCategory.isPRValue() && T2->isArrayType()))) {
2660 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2661 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002662 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2663 // compiler the freedom to perform a copy here or bind to the
2664 // object, while C++0x requires that we bind directly to the
2665 // object. Hence, we always bind to the object without making an
2666 // extra copy. However, in C++03 requires that we check for the
2667 // presence of a suitable copy constructor:
2668 //
2669 // The constructor that would be used to make the copy shall
2670 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002671 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002672 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002674
Douglas Gregor92e460e2011-01-20 16:44:54 +00002675 if (DerivedToBase)
2676 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2677 ValueKind);
2678 else if (ObjCConversion)
2679 Sequence.AddObjCObjectConversionStep(
2680 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681
Douglas Gregor92e460e2011-01-20 16:44:54 +00002682 if (T1Quals != T2Quals)
2683 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002684 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002685 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002686 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002687 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688
2689 // - has a class type (i.e., T2 is a class type), where T1 is not
2690 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002691 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2692 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002693 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002694 if (RefRelationship == Sema::Ref_Incompatible) {
2695 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2696 Kind, Initializer,
2697 /*AllowRValues=*/true,
2698 Sequence);
2699 if (ConvOvlResult)
2700 Sequence.SetOverloadFailure(
2701 InitializationSequence::FK_ReferenceInitOverloadFailed,
2702 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002704 return;
2705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002707 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2708 return;
2709 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002710
2711 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002712 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002714 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002715
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002716 // Determine whether we are allowed to call explicit constructors or
2717 // explicit conversion operators.
2718 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002719
2720 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2721
2722 if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2723 /*SuppressUserConversions*/ false,
2724 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002725 /*FIXME:InOverloadResolution=*/false,
2726 /*CStyle=*/Kind.isCStyleOrFunctionalCast())) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002727 // FIXME: Use the conversion function set stored in ICS to turn
2728 // this into an overloading ambiguity diagnostic. However, we need
2729 // to keep that set as an OverloadCandidateSet rather than as some
2730 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002731 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2732 Sequence.SetOverloadFailure(
2733 InitializationSequence::FK_ReferenceInitOverloadFailed,
2734 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00002735 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2736 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00002737 else
2738 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002739 return;
2740 }
2741
2742 // [...] If T1 is reference-related to T2, cv1 must be the
2743 // same cv-qualification as, or greater cv-qualification
2744 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002745 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2746 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002747 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002748 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002749 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2750 return;
2751 }
2752
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002754 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002755 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002756 InitCategory.isLValue()) {
2757 Sequence.SetFailed(
2758 InitializationSequence::FK_RValueReferenceBindingToLValue);
2759 return;
2760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002762 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2763 return;
2764}
2765
2766/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767/// (C++ [dcl.init.string], C99 6.7.8).
2768static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 const InitializedEntity &Entity,
2770 const InitializationKind &Kind,
2771 Expr *Initializer,
2772 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002773 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002774 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002775}
2776
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002777/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2778/// enumerates the constructors of the initialized entity and performs overload
2779/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002781 const InitializedEntity &Entity,
2782 const InitializationKind &Kind,
2783 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002784 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785 InitializationSequence &Sequence) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002786 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002787
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002788 // Build the candidate set directly in the initialization sequence
2789 // structure, so that it will persist if we fail.
2790 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2791 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002792
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002793 // Determine whether we are allowed to call explicit constructors or
2794 // explicit conversion operators.
2795 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2796 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002797 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00002798
2799 // The type we're constructing needs to be complete.
2800 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002801 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00002802 return;
2803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002805 // The type we're converting to is a class type. Enumerate its constructors
2806 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002807 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002808 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002809 CXXRecordDecl *DestRecordDecl
2810 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002812 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002813 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002814 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002815 NamedDecl *D = *Con;
2816 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00002817 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002819 // Find the constructor (which may be a template).
2820 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002821 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002822 if (ConstructorTmpl)
2823 Constructor = cast<CXXConstructorDecl>(
2824 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00002825 else {
John McCalla0296f72010-03-19 07:35:19 +00002826 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00002827
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00002829 // suppress user-defined conversions on the arguments.
2830 // FIXME: Move constructors?
2831 if (Kind.getKind() == InitializationKind::IK_Copy &&
2832 Constructor->isCopyConstructor())
2833 SuppressUserConversions = true;
2834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002836 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002837 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002838 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002839 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002840 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00002841 Args, NumArgs, CandidateSet,
2842 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002843 else
John McCalla0296f72010-03-19 07:35:19 +00002844 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00002845 Args, NumArgs, CandidateSet,
2846 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002847 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848 }
2849
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002850 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002851
2852 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002853 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00002855 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002856 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002858 Result);
2859 return;
2860 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002861
2862 // C++0x [dcl.init]p6:
2863 // If a program calls for the default initialization of an object
2864 // of a const-qualified type T, T shall be a class type with a
2865 // user-provided default constructor.
2866 if (Kind.getKind() == InitializationKind::IK_Default &&
2867 Entity.getType().isConstQualified() &&
2868 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2869 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2870 return;
2871 }
2872
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002873 // Add the constructor initialization step. Any cv-qualification conversion is
2874 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002875 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002876 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00002877 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00002878 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002879}
2880
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002881/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002882static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002883 const InitializedEntity &Entity,
2884 const InitializationKind &Kind,
2885 InitializationSequence &Sequence) {
2886 // C++ [dcl.init]p5:
2887 //
2888 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002889 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002890
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002891 // -- if T is an array type, then each element is value-initialized;
2892 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2893 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002894
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002895 if (const RecordType *RT = T->getAs<RecordType>()) {
2896 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2897 // -- if T is a class type (clause 9) with a user-declared
2898 // constructor (12.1), then the default constructor for T is
2899 // called (and the initialization is ill-formed if T has no
2900 // accessible default constructor);
2901 //
2902 // FIXME: we really want to refer to a single subobject of the array,
2903 // but Entity doesn't have a way to capture that (yet).
2904 if (ClassDecl->hasUserDeclaredConstructor())
2905 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002907 // -- if T is a (possibly cv-qualified) non-union class type
2908 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002909 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002910 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002911 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00002912 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002913 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002915 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002916 }
2917 }
2918
Douglas Gregor1b303932009-12-22 15:35:07 +00002919 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002920 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2921}
2922
Douglas Gregor85dabae2009-12-16 01:38:02 +00002923/// \brief Attempt default initialization (C++ [dcl.init]p6).
2924static void TryDefaultInitialization(Sema &S,
2925 const InitializedEntity &Entity,
2926 const InitializationKind &Kind,
2927 InitializationSequence &Sequence) {
2928 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929
Douglas Gregor85dabae2009-12-16 01:38:02 +00002930 // C++ [dcl.init]p6:
2931 // To default-initialize an object of type T means:
2932 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002933 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002934 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2935 DestType = Array->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002936
Douglas Gregor85dabae2009-12-16 01:38:02 +00002937 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2938 // constructor for T is called (and the initialization is ill-formed if
2939 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00002940 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00002941 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
2942 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944
Douglas Gregor85dabae2009-12-16 01:38:02 +00002945 // - otherwise, no initialization is performed.
2946 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947
Douglas Gregor85dabae2009-12-16 01:38:02 +00002948 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002949 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00002950 // default constructor.
Douglas Gregore6565622010-02-09 07:26:29 +00002951 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
Douglas Gregor85dabae2009-12-16 01:38:02 +00002952 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2953}
2954
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002955/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2956/// which enumerates all conversion functions and performs overload resolution
2957/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002959 const InitializedEntity &Entity,
2960 const InitializationKind &Kind,
2961 Expr *Initializer,
2962 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002963 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964
Douglas Gregor1b303932009-12-22 15:35:07 +00002965 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002966 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2967 QualType SourceType = Initializer->getType();
2968 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2969 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970
Douglas Gregor540c3b02009-12-14 17:27:33 +00002971 // Build the candidate set directly in the initialization sequence
2972 // structure, so that it will persist if we fail.
2973 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2974 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975
Douglas Gregor540c3b02009-12-14 17:27:33 +00002976 // Determine whether we are allowed to call explicit constructors or
2977 // explicit conversion operators.
2978 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979
Douglas Gregor540c3b02009-12-14 17:27:33 +00002980 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2981 // The type we're converting to is a class type. Enumerate its constructors
2982 // to see if there is a suitable conversion.
2983 CXXRecordDecl *DestRecordDecl
2984 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985
Douglas Gregord9848152010-04-26 14:36:57 +00002986 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00002988 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002989 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00002990 Con != ConEnd; ++Con) {
2991 NamedDecl *D = *Con;
2992 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993
Douglas Gregord9848152010-04-26 14:36:57 +00002994 // Find the constructor (which may be a template).
2995 CXXConstructorDecl *Constructor = 0;
2996 FunctionTemplateDecl *ConstructorTmpl
2997 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00002998 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00002999 Constructor = cast<CXXConstructorDecl>(
3000 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003001 else
Douglas Gregord9848152010-04-26 14:36:57 +00003002 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Douglas Gregord9848152010-04-26 14:36:57 +00003004 if (!Constructor->isInvalidDecl() &&
3005 Constructor->isConvertingConstructor(AllowExplicit)) {
3006 if (ConstructorTmpl)
3007 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3008 /*ExplicitArgs*/ 0,
3009 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003010 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003011 else
3012 S.AddOverloadCandidate(Constructor, FoundDecl,
3013 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003014 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003016 }
Douglas Gregord9848152010-04-26 14:36:57 +00003017 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003018 }
Eli Friedman78275202009-12-19 08:11:05 +00003019
3020 SourceLocation DeclLoc = Initializer->getLocStart();
3021
Douglas Gregor540c3b02009-12-14 17:27:33 +00003022 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3023 // The type we're converting from is a class type, enumerate its conversion
3024 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003025
Eli Friedman4afe9a32009-12-20 22:12:03 +00003026 // We can only enumerate the conversion functions for a complete type; if
3027 // the type isn't complete, simply skip this step.
3028 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3029 CXXRecordDecl *SourceRecordDecl
3030 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031
John McCallad371252010-01-20 00:46:10 +00003032 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003033 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003034 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003035 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003036 I != E; ++I) {
3037 NamedDecl *D = *I;
3038 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3039 if (isa<UsingShadowDecl>(D))
3040 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003041
Eli Friedman4afe9a32009-12-20 22:12:03 +00003042 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3043 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003044 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003045 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003046 else
John McCallda4458e2010-03-31 01:36:47 +00003047 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
Eli Friedman4afe9a32009-12-20 22:12:03 +00003049 if (AllowExplicit || !Conv->isExplicit()) {
3050 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003051 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003052 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003053 CandidateSet);
3054 else
John McCalla0296f72010-03-19 07:35:19 +00003055 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003056 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003057 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003058 }
3059 }
3060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003061
3062 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003063 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003064 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003065 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003066 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003067 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003068 Result);
3069 return;
3070 }
John McCall0d1da222010-01-12 00:44:57 +00003071
Douglas Gregor540c3b02009-12-14 17:27:33 +00003072 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003073 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074
Douglas Gregor540c3b02009-12-14 17:27:33 +00003075 if (isa<CXXConstructorDecl>(Function)) {
3076 // Add the user-defined conversion step. Any cv-qualification conversion is
3077 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003078 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003079 return;
3080 }
3081
3082 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003083 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003084 if (ConvType->getAs<RecordType>()) {
3085 // If we're converting to a class type, there may be an copy if
3086 // the resulting temporary object (possible to create an object of
3087 // a base class type). That copy is not a separate conversion, so
3088 // we just make a note of the actual destination type (possibly a
3089 // base class of the type returned by the conversion function) and
3090 // let the user-defined conversion step handle the conversion.
3091 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3092 return;
3093 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003094
Douglas Gregor5ab11652010-04-17 22:01:05 +00003095 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Douglas Gregor5ab11652010-04-17 22:01:05 +00003097 // If the conversion following the call to the conversion function
3098 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003099 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3100 Best->FinalConversion.Third) {
3101 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003102 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003103 ICS.Standard = Best->FinalConversion;
3104 Sequence.AddConversionSequenceStep(ICS, DestType);
3105 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003106}
3107
Douglas Gregore2f943b2011-02-22 18:29:51 +00003108/// \brief Determine whether we have compatible array types for the
3109/// purposes of GNU by-copy array initialization.
3110static bool hasCompatibleArrayTypes(ASTContext &Context,
3111 const ArrayType *Dest,
3112 const ArrayType *Source) {
3113 // If the source and destination array types are equivalent, we're
3114 // done.
3115 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3116 return true;
3117
3118 // Make sure that the element types are the same.
3119 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3120 return false;
3121
3122 // The only mismatch we allow is when the destination is an
3123 // incomplete array type and the source is a constant array type.
3124 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3125}
3126
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003127InitializationSequence::InitializationSequence(Sema &S,
3128 const InitializedEntity &Entity,
3129 const InitializationKind &Kind,
3130 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003131 unsigned NumArgs)
3132 : FailedCandidateSet(Kind.getLocation()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003135 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136 // The semantics of initializers are as follows. The destination type is
3137 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003139 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003140 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00003141 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003142
3143 if (DestType->isDependentType() ||
3144 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3145 SequenceKind = DependentSequence;
3146 return;
3147 }
3148
John McCalled75c092010-12-07 22:54:16 +00003149 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003150 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3151 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3152 if (Result.isInvalid()) {
3153 SetFailed(FK_ConversionFromPropertyFailed);
3154 return;
3155 }
3156 Args[I] = Result.take();
3157 }
John McCalled75c092010-12-07 22:54:16 +00003158
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003159 QualType SourceType;
3160 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003161 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003162 Initializer = Args[0];
3163 if (!isa<InitListExpr>(Initializer))
3164 SourceType = Initializer->getType();
3165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
3167 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003168 // list-initialized (8.5.4).
3169 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3170 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003171 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003174 // - If the destination type is a reference type, see 8.5.3.
3175 if (DestType->isReferenceType()) {
3176 // C++0x [dcl.init.ref]p1:
3177 // A variable declared to be a T& or T&&, that is, "reference to type T"
3178 // (8.3.2), shall be initialized by an object, or function, of type T or
3179 // by an object that can be converted into a T.
3180 // (Therefore, multiple arguments are not permitted.)
3181 if (NumArgs != 1)
3182 SetFailed(FK_TooManyInitsForReference);
3183 else
3184 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3185 return;
3186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003188 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003189 if (Kind.getKind() == InitializationKind::IK_Value ||
3190 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003191 TryValueInitialization(S, Entity, Kind, *this);
3192 return;
3193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194
Douglas Gregor85dabae2009-12-16 01:38:02 +00003195 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003196 if (Kind.getKind() == InitializationKind::IK_Default) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003197 TryDefaultInitialization(S, Entity, Kind, *this);
3198 return;
3199 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003200
John McCall66884dd2011-02-21 07:22:22 +00003201 // - If the destination type is an array of characters, an array of
3202 // char16_t, an array of char32_t, or an array of wchar_t, and the
3203 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003205 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003206 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3207 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
John McCall66884dd2011-02-21 07:22:22 +00003208 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3209 return;
3210 }
3211
Douglas Gregore2f943b2011-02-22 18:29:51 +00003212 // Note: as an GNU C extension, we allow initialization of an
3213 // array from a compound literal that creates an array of the same
3214 // type, so long as the initializer has no side effects.
3215 if (!S.getLangOptions().CPlusPlus && Initializer &&
3216 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3217 Initializer->getType()->isArrayType()) {
3218 const ArrayType *SourceAT
3219 = Context.getAsArrayType(Initializer->getType());
3220 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
3221 SetFailed(FK_ArrayTypeMismatch);
3222 else if (Initializer->HasSideEffects(S.Context))
3223 SetFailed(FK_NonConstantArrayInit);
3224 else {
3225 setSequenceKind(ArrayInit);
3226 AddArrayInitStep(DestType);
3227 }
3228 } else if (DestAT->getElementType()->isAnyCharacterType())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003229 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3230 else
3231 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003233 return;
3234 }
Eli Friedman78275202009-12-19 08:11:05 +00003235
3236 // Handle initialization in C
3237 if (!S.getLangOptions().CPlusPlus) {
3238 setSequenceKind(CAssignment);
3239 AddCAssignmentStep(DestType);
3240 return;
3241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 // - If the destination type is a (possibly cv-qualified) class type:
3244 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245 // - If the initialization is direct-initialization, or if it is
3246 // copy-initialization where the cv-unqualified version of the
3247 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003248 // class of the destination, constructors are considered. [...]
3249 if (Kind.getKind() == InitializationKind::IK_Direct ||
3250 (Kind.getKind() == InitializationKind::IK_Copy &&
3251 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3252 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00003254 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003255 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003256 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003258 // used) to a derived class thereof are enumerated as described in
3259 // 13.3.1.4, and the best one is chosen through overload resolution
3260 // (13.3).
3261 else
3262 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3263 return;
3264 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
Douglas Gregor85dabae2009-12-16 01:38:02 +00003266 if (NumArgs > 1) {
3267 SetFailed(FK_TooManyInitsForScalar);
3268 return;
3269 }
3270 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271
3272 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003273 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003274 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003275 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3276 return;
3277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003280 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003281 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003283 // destination type; no user-defined conversions are considered.
John McCallec6f4e92010-06-04 02:29:22 +00003284 if (S.TryImplicitConversion(*this, Entity, Initializer,
3285 /*SuppressUserConversions*/ true,
3286 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003287 /*InOverloadResolution*/ false,
3288 /*CStyle=*/Kind.isCStyleOrFunctionalCast()))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003289 {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003290 DeclAccessPair dap;
3291 if (Initializer->getType() == Context.OverloadTy &&
3292 !S.ResolveAddressOfOverloadedFunction(Initializer
3293 , DestType, false, dap))
Douglas Gregore81f58e2010-11-08 03:40:48 +00003294 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3295 else
3296 SetFailed(InitializationSequence::FK_ConversionFailed);
3297 }
John McCallec6f4e92010-06-04 02:29:22 +00003298 else
3299 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003300}
3301
3302InitializationSequence::~InitializationSequence() {
3303 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3304 StepEnd = Steps.end();
3305 Step != StepEnd; ++Step)
3306 Step->Destroy();
3307}
3308
3309//===----------------------------------------------------------------------===//
3310// Perform initialization
3311//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003313getAssignmentAction(const InitializedEntity &Entity) {
3314 switch(Entity.getKind()) {
3315 case InitializedEntity::EK_Variable:
3316 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003317 case InitializedEntity::EK_Exception:
3318 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003319 case InitializedEntity::EK_Delegation:
Douglas Gregore1314a62009-12-18 05:02:21 +00003320 return Sema::AA_Initializing;
3321
3322 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003323 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003324 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3325 return Sema::AA_Sending;
3326
Douglas Gregore1314a62009-12-18 05:02:21 +00003327 return Sema::AA_Passing;
3328
3329 case InitializedEntity::EK_Result:
3330 return Sema::AA_Returning;
3331
Douglas Gregore1314a62009-12-18 05:02:21 +00003332 case InitializedEntity::EK_Temporary:
3333 // FIXME: Can we tell apart casting vs. converting?
3334 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335
Douglas Gregore1314a62009-12-18 05:02:21 +00003336 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003337 case InitializedEntity::EK_ArrayElement:
3338 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003339 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003340 return Sema::AA_Initializing;
3341 }
3342
3343 return Sema::AA_Converting;
3344}
3345
Douglas Gregor95562572010-04-24 23:45:46 +00003346/// \brief Whether we should binding a created object as a temporary when
3347/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003348static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003349 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003350 case InitializedEntity::EK_ArrayElement:
3351 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003352 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003353 case InitializedEntity::EK_New:
3354 case InitializedEntity::EK_Variable:
3355 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003356 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003357 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003358 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003359 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003360 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003361
Douglas Gregore1314a62009-12-18 05:02:21 +00003362 case InitializedEntity::EK_Parameter:
3363 case InitializedEntity::EK_Temporary:
3364 return true;
3365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Douglas Gregore1314a62009-12-18 05:02:21 +00003367 llvm_unreachable("missed an InitializedEntity kind?");
3368}
3369
Douglas Gregor95562572010-04-24 23:45:46 +00003370/// \brief Whether the given entity, when initialized with an object
3371/// created for that initialization, requires destruction.
3372static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3373 switch (Entity.getKind()) {
3374 case InitializedEntity::EK_Member:
3375 case InitializedEntity::EK_Result:
3376 case InitializedEntity::EK_New:
3377 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003378 case InitializedEntity::EK_Delegation:
Douglas Gregor95562572010-04-24 23:45:46 +00003379 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003380 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003381 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382
Douglas Gregor95562572010-04-24 23:45:46 +00003383 case InitializedEntity::EK_Variable:
3384 case InitializedEntity::EK_Parameter:
3385 case InitializedEntity::EK_Temporary:
3386 case InitializedEntity::EK_ArrayElement:
3387 case InitializedEntity::EK_Exception:
3388 return true;
3389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
3391 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003392}
3393
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003394/// \brief Make a (potentially elidable) temporary copy of the object
3395/// provided by the given initializer by calling the appropriate copy
3396/// constructor.
3397///
3398/// \param S The Sema object used for type-checking.
3399///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003400/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003401/// the type of the initializer expression or a superclass thereof.
3402///
3403/// \param Enter The entity being initialized.
3404///
3405/// \param CurInit The initializer expression.
3406///
3407/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3408/// is permitted in C++03 (but not C++0x) when binding a reference to
3409/// an rvalue.
3410///
3411/// \returns An expression that copies the initializer expression into
3412/// a temporary object, or an error expression if a copy could not be
3413/// created.
John McCalldadc5752010-08-24 06:29:42 +00003414static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003415 QualType T,
3416 const InitializedEntity &Entity,
3417 ExprResult CurInit,
3418 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003419 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003420 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003422 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003423 Class = cast<CXXRecordDecl>(Record->getDecl());
3424 if (!Class)
3425 return move(CurInit);
3426
Douglas Gregor5d369002011-01-21 18:05:27 +00003427 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003428 // When certain criteria are met, an implementation is allowed to
3429 // omit the copy/move construction of a class object, even if the
3430 // copy/move constructor and/or destructor for the object have
3431 // side effects. [...]
3432 // - when a temporary class object that has not been bound to a
3433 // reference (12.2) would be copied/moved to a class object
3434 // with the same cv-unqualified type, the copy/move operation
3435 // can be omitted by constructing the temporary object
3436 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003438 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003439 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003441 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003442 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003443 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003444 switch (Entity.getKind()) {
3445 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003446 Loc = Entity.getReturnLoc();
3447 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448
Douglas Gregore1314a62009-12-18 05:02:21 +00003449 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003450 Loc = Entity.getThrowLoc();
3451 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Douglas Gregore1314a62009-12-18 05:02:21 +00003453 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003454 Loc = Entity.getDecl()->getLocation();
3455 break;
3456
Anders Carlsson0bd52402010-01-24 00:19:41 +00003457 case InitializedEntity::EK_ArrayElement:
3458 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003459 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003460 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003461 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003462 case InitializedEntity::EK_Base:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003463 case InitializedEntity::EK_Delegation:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003464 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003465 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003466 Loc = CurInitExpr->getLocStart();
3467 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003468 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003469
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003471 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3472 return move(CurInit);
3473
Douglas Gregorf282a762011-01-21 19:38:21 +00003474 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003475 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003476 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003477 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003478 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003479 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003480 // C++0x [dcl.init]p16, second bullet to class types, this
3481 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003482 CXXConstructorDecl *Constructor = 0;
3483
3484 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003485 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003486 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003487 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003488 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003489 continue;
3490
3491 DeclAccessPair FoundDecl
3492 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3493 S.AddOverloadCandidate(Constructor, FoundDecl,
3494 &CurInitExpr, 1, CandidateSet);
3495 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003497
3498 // Handle constructor templates.
3499 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3500 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003501 continue;
John McCalla0296f72010-03-19 07:35:19 +00003502
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003503 Constructor = cast<CXXConstructorDecl>(
3504 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003505 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003506 continue;
3507
3508 // FIXME: Do we need to limit this to copy-constructor-like
3509 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003510 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003511 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3512 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3513 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515
Douglas Gregore1314a62009-12-18 05:02:21 +00003516 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003517 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003518 case OR_Success:
3519 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
Douglas Gregore1314a62009-12-18 05:02:21 +00003521 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003522 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3523 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3524 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003525 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003526 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003527 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003528 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003529 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003530 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregore1314a62009-12-18 05:02:21 +00003532 case OR_Ambiguous:
3533 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003534 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003535 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003536 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003537 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538
Douglas Gregore1314a62009-12-18 05:02:21 +00003539 case OR_Deleted:
3540 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003541 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003542 << CurInitExpr->getSourceRange();
3543 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3544 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003545 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003546 }
3547
Douglas Gregor5ab11652010-04-17 22:01:05 +00003548 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003549 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003550 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003551
Anders Carlssona01874b2010-04-21 18:47:17 +00003552 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003553 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003554
3555 if (IsExtraneousCopy) {
3556 // If this is a totally extraneous copy for C++03 reference
3557 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00003558 // expression. We don't generate an (elided) copy operation here
3559 // because doing so would require us to pass down a flag to avoid
3560 // infinite recursion, where each step adds another extraneous,
3561 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003562
Douglas Gregor30b52772010-04-18 07:57:34 +00003563 // Instantiate the default arguments of any extra parameters in
3564 // the selected copy constructor, as if we were going to create a
3565 // proper call to the copy constructor.
3566 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3567 ParmVarDecl *Parm = Constructor->getParamDecl(I);
3568 if (S.RequireCompleteType(Loc, Parm->getType(),
3569 S.PDiag(diag::err_call_incomplete_argument)))
3570 break;
3571
3572 // Build the default argument expression; we don't actually care
3573 // if this succeeds or not, because this routine will complain
3574 // if there was a problem.
3575 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3576 }
3577
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003578 return S.Owned(CurInitExpr);
3579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Chandler Carruth30141632011-02-25 19:41:05 +00003581 S.MarkDeclarationReferenced(Loc, Constructor);
3582
Douglas Gregor5ab11652010-04-17 22:01:05 +00003583 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003584 // constructor call (we might have derived-to-base conversions, or
3585 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00003586 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00003587 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003588 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003589
Douglas Gregord0ace022010-04-25 00:55:24 +00003590 // Actually perform the constructor call.
3591 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00003592 move_arg(ConstructorArgs),
3593 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003594 CXXConstructExpr::CK_Complete,
3595 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregord0ace022010-04-25 00:55:24 +00003597 // If we're supposed to bind temporaries, do so.
3598 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3599 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3600 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003601}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003602
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003603void InitializationSequence::PrintInitLocationNote(Sema &S,
3604 const InitializedEntity &Entity) {
3605 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3606 if (Entity.getDecl()->getLocation().isInvalid())
3607 return;
3608
3609 if (Entity.getDecl()->getDeclName())
3610 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3611 << Entity.getDecl()->getDeclName();
3612 else
3613 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3614 }
3615}
3616
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618InitializationSequence::Perform(Sema &S,
3619 const InitializedEntity &Entity,
3620 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00003621 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003622 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623 if (SequenceKind == FailedSequence) {
3624 unsigned NumArgs = Args.size();
3625 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00003626 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003629 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003630 // If the declaration is a non-dependent, incomplete array type
3631 // that has an initializer, then its type will be completed once
3632 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003633 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003634 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003635 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003636 if (const IncompleteArrayType *ArrayT
3637 = S.Context.getAsIncompleteArrayType(DeclType)) {
3638 // FIXME: We don't currently have the ability to accurately
3639 // compute the length of an initializer list without
3640 // performing full type-checking of the initializer list
3641 // (since we have to determine where braces are implicitly
3642 // introduced and such). So, we fall back to making the array
3643 // type a dependently-sized array type with no specified
3644 // bound.
3645 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3646 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003647
Douglas Gregor51e77d52009-12-10 17:56:55 +00003648 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003649 if (DeclaratorDecl *DD = Entity.getDecl()) {
3650 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3651 TypeLoc TL = TInfo->getTypeLoc();
3652 if (IncompleteArrayTypeLoc *ArrayLoc
3653 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3654 Brackets = ArrayLoc->getBracketsRange();
3655 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003656 }
3657
3658 *ResultType
3659 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3660 /*NumElts=*/0,
3661 ArrayT->getSizeModifier(),
3662 ArrayT->getIndexTypeCVRQualifiers(),
3663 Brackets);
3664 }
3665
3666 }
3667 }
3668
Eli Friedmana553d4a2009-12-22 02:35:53 +00003669 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
John McCalldadc5752010-08-24 06:29:42 +00003670 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003671
Douglas Gregor0ab7af62010-02-05 07:56:11 +00003672 if (Args.size() == 0)
3673 return S.Owned((Expr *)0);
3674
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003675 unsigned NumArgs = Args.size();
3676 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3677 SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678 (Expr **)Args.release(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003679 NumArgs,
3680 SourceLocation()));
3681 }
3682
Douglas Gregor85dabae2009-12-16 01:38:02 +00003683 if (SequenceKind == NoInitialization)
3684 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003685
Douglas Gregor1b303932009-12-22 15:35:07 +00003686 QualType DestType = Entity.getType().getNonReferenceType();
3687 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003688 // the same as Entity.getDecl()->getType() in cases involving type merging,
3689 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003690 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003691 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003692 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693
John McCalldadc5752010-08-24 06:29:42 +00003694 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695
Douglas Gregor85dabae2009-12-16 01:38:02 +00003696 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003697
3698 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00003699 // grab the only argument out the Args and place it into the "current"
3700 // initializer.
3701 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003702 case SK_ResolveAddressOfOverloadedFunction:
3703 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003704 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003705 case SK_CastDerivedToBaseLValue:
3706 case SK_BindReference:
3707 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003708 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00003709 case SK_UserConversion:
3710 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003711 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00003712 case SK_QualificationConversionRValue:
3713 case SK_ConversionSequence:
3714 case SK_ListInitialization:
3715 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003716 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003717 case SK_ObjCObjectConversion:
3718 case SK_ArrayInit: {
Douglas Gregore1314a62009-12-18 05:02:21 +00003719 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00003720 CurInit = Args.get()[0];
3721 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00003722
3723 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00003724 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
3725 CurInit = S.ConvertPropertyForRValue(CurInit.take());
3726 if (CurInit.isInvalid())
3727 return ExprError();
3728 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003729 break;
John McCall34376a62010-12-04 03:47:34 +00003730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003731
Douglas Gregore1314a62009-12-18 05:02:21 +00003732 case SK_ConstructorInitialization:
3733 case SK_ZeroInitialization:
3734 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
3737 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003738 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003739 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003740 for (step_iterator Step = step_begin(), StepEnd = step_end();
3741 Step != StepEnd; ++Step) {
3742 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003743 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744
John Wiegley01296292011-04-08 18:41:53 +00003745 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003747 switch (Step->Kind) {
3748 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003750 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00003751 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00003752 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00003753 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00003754 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00003755 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003756 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003758 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003759 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003760 case SK_CastDerivedToBaseLValue: {
3761 // We have a derived-to-base cast that produces either an rvalue or an
3762 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763
John McCallcf142162010-08-07 06:22:56 +00003764 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003765
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003766 // Casts to inaccessible base classes are allowed with C-style casts.
3767 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3768 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00003769 CurInit.get()->getLocStart(),
3770 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00003771 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00003772 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregor88d292c2010-05-13 16:44:06 +00003774 if (S.BasePathInvolvesVirtualBase(BasePath)) {
3775 QualType T = SourceType;
3776 if (const PointerType *Pointer = T->getAs<PointerType>())
3777 T = Pointer->getPointeeType();
3778 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00003779 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003780 cast<CXXRecordDecl>(RecordTy->getDecl()));
3781 }
3782
John McCall2536c6d2010-08-25 10:28:54 +00003783 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003784 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003785 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003786 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003787 VK_XValue :
3788 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00003789 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
3790 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00003791 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00003792 CurInit.get(),
3793 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003794 break;
3795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003797 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00003798 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003799 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3800 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003801 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003802 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00003803 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003804 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00003805 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003806 }
Anders Carlssona91be642010-01-29 02:47:33 +00003807
John Wiegley01296292011-04-08 18:41:53 +00003808 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00003809 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003810 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3811 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00003812 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00003813 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00003814 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003817 // Reference binding does not have any corresponding ASTs.
3818
3819 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003820 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003821 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003822
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003823 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00003824
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003825 case SK_BindReferenceToTemporary:
Anders Carlsson3b227bd2010-02-03 16:38:03 +00003826 // Reference binding does not have any corresponding ASTs.
3827
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003828 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00003829 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00003830 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003831
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003832 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003834 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003836 /*IsExtraneousCopy=*/true);
3837 break;
3838
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003839 case SK_UserConversion: {
3840 // We have a user-defined conversion that invokes either a constructor
3841 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00003842 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00003843 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00003844 FunctionDecl *Fn = Step->Function.Function;
3845 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00003846 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00003847 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00003848 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003849 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003850 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00003851 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003852 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00003853
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003854 // Determine the arguments required to actually perform the constructor
3855 // call.
John Wiegley01296292011-04-08 18:41:53 +00003856 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003857 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00003858 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003859 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003860 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003861
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003862 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00003864 move_arg(ConstructorArgs),
3865 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00003866 CXXConstructExpr::CK_Complete,
3867 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003868 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003869 return ExprError();
John McCall760af172010-02-01 03:16:54 +00003870
Anders Carlssona01874b2010-04-21 18:47:17 +00003871 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00003872 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00003873 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874
John McCalle3027922010-08-25 11:45:40 +00003875 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003876 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3877 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3878 S.IsDerivedFrom(SourceType, Class))
3879 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880
Douglas Gregor95562572010-04-24 23:45:46 +00003881 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003882 } else {
3883 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00003884 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00003885 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00003886 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00003887 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00003888 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
3890 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003891 // derived-to-base conversion? I believe the answer is "no", because
3892 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00003893 ExprResult CurInitExprRes =
3894 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
3895 FoundFn, Conversion);
3896 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003897 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003898 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003900 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00003901 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003902 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00003903 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904
John McCalle3027922010-08-25 11:45:40 +00003905 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906
Douglas Gregor95562572010-04-24 23:45:46 +00003907 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909
3910 bool RequiresCopy = !IsCopy &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003911 getKind() != InitializationSequence::ReferenceBinding;
3912 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00003913 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00003914 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00003915 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00003916 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00003918 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00003919 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00003920 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00003921 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
3922 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00003923 }
3924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003926 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00003927 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00003928 CurInit.get()->getType(),
3929 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00003930 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003932 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003933 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3934 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003935
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003936 break;
3937 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003938
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003939 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003940 case SK_QualificationConversionXValue:
3941 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003942 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00003943 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003944 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003945 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003946 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00003947 VK_XValue :
3948 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00003949 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003950 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003951 }
3952
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003953 case SK_ConversionSequence: {
John Wiegley01296292011-04-08 18:41:53 +00003954 ExprResult CurInitExprRes =
3955 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
3956 getAssignmentAction(Entity),
3957 Kind.isCStyleOrFunctionalCast());
3958 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003959 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00003960 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003961 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00003962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003963
Douglas Gregor51e77d52009-12-10 17:56:55 +00003964 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00003965 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003966 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003967 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00003968 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003969
3970 CurInit.release();
3971 CurInit = S.Owned(InitList);
3972 break;
3973 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003974
3975 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00003976 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003977 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00003978 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003980 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00003981 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00003982 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
3983 ? Kind.getEqualLoc()
3984 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00003985
3986 if (Kind.getKind() == InitializationKind::IK_Default) {
3987 // Force even a trivial, implicit default constructor to be
3988 // semantically checked. We do this explicitly because we don't build
3989 // the definition for completely trivial constructors.
3990 CXXRecordDecl *ClassDecl = Constructor->getParent();
3991 assert(ClassDecl && "No parent class for constructor.");
3992 if (Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3993 ClassDecl->hasTrivialConstructor() && !Constructor->isUsed(false))
3994 S.DefineImplicitDefaultConstructor(Loc, Constructor);
3995 }
3996
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003997 // Determine the arguments required to actually perform the constructor
3998 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004000 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004001 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002
4003
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004004 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004005 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004006 (Kind.getKind() == InitializationKind::IK_Direct ||
4007 Kind.getKind() == InitializationKind::IK_Value)) {
4008 // An explicitly-constructed temporary, e.g., X(1, 2).
4009 unsigned NumExprs = ConstructorArgs.size();
4010 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004011 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004012 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004013
Douglas Gregor2b88c112010-09-08 00:15:04 +00004014 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4015 if (!TSInfo)
4016 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004018 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4019 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004020 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004022 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004023 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004024 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004025 } else {
4026 CXXConstructExpr::ConstructionKind ConstructKind =
4027 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004029 if (Entity.getKind() == InitializedEntity::EK_Base) {
4030 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004032 CXXConstructExpr::CK_NonVirtualBase;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033 }
4034
Chandler Carruth01718152010-10-25 08:47:36 +00004035 // Only get the parenthesis range if it is a direct construction.
4036 SourceRange parenRange =
4037 Kind.getKind() == InitializationKind::IK_Direct ?
4038 Kind.getParenRange() : SourceRange();
4039
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004040 // If the entity allows NRVO, mark the construction as elidable
4041 // unconditionally.
4042 if (Entity.allowsNRVO())
4043 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4044 Constructor, /*Elidable=*/true,
4045 move_arg(ConstructorArgs),
4046 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004047 ConstructKind,
4048 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004049 else
4050 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004051 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004052 move_arg(ConstructorArgs),
4053 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004054 ConstructKind,
4055 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004056 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004057 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004058 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004059
4060 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004061 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004062 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004063 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004064
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004065 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004066 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004068 break;
4069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004071 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004072 step_iterator NextStep = Step;
4073 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004075 NextStep->Kind == SK_ConstructorInitialization) {
4076 // The need for zero-initialization is recorded directly into
4077 // the call to the object's constructor within the next step.
4078 ConstructorInitRequiresZeroInit = true;
4079 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4080 S.getLangOptions().CPlusPlus &&
4081 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004082 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4083 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004085 Kind.getRange().getBegin());
4086
4087 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4088 TSInfo->getType().getNonLValueExprType(S.Context),
4089 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004090 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004091 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004092 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004093 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004094 break;
4095 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004096
4097 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004098 QualType SourceType = CurInit.get()->getType();
4099 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004100 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004101 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4102 if (Result.isInvalid())
4103 return ExprError();
4104 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004105
4106 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004107 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004108 if (ConvTy != Sema::Compatible &&
4109 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004110 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004111 == Sema::Compatible)
4112 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004113 if (CurInitExprRes.isInvalid())
4114 return ExprError();
4115 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004116
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004117 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004118 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4119 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004120 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004121 getAssignmentAction(Entity),
4122 &Complained)) {
4123 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004124 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004125 } else if (Complained)
4126 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004127 break;
4128 }
Eli Friedman78275202009-12-19 08:11:05 +00004129
4130 case SK_StringInit: {
4131 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004132 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004133 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004134 break;
4135 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004136
4137 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004138 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004139 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004140 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004141 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004142
4143 case SK_ArrayInit:
4144 // Okay: we checked everything before creating this step. Note that
4145 // this is a GNU extension.
4146 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004147 << Step->Type << CurInit.get()->getType()
4148 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004149
4150 // If the destination type is an incomplete array type, update the
4151 // type accordingly.
4152 if (ResultType) {
4153 if (const IncompleteArrayType *IncompleteDest
4154 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4155 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004156 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004157 *ResultType = S.Context.getConstantArrayType(
4158 IncompleteDest->getElementType(),
4159 ConstantSource->getSize(),
4160 ArrayType::Normal, 0);
4161 }
4162 }
4163 }
4164
4165 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004166 }
4167 }
John McCall1f425642010-11-11 03:21:53 +00004168
4169 // Diagnose non-fatal problems with the completed initialization.
4170 if (Entity.getKind() == InitializedEntity::EK_Member &&
4171 cast<FieldDecl>(Entity.getDecl())->isBitField())
4172 S.CheckBitFieldInitialization(Kind.getLocation(),
4173 cast<FieldDecl>(Entity.getDecl()),
4174 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004176 return move(CurInit);
4177}
4178
4179//===----------------------------------------------------------------------===//
4180// Diagnose initialization failures
4181//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004183 const InitializedEntity &Entity,
4184 const InitializationKind &Kind,
4185 Expr **Args, unsigned NumArgs) {
4186 if (SequenceKind != FailedSequence)
4187 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
Douglas Gregor1b303932009-12-22 15:35:07 +00004189 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004190 switch (Failure) {
4191 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004192 // FIXME: Customize for the initialized entity?
4193 if (NumArgs == 0)
4194 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4195 << DestType.getNonReferenceType();
4196 else // FIXME: diagnostic below could be better!
4197 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4198 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004199 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004201 case FK_ArrayNeedsInitList:
4202 case FK_ArrayNeedsInitListOrStringLiteral:
4203 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4204 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4205 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206
Douglas Gregore2f943b2011-02-22 18:29:51 +00004207 case FK_ArrayTypeMismatch:
4208 case FK_NonConstantArrayInit:
4209 S.Diag(Kind.getLocation(),
4210 (Failure == FK_ArrayTypeMismatch
4211 ? diag::err_array_init_different_type
4212 : diag::err_array_init_non_constant_array))
4213 << DestType.getNonReferenceType()
4214 << Args[0]->getType()
4215 << Args[0]->getSourceRange();
4216 break;
4217
John McCall16df1e52010-03-30 21:47:33 +00004218 case FK_AddressOfOverloadFailed: {
4219 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004221 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004222 true,
4223 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004224 break;
John McCall16df1e52010-03-30 21:47:33 +00004225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004227 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004228 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004229 switch (FailedOverloadResult) {
4230 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004231 if (Failure == FK_UserConversionOverloadFailed)
4232 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4233 << Args[0]->getType() << DestType
4234 << Args[0]->getSourceRange();
4235 else
4236 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4237 << DestType << Args[0]->getType()
4238 << Args[0]->getSourceRange();
4239
John McCall5c32be02010-08-24 20:38:10 +00004240 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004243 case OR_No_Viable_Function:
4244 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4245 << Args[0]->getType() << DestType.getNonReferenceType()
4246 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004247 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004250 case OR_Deleted: {
4251 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4252 << Args[0]->getType() << DestType.getNonReferenceType()
4253 << Args[0]->getSourceRange();
4254 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004255 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004256 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4257 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004258 if (Ovl == OR_Deleted) {
4259 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4260 << Best->Function->isDeleted();
4261 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004262 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004263 }
4264 break;
4265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004268 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004269 break;
4270 }
4271 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 case FK_NonConstLValueReferenceBindingToTemporary:
4274 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004276 Failure == FK_NonConstLValueReferenceBindingToTemporary
4277 ? diag::err_lvalue_reference_bind_to_temporary
4278 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004279 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 << DestType.getNonReferenceType()
4281 << Args[0]->getType()
4282 << Args[0]->getSourceRange();
4283 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 case FK_RValueReferenceBindingToLValue:
4286 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004287 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004288 << Args[0]->getSourceRange();
4289 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004291 case FK_ReferenceInitDropsQualifiers:
4292 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4293 << DestType.getNonReferenceType()
4294 << Args[0]->getType()
4295 << Args[0]->getSourceRange();
4296 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 case FK_ReferenceInitFailed:
4299 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4300 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004301 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004302 << Args[0]->getType()
4303 << Args[0]->getSourceRange();
4304 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305
Douglas Gregorb491ed32011-02-19 21:32:49 +00004306 case FK_ConversionFailed: {
4307 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004308 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4309 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004310 << DestType
John McCall086a4642010-11-24 05:12:34 +00004311 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004312 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004313 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004314 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004315 }
John Wiegley01296292011-04-08 18:41:53 +00004316
4317 case FK_ConversionFromPropertyFailed:
4318 // No-op. This error has already been reported.
4319 break;
4320
Douglas Gregor51e77d52009-12-10 17:56:55 +00004321 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004322 SourceRange R;
4323
4324 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004325 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004326 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004328 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004329
Douglas Gregor8ec51732010-09-08 21:40:08 +00004330 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4331 if (Kind.isCStyleOrFunctionalCast())
4332 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4333 << R;
4334 else
4335 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4336 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004337 break;
4338 }
4339
4340 case FK_ReferenceBindingToInitList:
4341 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4342 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4343 break;
4344
4345 case FK_InitListBadDestinationType:
4346 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4347 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4348 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004350 case FK_ConstructorOverloadFailed: {
4351 SourceRange ArgsRange;
4352 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004354 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004356 // FIXME: Using "DestType" for the entity we're printing is probably
4357 // bad.
4358 switch (FailedOverloadResult) {
4359 case OR_Ambiguous:
4360 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4361 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004362 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4363 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004364 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004366 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004367 if (Kind.getKind() == InitializationKind::IK_Default &&
4368 (Entity.getKind() == InitializedEntity::EK_Base ||
4369 Entity.getKind() == InitializedEntity::EK_Member) &&
4370 isa<CXXConstructorDecl>(S.CurContext)) {
4371 // This is implicit default initialization of a member or
4372 // base within a constructor. If no viable function was
4373 // found, notify the user that she needs to explicitly
4374 // initialize this base/member.
4375 CXXConstructorDecl *Constructor
4376 = cast<CXXConstructorDecl>(S.CurContext);
4377 if (Entity.getKind() == InitializedEntity::EK_Base) {
4378 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4379 << Constructor->isImplicit()
4380 << S.Context.getTypeDeclType(Constructor->getParent())
4381 << /*base=*/0
4382 << Entity.getType();
4383
4384 RecordDecl *BaseDecl
4385 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4386 ->getDecl();
4387 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4388 << S.Context.getTagDeclType(BaseDecl);
4389 } else {
4390 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4391 << Constructor->isImplicit()
4392 << S.Context.getTypeDeclType(Constructor->getParent())
4393 << /*member=*/1
4394 << Entity.getName();
4395 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4396
4397 if (const RecordType *Record
4398 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004400 diag::note_previous_decl)
4401 << S.Context.getTagDeclType(Record->getDecl());
4402 }
4403 break;
4404 }
4405
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004406 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4407 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004408 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004409 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004411 case OR_Deleted: {
4412 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4413 << true << DestType << ArgsRange;
4414 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004415 OverloadingResult Ovl
4416 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004417 if (Ovl == OR_Deleted) {
4418 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4419 << Best->Function->isDeleted();
4420 } else {
4421 llvm_unreachable("Inconsistent overload resolution?");
4422 }
4423 break;
4424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004426 case OR_Success:
4427 llvm_unreachable("Conversion did not fail!");
4428 break;
4429 }
4430 break;
4431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432
Douglas Gregor85dabae2009-12-16 01:38:02 +00004433 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004434 if (Entity.getKind() == InitializedEntity::EK_Member &&
4435 isa<CXXConstructorDecl>(S.CurContext)) {
4436 // This is implicit default-initialization of a const member in
4437 // a constructor. Complain that it needs to be explicitly
4438 // initialized.
4439 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4440 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4441 << Constructor->isImplicit()
4442 << S.Context.getTypeDeclType(Constructor->getParent())
4443 << /*const=*/1
4444 << Entity.getName();
4445 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4446 << Entity.getName();
4447 } else {
4448 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4449 << DestType << (bool)DestType->getAs<RecordType>();
4450 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004451 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004453 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004455 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004459 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004460 return true;
4461}
Douglas Gregore1314a62009-12-18 05:02:21 +00004462
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004463void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4464 switch (SequenceKind) {
4465 case FailedSequence: {
4466 OS << "Failed sequence: ";
4467 switch (Failure) {
4468 case FK_TooManyInitsForReference:
4469 OS << "too many initializers for reference";
4470 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004472 case FK_ArrayNeedsInitList:
4473 OS << "array requires initializer list";
4474 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004476 case FK_ArrayNeedsInitListOrStringLiteral:
4477 OS << "array requires initializer list or string literal";
4478 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479
Douglas Gregore2f943b2011-02-22 18:29:51 +00004480 case FK_ArrayTypeMismatch:
4481 OS << "array type mismatch";
4482 break;
4483
4484 case FK_NonConstantArrayInit:
4485 OS << "non-constant array initializer";
4486 break;
4487
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004488 case FK_AddressOfOverloadFailed:
4489 OS << "address of overloaded function failed";
4490 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004492 case FK_ReferenceInitOverloadFailed:
4493 OS << "overload resolution for reference initialization failed";
4494 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004495
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004496 case FK_NonConstLValueReferenceBindingToTemporary:
4497 OS << "non-const lvalue reference bound to temporary";
4498 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004500 case FK_NonConstLValueReferenceBindingToUnrelated:
4501 OS << "non-const lvalue reference bound to unrelated type";
4502 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004504 case FK_RValueReferenceBindingToLValue:
4505 OS << "rvalue reference bound to an lvalue";
4506 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004508 case FK_ReferenceInitDropsQualifiers:
4509 OS << "reference initialization drops qualifiers";
4510 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004512 case FK_ReferenceInitFailed:
4513 OS << "reference initialization failed";
4514 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004516 case FK_ConversionFailed:
4517 OS << "conversion failed";
4518 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
John Wiegley01296292011-04-08 18:41:53 +00004520 case FK_ConversionFromPropertyFailed:
4521 OS << "conversion from property failed";
4522 break;
4523
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004524 case FK_TooManyInitsForScalar:
4525 OS << "too many initializers for scalar";
4526 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004528 case FK_ReferenceBindingToInitList:
4529 OS << "referencing binding to initializer list";
4530 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004532 case FK_InitListBadDestinationType:
4533 OS << "initializer list for non-aggregate, non-scalar type";
4534 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004536 case FK_UserConversionOverloadFailed:
4537 OS << "overloading failed for user-defined conversion";
4538 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004540 case FK_ConstructorOverloadFailed:
4541 OS << "constructor overloading failed";
4542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004544 case FK_DefaultInitOfConst:
4545 OS << "default initialization of a const variable";
4546 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004548 case FK_Incomplete:
4549 OS << "initialization of incomplete type";
4550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004552 OS << '\n';
4553 return;
4554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004556 case DependentSequence:
4557 OS << "Dependent sequence: ";
4558 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004560 case UserDefinedConversion:
4561 OS << "User-defined conversion sequence: ";
4562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004564 case ConstructorInitialization:
4565 OS << "Constructor initialization sequence: ";
4566 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004568 case ReferenceBinding:
4569 OS << "Reference binding: ";
4570 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004572 case ListInitialization:
4573 OS << "List initialization: ";
4574 break;
4575
4576 case ZeroInitialization:
4577 OS << "Zero initialization\n";
4578 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004579
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004580 case NoInitialization:
4581 OS << "No initialization\n";
4582 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004584 case StandardConversion:
4585 OS << "Standard conversion: ";
4586 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004588 case CAssignment:
4589 OS << "C assignment: ";
4590 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004592 case StringInit:
4593 OS << "String initialization: ";
4594 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004595
4596 case ArrayInit:
4597 OS << "Array initialization: ";
4598 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004601 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4602 if (S != step_begin()) {
4603 OS << " -> ";
4604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004606 switch (S->Kind) {
4607 case SK_ResolveAddressOfOverloadedFunction:
4608 OS << "resolve address of overloaded function";
4609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004611 case SK_CastDerivedToBaseRValue:
4612 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4613 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004615 case SK_CastDerivedToBaseXValue:
4616 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
4617 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004619 case SK_CastDerivedToBaseLValue:
4620 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004623 case SK_BindReference:
4624 OS << "bind reference to lvalue";
4625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004627 case SK_BindReferenceToTemporary:
4628 OS << "bind reference to a temporary";
4629 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004630
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004631 case SK_ExtraneousCopyToTemporary:
4632 OS << "extraneous C++03 copy to temporary";
4633 break;
4634
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004635 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00004636 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004637 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004638
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004639 case SK_QualificationConversionRValue:
4640 OS << "qualification conversion (rvalue)";
4641
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004642 case SK_QualificationConversionXValue:
4643 OS << "qualification conversion (xvalue)";
4644
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004645 case SK_QualificationConversionLValue:
4646 OS << "qualification conversion (lvalue)";
4647 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004649 case SK_ConversionSequence:
4650 OS << "implicit conversion sequence (";
4651 S->ICS->DebugPrint(); // FIXME: use OS
4652 OS << ")";
4653 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004655 case SK_ListInitialization:
4656 OS << "list initialization";
4657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004659 case SK_ConstructorInitialization:
4660 OS << "constructor initialization";
4661 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004663 case SK_ZeroInitialization:
4664 OS << "zero initialization";
4665 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004666
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004667 case SK_CAssignment:
4668 OS << "C assignment";
4669 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004670
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004671 case SK_StringInit:
4672 OS << "string initialization";
4673 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004674
4675 case SK_ObjCObjectConversion:
4676 OS << "Objective-C object conversion";
4677 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004678
4679 case SK_ArrayInit:
4680 OS << "array initialization";
4681 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004682 }
4683 }
4684}
4685
4686void InitializationSequence::dump() const {
4687 dump(llvm::errs());
4688}
4689
Douglas Gregore1314a62009-12-18 05:02:21 +00004690//===----------------------------------------------------------------------===//
4691// Initialization helper functions
4692//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004693ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00004694Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4695 SourceLocation EqualLoc,
John McCalldadc5752010-08-24 06:29:42 +00004696 ExprResult Init) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004697 if (Init.isInvalid())
4698 return ExprError();
4699
John McCall1f425642010-11-11 03:21:53 +00004700 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00004701 assert(InitE && "No initialization expression?");
4702
4703 if (EqualLoc.isInvalid())
4704 EqualLoc = InitE->getLocStart();
4705
4706 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4707 EqualLoc);
4708 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4709 Init.release();
John McCallfaf5fb42010-08-26 23:41:50 +00004710 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00004711}