blob: a61b1d11fc5a9542eda2a154a41a4342150c6f1a [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//
Rafael Espindola699fc4d2011-07-14 22:58:04 +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.
Chris Lattner0cb78032009-02-24 22:27:37 +000013//
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"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000198 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000200 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000203 void CheckReferenceType(const InitializedEntity &Entity,
204 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000205 unsigned &Index,
206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000208 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000209 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000212 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000213 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000214 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000215 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000217 unsigned &StructuredIndex,
218 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000219 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000220 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000221 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000225 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000226 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000227 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000228 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 RecordDecl::field_iterator *NextField,
230 llvm::APSInt *NextElementIndex,
231 unsigned &Index,
232 InitListExpr *StructuredList,
233 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000234 bool FinishSubobjectInit,
235 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000236 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
237 QualType CurrentObjectType,
238 InitListExpr *StructuredList,
239 unsigned StructuredIndex,
240 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000241 void UpdateStructuredListElement(InitListExpr *StructuredList,
242 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 Expr *expr);
244 int numArrayElements(QualType DeclType);
245 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000246
Douglas Gregor2bb07652009-12-22 00:05:34 +0000247 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
248 const InitializedEntity &ParentEntity,
249 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000250 void FillInValueInitializations(const InitializedEntity &Entity,
251 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000252public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000253 InitListChecker(Sema &S, const InitializedEntity &Entity,
254 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000255 bool HadError() { return hadError; }
256
257 // @brief Retrieves the fully-structured initializer list used for
258 // semantic analysis and code generation.
259 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
260};
Chris Lattner9ececce2009-02-24 22:48:58 +0000261} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000262
Douglas Gregor2bb07652009-12-22 00:05:34 +0000263void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
264 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000265 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000266 bool &RequiresSecondPass) {
267 SourceLocation Loc = ILE->getSourceRange().getBegin();
268 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000270 = InitializedEntity::InitializeMember(Field, &ParentEntity);
271 if (Init >= NumInits || !ILE->getInit(Init)) {
272 // FIXME: We probably don't need to handle references
273 // specially here, since value-initialization of references is
274 // handled in InitializationSequence.
275 if (Field->getType()->isReferenceType()) {
276 // C++ [dcl.init.aggr]p9:
277 // If an incomplete or empty initializer-list leaves a
278 // member of reference type uninitialized, the program is
279 // ill-formed.
280 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
281 << Field->getType()
282 << ILE->getSyntacticForm()->getSourceRange();
283 SemaRef.Diag(Field->getLocation(),
284 diag::note_uninit_reference_member);
285 hadError = true;
286 return;
287 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288
Douglas Gregor2bb07652009-12-22 00:05:34 +0000289 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
290 true);
291 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
292 if (!InitSeq) {
293 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
294 hadError = true;
295 return;
296 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000297
John McCalldadc5752010-08-24 06:29:42 +0000298 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000299 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000300 if (MemberInit.isInvalid()) {
301 hadError = true;
302 return;
303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000304
Douglas Gregor2bb07652009-12-22 00:05:34 +0000305 if (hadError) {
306 // Do nothing
307 } else if (Init < NumInits) {
308 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000309 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000310 // Value-initialization requires a constructor call, so
311 // extend the initializer list to include the constructor
312 // call and make a note that we'll need to take another pass
313 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000314 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000315 RequiresSecondPass = true;
316 }
317 } else if (InitListExpr *InnerILE
318 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000319 FillInValueInitializations(MemberEntity, InnerILE,
320 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321}
322
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000323/// Recursively replaces NULL values within the given initializer list
324/// with expressions that perform value-initialization of the
325/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326void
Douglas Gregor723796a2009-12-16 06:35:08 +0000327InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
328 InitListExpr *ILE,
329 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000330 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000331 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000332 SourceLocation Loc = ILE->getSourceRange().getBegin();
333 if (ILE->getSyntacticForm())
334 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000335
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000336 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000337 if (RType->getDecl()->isUnion() &&
338 ILE->getInitializedFieldInUnion())
339 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
340 Entity, ILE, RequiresSecondPass);
341 else {
342 unsigned Init = 0;
343 for (RecordDecl::field_iterator
344 Field = RType->getDecl()->field_begin(),
345 FieldEnd = RType->getDecl()->field_end();
346 Field != FieldEnd; ++Field) {
347 if (Field->isUnnamedBitfield())
348 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000351 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000352
353 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
354 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000355 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000356
Douglas Gregor2bb07652009-12-22 00:05:34 +0000357 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000358
Douglas Gregor2bb07652009-12-22 00:05:34 +0000359 // Only look at the first initialization of a union.
360 if (RType->getDecl()->isUnion())
361 break;
362 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000363 }
364
365 return;
Mike Stump11289f42009-09-09 15:08:12 +0000366 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000367
368 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Douglas Gregor723796a2009-12-16 06:35:08 +0000370 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000371 unsigned NumInits = ILE->getNumInits();
372 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000373 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000374 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000375 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
376 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000379 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000380 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000383 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000384 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000385 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000386
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000388 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000389 if (hadError)
390 return;
391
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000392 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
393 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000394 ElementEntity.setElementIndex(Init);
395
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000397 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
398 true);
399 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
400 if (!InitSeq) {
401 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000402 hadError = true;
403 return;
404 }
405
John McCalldadc5752010-08-24 06:29:42 +0000406 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000407 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000409 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000410 return;
411 }
412
413 if (hadError) {
414 // Do nothing
415 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000416 // For arrays, just set the expression used for value-initialization
417 // of the "holes" in the array.
418 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
419 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
420 else
421 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000422 } else {
423 // For arrays, just set the expression used for value-initialization
424 // of the rest of elements and exit.
425 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
426 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
427 return;
428 }
429
Sebastian Redld201edf2011-06-05 13:59:11 +0000430 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000431 // Value-initialization requires a constructor call, so
432 // extend the initializer list to include the constructor
433 // call and make a note that we'll need to take another pass
434 // through the initializer list.
435 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
436 RequiresSecondPass = true;
437 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000438 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000439 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000440 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
441 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000442 }
443}
444
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000445
Douglas Gregor723796a2009-12-16 06:35:08 +0000446InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
447 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000448 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000449 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000450
Eli Friedman23a9e312008-05-19 19:16:24 +0000451 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000452 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000453 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000454 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000455 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000456 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000457 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000458
Douglas Gregor723796a2009-12-16 06:35:08 +0000459 if (!hadError) {
460 bool RequiresSecondPass = false;
461 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000462 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000464 RequiresSecondPass);
465 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000466}
467
468int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000469 // FIXME: use a proper constant
470 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000471 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000472 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000473 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
474 }
475 return maxElements;
476}
477
478int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000479 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000480 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000481 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000482 Field = structDecl->field_begin(),
483 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000484 Field != FieldEnd; ++Field) {
485 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
486 ++InitializableMembers;
487 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000488 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000489 return std::min(InitializableMembers, 1);
490 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000491}
492
Anders Carlsson6cabf312010-01-23 23:23:01 +0000493void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000494 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000495 QualType T, unsigned &Index,
496 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000497 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000498 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000499
Steve Narofff8ecff22008-05-01 22:18:59 +0000500 if (T->isArrayType())
501 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000502 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000503 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000504 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000505 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000506 else
507 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000508
Eli Friedmane0f832b2008-05-25 13:49:22 +0000509 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000510 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000511 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000512 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000513 hadError = true;
514 return;
515 }
516
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000517 // Build a structured initializer list corresponding to this subobject.
518 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000519 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
520 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000521 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
522 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000523 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000524
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000525 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000526 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000528 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000529 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000530 StructuredSubobjectInitIndex);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000531 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000532 StructuredSubobjectInitList->setType(T);
533
Douglas Gregor5741efb2009-03-01 17:12:46 +0000534 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000535 // range corresponds with the end of the last initializer it used.
536 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000537 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000538 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
539 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
Tanya Lattner5029d562010-03-07 04:17:15 +0000542 // Warn about missing braces.
543 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000544 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
545 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000546 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000548 "{")
549 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000550 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000551 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000552 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000553}
554
Anders Carlsson6cabf312010-01-23 23:23:01 +0000555void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000556 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000557 unsigned &Index,
558 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000559 unsigned &StructuredIndex,
560 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000561 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000562 SyntacticToSemantic[IList] = StructuredList;
563 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000565 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000566 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
567 IList->setType(ExprTy);
568 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000569 if (hadError)
570 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000571
Eli Friedman85f54972008-05-25 13:22:35 +0000572 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000573 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000574 if (StructuredIndex == 1 &&
575 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000576 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000577 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000578 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000579 hadError = true;
580 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000581 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000582 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000583 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000584 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000585 // Don't complain for incomplete types, since we'll get an error
586 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000587 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000588 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000589 CurrentObjectType->isArrayType()? 0 :
590 CurrentObjectType->isVectorType()? 1 :
591 CurrentObjectType->isScalarType()? 2 :
592 CurrentObjectType->isUnionType()? 3 :
593 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000594
595 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000596 if (SemaRef.getLangOptions().CPlusPlus) {
597 DK = diag::err_excess_initializers;
598 hadError = true;
599 }
Nate Begeman425038c2009-07-07 21:53:06 +0000600 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
601 DK = diag::err_excess_initializers;
602 hadError = true;
603 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000604
Chris Lattnerb0912a52009-02-24 22:50:46 +0000605 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000606 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000607 }
608 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000609
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000610 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000612 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000613 << FixItHint::CreateRemoval(IList->getLocStart())
614 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000615}
616
Anders Carlsson6cabf312010-01-23 23:23:01 +0000617void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000618 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000619 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000620 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000621 unsigned &Index,
622 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000623 unsigned &StructuredIndex,
624 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000625 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000626 CheckScalarType(Entity, IList, DeclType, Index,
627 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000628 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000629 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000630 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000631 } else if (DeclType->isAggregateType()) {
632 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000633 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000634 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000636 StructuredList, StructuredIndex,
637 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000638 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000639 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000640 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000641 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000643 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000644 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000645 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000646 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000647 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
648 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000650 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000651 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000652 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000653 } else if (DeclType->isRecordType()) {
654 // C++ [dcl.init]p14:
655 // [...] If the class is an aggregate (8.5.1), and the initializer
656 // is a brace-enclosed list, see 8.5.1.
657 //
658 // Note: 8.5.1 is handled below; here, we diagnose the case where
659 // we have an initializer list and a destination type that is not
660 // an aggregate.
661 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000662 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000663 << DeclType << IList->getSourceRange();
664 hadError = true;
665 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000666 CheckReferenceType(Entity, IList, DeclType, Index,
667 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000668 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000669 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
670 << DeclType;
671 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000672 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000673 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
674 << DeclType;
675 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000676 }
677}
678
Anders Carlsson6cabf312010-01-23 23:23:01 +0000679void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000680 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000681 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000682 unsigned &Index,
683 InitListExpr *StructuredList,
684 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000685 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000686 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
687 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000688 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000689 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000690 = getStructuredSubobjectInit(IList, Index, ElemType,
691 StructuredList, StructuredIndex,
692 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000693 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000694 newStructuredList, newStructuredIndex);
695 ++StructuredIndex;
696 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000697 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000698 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000699 return CheckScalarType(Entity, IList, ElemType, Index,
700 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000701 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000702 return CheckReferenceType(Entity, IList, ElemType, Index,
703 StructuredList, StructuredIndex);
704 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000705
John McCall5decec92011-02-21 07:57:55 +0000706 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
707 // arrayType can be incomplete if we're initializing a flexible
708 // array member. There's nothing we can do with the completed
709 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000710
John McCall5decec92011-02-21 07:57:55 +0000711 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
712 CheckStringInit(Str, ElemType, arrayType, SemaRef);
713 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000714 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000715 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000716 }
John McCall5decec92011-02-21 07:57:55 +0000717
718 // Fall through for subaggregate initialization.
719
720 } else if (SemaRef.getLangOptions().CPlusPlus) {
721 // C++ [dcl.init.aggr]p12:
722 // All implicit type conversions (clause 4) are considered when
Rafael Espindola699fc4d2011-07-14 22:58:04 +0000723 // initializing the aggregate member with an ini- tializer from
John McCall5decec92011-02-21 07:57:55 +0000724 // an initializer-list. If the initializer can initialize a
725 // member, the member is initialized. [...]
726
727 // FIXME: Better EqualLoc?
728 InitializationKind Kind =
729 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
730 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
731
732 if (Seq) {
733 ExprResult Result =
734 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
735 if (Result.isInvalid())
736 hadError = true;
737
738 UpdateStructuredListElement(StructuredList, StructuredIndex,
739 Result.takeAs<Expr>());
740 ++Index;
741 return;
742 }
743
744 // Fall through for subaggregate initialization
745 } else {
746 // C99 6.7.8p13:
747 //
748 // The initializer for a structure or union object that has
749 // automatic storage duration shall be either an initializer
750 // list as described below, or a single expression that has
751 // compatible structure or union type. In the latter case, the
752 // initial value of the object, including unnamed members, is
753 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000754 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000755 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000756 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000757 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000758 if (ExprRes.isInvalid())
759 hadError = true;
760 else {
761 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
762 if (ExprRes.isInvalid())
763 hadError = true;
764 }
765 UpdateStructuredListElement(StructuredList, StructuredIndex,
766 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000767 ++Index;
768 return;
769 }
John Wiegley01296292011-04-08 18:41:53 +0000770 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000771 // Fall through for subaggregate initialization
772 }
773
774 // C++ [dcl.init.aggr]p12:
775 //
776 // [...] Otherwise, if the member is itself a non-empty
777 // subaggregate, brace elision is assumed and the initializer is
778 // considered for the initialization of the first member of
779 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000780 if (!SemaRef.getLangOptions().OpenCL &&
781 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000782 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
783 StructuredIndex);
784 ++StructuredIndex;
785 } else {
786 // We cannot initialize this element, so let
787 // PerformCopyInitialization produce the appropriate diagnostic.
788 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000789 SemaRef.Owned(expr),
790 /*TopLevelOfInitList=*/true);
John McCall5decec92011-02-21 07:57:55 +0000791 hadError = true;
792 ++Index;
793 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000794 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000795}
796
Anders Carlsson6cabf312010-01-23 23:23:01 +0000797void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000798 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000799 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000800 InitListExpr *StructuredList,
801 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000802 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000803 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000804 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000805 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000806 ++Index;
807 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000808 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000809 }
John McCall643169b2010-11-11 00:46:36 +0000810
811 Expr *expr = IList->getInit(Index);
812 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
813 SemaRef.Diag(SubIList->getLocStart(),
814 diag::warn_many_braces_around_scalar_init)
815 << SubIList->getSourceRange();
816
817 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
818 StructuredIndex);
819 return;
820 } else if (isa<DesignatedInitExpr>(expr)) {
821 SemaRef.Diag(expr->getSourceRange().getBegin(),
822 diag::err_designator_for_scalar_init)
823 << DeclType << expr->getSourceRange();
824 hadError = true;
825 ++Index;
826 ++StructuredIndex;
827 return;
828 }
829
830 ExprResult Result =
831 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000832 SemaRef.Owned(expr),
833 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000834
835 Expr *ResultExpr = 0;
836
837 if (Result.isInvalid())
838 hadError = true; // types weren't compatible.
839 else {
840 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841
John McCall643169b2010-11-11 00:46:36 +0000842 if (ResultExpr != expr) {
843 // The type was promoted, update initializer list.
844 IList->setInit(Index, ResultExpr);
845 }
846 }
847 if (hadError)
848 ++StructuredIndex;
849 else
850 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
851 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000852}
853
Anders Carlsson6cabf312010-01-23 23:23:01 +0000854void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
855 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000856 unsigned &Index,
857 InitListExpr *StructuredList,
858 unsigned &StructuredIndex) {
859 if (Index < IList->getNumInits()) {
860 Expr *expr = IList->getInit(Index);
861 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000862 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000863 << DeclType << IList->getSourceRange();
864 hadError = true;
865 ++Index;
866 ++StructuredIndex;
867 return;
Mike Stump11289f42009-09-09 15:08:12 +0000868 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000869
John McCalldadc5752010-08-24 06:29:42 +0000870 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000871 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000872 SemaRef.Owned(expr),
873 /*TopLevelOfInitList=*/true);
Anders Carlssona91be642010-01-29 02:47:33 +0000874
875 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000876 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000877
878 expr = Result.takeAs<Expr>();
879 IList->setInit(Index, expr);
880
Douglas Gregord14247a2009-01-30 22:09:00 +0000881 if (hadError)
882 ++StructuredIndex;
883 else
884 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
885 ++Index;
886 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000887 // FIXME: It would be wonderful if we could point at the actual member. In
888 // general, it would be useful to pass location information down the stack,
889 // so that we know the location (or decl) of the "current object" being
890 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000891 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000892 diag::err_init_reference_member_uninitialized)
893 << DeclType
894 << IList->getSourceRange();
895 hadError = true;
896 ++Index;
897 ++StructuredIndex;
898 return;
899 }
900}
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000904 unsigned &Index,
905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000907 if (Index >= IList->getNumInits())
908 return;
Mike Stump11289f42009-09-09 15:08:12 +0000909
John McCall6a16b2f2010-10-30 00:11:39 +0000910 const VectorType *VT = DeclType->getAs<VectorType>();
911 unsigned maxElements = VT->getNumElements();
912 unsigned numEltsInit = 0;
913 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000914
John McCall6a16b2f2010-10-30 00:11:39 +0000915 if (!SemaRef.getLangOptions().OpenCL) {
916 // If the initializing element is a vector, try to copy-initialize
917 // instead of breaking it apart (which is doomed to failure anyway).
918 Expr *Init = IList->getInit(Index);
919 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
920 ExprResult Result =
921 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000922 SemaRef.Owned(Init),
923 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +0000924
925 Expr *ResultExpr = 0;
926 if (Result.isInvalid())
927 hadError = true; // types weren't compatible.
928 else {
929 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000930
John McCall6a16b2f2010-10-30 00:11:39 +0000931 if (ResultExpr != Init) {
932 // The type was promoted, update initializer list.
933 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000934 }
935 }
John McCall6a16b2f2010-10-30 00:11:39 +0000936 if (hadError)
937 ++StructuredIndex;
938 else
939 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
940 ++Index;
941 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
John McCall6a16b2f2010-10-30 00:11:39 +0000944 InitializedEntity ElementEntity =
945 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946
John McCall6a16b2f2010-10-30 00:11:39 +0000947 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
948 // Don't attempt to go past the end of the init list
949 if (Index >= IList->getNumInits())
950 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951
John McCall6a16b2f2010-10-30 00:11:39 +0000952 ElementEntity.setElementIndex(Index);
953 CheckSubElementType(ElementEntity, IList, elementType, Index,
954 StructuredList, StructuredIndex);
955 }
956 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000957 }
John McCall6a16b2f2010-10-30 00:11:39 +0000958
959 InitializedEntity ElementEntity =
960 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
John McCall6a16b2f2010-10-30 00:11:39 +0000962 // OpenCL initializers allows vectors to be constructed from vectors.
963 for (unsigned i = 0; i < maxElements; ++i) {
964 // Don't attempt to go past the end of the init list
965 if (Index >= IList->getNumInits())
966 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967
John McCall6a16b2f2010-10-30 00:11:39 +0000968 ElementEntity.setElementIndex(Index);
969
970 QualType IType = IList->getInit(Index)->getType();
971 if (!IType->isVectorType()) {
972 CheckSubElementType(ElementEntity, IList, elementType, Index,
973 StructuredList, StructuredIndex);
974 ++numEltsInit;
975 } else {
976 QualType VecType;
977 const VectorType *IVT = IType->getAs<VectorType>();
978 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
John McCall6a16b2f2010-10-30 00:11:39 +0000980 if (IType->isExtVectorType())
981 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
982 else
983 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000984 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +0000985 CheckSubElementType(ElementEntity, IList, VecType, Index,
986 StructuredList, StructuredIndex);
987 numEltsInit += numIElts;
988 }
989 }
990
991 // OpenCL requires all elements to be initialized.
992 if (numEltsInit != maxElements)
993 if (SemaRef.getLangOptions().OpenCL)
994 SemaRef.Diag(IList->getSourceRange().getBegin(),
995 diag::err_vector_incorrect_num_initializers)
996 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000997}
998
Anders Carlsson6cabf312010-01-23 23:23:01 +0000999void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001000 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001001 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001002 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001003 unsigned &Index,
1004 InitListExpr *StructuredList,
1005 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001006 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1007
Steve Narofff8ecff22008-05-01 22:18:59 +00001008 // Check for the special-case of initializing an array with a string.
1009 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001010 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001011 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +00001012 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001013 // We place the string literal directly into the resulting
1014 // initializer list. This is the only place where the structure
1015 // of the structured initializer list doesn't match exactly,
1016 // because doing so would involve allocating one character
1017 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001018 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001019 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001020 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001021 return;
1022 }
1023 }
John McCall66884dd2011-02-21 07:22:22 +00001024 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001025 // Check for VLAs; in standard C it would be possible to check this
1026 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1027 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001028 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001029 diag::err_variable_object_no_init)
1030 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001031 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001032 ++Index;
1033 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001034 return;
1035 }
1036
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001037 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001038 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1039 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001040 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001041 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001042 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001043 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001044 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001045 maxElementsKnown = true;
1046 }
1047
John McCall66884dd2011-02-21 07:22:22 +00001048 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001049 while (Index < IList->getNumInits()) {
1050 Expr *Init = IList->getInit(Index);
1051 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001052 // If we're not the subobject that matches up with the '{' for
1053 // the designator, we shouldn't be handling the
1054 // designator. Return immediately.
1055 if (!SubobjectIsDesignatorContext)
1056 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001057
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001058 // Handle this designated initializer. elementIndex will be
1059 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001060 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001061 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001062 StructuredList, StructuredIndex, true,
1063 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001064 hadError = true;
1065 continue;
1066 }
1067
Douglas Gregor033d1252009-01-23 16:54:12 +00001068 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001069 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001070 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001071 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001072 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001073
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001074 // If the array is of incomplete type, keep track of the number of
1075 // elements in the initializer.
1076 if (!maxElementsKnown && elementIndex > maxElements)
1077 maxElements = elementIndex;
1078
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001079 continue;
1080 }
1081
1082 // If we know the maximum number of elements, and we've already
1083 // hit it, stop consuming elements in the initializer list.
1084 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001085 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001086
Anders Carlsson6cabf312010-01-23 23:23:01 +00001087 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001089 Entity);
1090 // Check this element.
1091 CheckSubElementType(ElementEntity, IList, elementType, Index,
1092 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001093 ++elementIndex;
1094
1095 // If the array is of incomplete type, keep track of the number of
1096 // elements in the initializer.
1097 if (!maxElementsKnown && elementIndex > maxElements)
1098 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001099 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001100 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001101 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001102 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001103 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001104 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001105 // Sizing an array implicitly to zero is not allowed by ISO C,
1106 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001107 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001108 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001109 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001110
Mike Stump11289f42009-09-09 15:08:12 +00001111 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001112 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001113 }
1114}
1115
Anders Carlsson6cabf312010-01-23 23:23:01 +00001116void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001117 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001118 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001119 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001120 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001121 unsigned &Index,
1122 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001123 unsigned &StructuredIndex,
1124 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001125 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001126
Eli Friedman23a9e312008-05-19 19:16:24 +00001127 // If the record is invalid, some of it's members are invalid. To avoid
1128 // confusion, we forgo checking the intializer for the entire record.
1129 if (structDecl->isInvalidDecl()) {
1130 hadError = true;
1131 return;
Mike Stump11289f42009-09-09 15:08:12 +00001132 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001133
1134 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1135 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001136 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001137 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001138 Field != FieldEnd; ++Field) {
1139 if (Field->getDeclName()) {
1140 StructuredList->setInitializedFieldInUnion(*Field);
1141 break;
1142 }
1143 }
1144 return;
1145 }
1146
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001147 // If structDecl is a forward declaration, this loop won't do
1148 // anything except look at designated initializers; That's okay,
1149 // because an error should get printed out elsewhere. It might be
1150 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001151 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001152 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001153 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001154 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001155 while (Index < IList->getNumInits()) {
1156 Expr *Init = IList->getInit(Index);
1157
1158 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001159 // If we're not the subobject that matches up with the '{' for
1160 // the designator, we shouldn't be handling the
1161 // designator. Return immediately.
1162 if (!SubobjectIsDesignatorContext)
1163 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001164
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001165 // Handle this designated initializer. Field will be updated to
1166 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001167 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001168 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001169 StructuredList, StructuredIndex,
1170 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001171 hadError = true;
1172
Douglas Gregora9add4e2009-02-12 19:00:39 +00001173 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001174
1175 // Disable check for missing fields when designators are used.
1176 // This matches gcc behaviour.
1177 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001178 continue;
1179 }
1180
1181 if (Field == FieldEnd) {
1182 // We've run out of fields. We're done.
1183 break;
1184 }
1185
Douglas Gregora9add4e2009-02-12 19:00:39 +00001186 // We've already initialized a member of a union. We're done.
1187 if (InitializedSomething && DeclType->isUnionType())
1188 break;
1189
Douglas Gregor91f84212008-12-11 16:49:14 +00001190 // If we've hit the flexible array member at the end, we're done.
1191 if (Field->getType()->isIncompleteArrayType())
1192 break;
1193
Douglas Gregor51695702009-01-29 16:53:55 +00001194 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001195 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001196 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001197 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001198 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001199
Douglas Gregora82064c2011-06-29 21:51:31 +00001200 // Make sure we can use this declaration.
1201 if (SemaRef.DiagnoseUseOfDecl(*Field,
1202 IList->getInit(Index)->getLocStart())) {
1203 ++Index;
1204 ++Field;
1205 hadError = true;
1206 continue;
1207 }
1208
Anders Carlsson6cabf312010-01-23 23:23:01 +00001209 InitializedEntity MemberEntity =
1210 InitializedEntity::InitializeMember(*Field, &Entity);
1211 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1212 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001213 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001214
1215 if (DeclType->isUnionType()) {
1216 // Initialize the first field within the union.
1217 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001218 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001219
1220 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001221 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001222
John McCalle40b58e2010-03-11 19:32:38 +00001223 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001224 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001225 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1226 // It is possible we have one or more unnamed bitfields remaining.
1227 // Find first (if any) named field and emit warning.
1228 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1229 it != end; ++it) {
1230 if (!it->isUnnamedBitfield()) {
1231 SemaRef.Diag(IList->getSourceRange().getEnd(),
1232 diag::warn_missing_field_initializers) << it->getName();
1233 break;
1234 }
1235 }
1236 }
1237
Mike Stump11289f42009-09-09 15:08:12 +00001238 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001239 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001240 return;
1241
1242 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001243 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001244 (!isa<InitListExpr>(IList->getInit(Index)) ||
1245 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001246 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001247 diag::err_flexible_array_init_nonempty)
1248 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001249 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001250 << *Field;
1251 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001252 ++Index;
1253 return;
1254 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001255 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001256 diag::ext_flexible_array_init)
1257 << IList->getInit(Index)->getSourceRange().getBegin();
1258 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1259 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001260 }
1261
Anders Carlsson6cabf312010-01-23 23:23:01 +00001262 InitializedEntity MemberEntity =
1263 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
Anders Carlsson6cabf312010-01-23 23:23:01 +00001265 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001267 StructuredList, StructuredIndex);
1268 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001269 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001270 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001271}
Steve Narofff8ecff22008-05-01 22:18:59 +00001272
Douglas Gregord5846a12009-04-15 06:41:24 +00001273/// \brief Expand a field designator that refers to a member of an
1274/// anonymous struct or union into a series of field designators that
1275/// refers to the field within the appropriate subobject.
1276///
Douglas Gregord5846a12009-04-15 06:41:24 +00001277static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001278 DesignatedInitExpr *DIE,
1279 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001280 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001281 typedef DesignatedInitExpr::Designator Designator;
1282
Douglas Gregord5846a12009-04-15 06:41:24 +00001283 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001284 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001285 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1286 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1287 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001288 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001289 DIE->getDesignator(DesigIdx)->getDotLoc(),
1290 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1291 else
1292 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1293 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001294 assert(isa<FieldDecl>(*PI));
1295 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001296 }
1297
1298 // Expand the current designator into the set of replacement
1299 // designators, so we have a full subobject path down to where the
1300 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001301 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001302 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001303}
Mike Stump11289f42009-09-09 15:08:12 +00001304
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001305/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001306/// corresponds to FieldName.
1307static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1308 IdentifierInfo *FieldName) {
1309 assert(AnonField->isAnonymousStructOrUnion());
1310 Decl *NextDecl = AnonField->getNextDeclInContext();
1311 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1312 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1313 return IF;
1314 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001315 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001316 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001317}
1318
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001319/// @brief Check the well-formedness of a C99 designated initializer.
1320///
1321/// Determines whether the designated initializer @p DIE, which
1322/// resides at the given @p Index within the initializer list @p
1323/// IList, is well-formed for a current object of type @p DeclType
1324/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001325/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001326/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001327///
1328/// @param IList The initializer list in which this designated
1329/// initializer occurs.
1330///
Douglas Gregora5324162009-04-15 04:56:10 +00001331/// @param DIE The designated initializer expression.
1332///
1333/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001334///
1335/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1336/// into which the designation in @p DIE should refer.
1337///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001338/// @param NextField If non-NULL and the first designator in @p DIE is
1339/// a field, this will be set to the field declaration corresponding
1340/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001341///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001342/// @param NextElementIndex If non-NULL and the first designator in @p
1343/// DIE is an array designator or GNU array-range designator, this
1344/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001345///
1346/// @param Index Index into @p IList where the designated initializer
1347/// @p DIE occurs.
1348///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001349/// @param StructuredList The initializer list expression that
1350/// describes all of the subobject initializers in the order they'll
1351/// actually be initialized.
1352///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001353/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001354bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001355InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001356 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001357 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001358 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001359 QualType &CurrentObjectType,
1360 RecordDecl::field_iterator *NextField,
1361 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001362 unsigned &Index,
1363 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001364 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001365 bool FinishSubobjectInit,
1366 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001367 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001368 // Check the actual initialization for the designated object type.
1369 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001370
1371 // Temporarily remove the designator expression from the
1372 // initializer list that the child calls see, so that we don't try
1373 // to re-process the designator.
1374 unsigned OldIndex = Index;
1375 IList->setInit(OldIndex, DIE->getInit());
1376
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001377 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001378 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001379
1380 // Restore the designated initializer expression in the syntactic
1381 // form of the initializer list.
1382 if (IList->getInit(OldIndex) != DIE->getInit())
1383 DIE->setInit(IList->getInit(OldIndex));
1384 IList->setInit(OldIndex, DIE);
1385
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001386 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001387 }
1388
Douglas Gregora5324162009-04-15 04:56:10 +00001389 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001390 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001391 "Need a non-designated initializer list to start from");
1392
Douglas Gregora5324162009-04-15 04:56:10 +00001393 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 // Determine the structural initializer list that corresponds to the
1395 // current subobject.
1396 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001397 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001398 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 SourceRange(D->getStartLocation(),
1400 DIE->getSourceRange().getEnd()));
1401 assert(StructuredList && "Expected a structured initializer list");
1402
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001403 if (D->isFieldDesignator()) {
1404 // C99 6.7.8p7:
1405 //
1406 // If a designator has the form
1407 //
1408 // . identifier
1409 //
1410 // then the current object (defined below) shall have
1411 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001412 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001413 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001414 if (!RT) {
1415 SourceLocation Loc = D->getDotLoc();
1416 if (Loc.isInvalid())
1417 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001418 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1419 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001420 ++Index;
1421 return true;
1422 }
1423
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001424 // Note: we perform a linear search of the fields here, despite
1425 // the fact that we have a faster lookup method, because we always
1426 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001427 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001428 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001429 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001430 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001431 Field = RT->getDecl()->field_begin(),
1432 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001433 for (; Field != FieldEnd; ++Field) {
1434 if (Field->isUnnamedBitfield())
1435 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001437 // If we find a field representing an anonymous field, look in the
1438 // IndirectFieldDecl that follow for the designated initializer.
1439 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1440 if (IndirectFieldDecl *IF =
1441 FindIndirectFieldDesignator(*Field, FieldName)) {
1442 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1443 D = DIE->getDesignator(DesigIdx);
1444 break;
1445 }
1446 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001447 if (KnownField && KnownField == *Field)
1448 break;
1449 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001450 break;
1451
1452 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001453 }
1454
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001455 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001456 // There was no normal field in the struct with the designated
1457 // name. Perform another lookup for this name, which may find
1458 // something that we can't designate (e.g., a member function),
1459 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001460 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001461 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001462 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001463 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001464 // Name lookup didn't find anything. Determine whether this
1465 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001467 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001468 TypoCorrection Corrected = SemaRef.CorrectTypo(
1469 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1470 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1471 RT->getDecl(), false, Sema::CTC_NoKeywords);
1472 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001473 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001474 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001475 std::string CorrectedStr(
1476 Corrected.getAsString(SemaRef.getLangOptions()));
1477 std::string CorrectedQuotedStr(
1478 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001479 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001480 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001481 << FieldName << CurrentObjectType << CorrectedQuotedStr
1482 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001483 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001484 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001485 } else {
1486 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1487 << FieldName << CurrentObjectType;
1488 ++Index;
1489 return true;
1490 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001492
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001493 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001494 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001495 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001496 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001497 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001498 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001499 ++Index;
1500 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001501 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001502
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001503 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001504 // The replacement field comes from typo correction; find it
1505 // in the list of fields.
1506 FieldIndex = 0;
1507 Field = RT->getDecl()->field_begin();
1508 for (; Field != FieldEnd; ++Field) {
1509 if (Field->isUnnamedBitfield())
1510 continue;
1511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001512 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001513 Field->getIdentifier() == ReplacementField->getIdentifier())
1514 break;
1515
1516 ++FieldIndex;
1517 }
1518 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001519 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001520
1521 // All of the fields of a union are located at the same place in
1522 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001523 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001524 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001525 StructuredList->setInitializedFieldInUnion(*Field);
1526 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001527
Douglas Gregora82064c2011-06-29 21:51:31 +00001528 // Make sure we can use this declaration.
1529 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1530 ++Index;
1531 return true;
1532 }
1533
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001534 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001535 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001536
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001537 // Make sure that our non-designated initializer list has space
1538 // for a subobject corresponding to this field.
1539 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001540 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001541
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001542 // This designator names a flexible array member.
1543 if (Field->getType()->isIncompleteArrayType()) {
1544 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001545 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001546 // We can't designate an object within the flexible array
1547 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001548 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001549 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001550 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001551 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001552 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001553 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001554 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001555 << *Field;
1556 Invalid = true;
1557 }
1558
Chris Lattner001b29c2010-10-10 17:49:49 +00001559 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1560 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001561 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001562 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001563 diag::err_flexible_array_init_needs_braces)
1564 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001565 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001566 << *Field;
1567 Invalid = true;
1568 }
1569
1570 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001571 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001572 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001573 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001574 diag::err_flexible_array_init_nonempty)
1575 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001576 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001577 << *Field;
1578 Invalid = true;
1579 }
1580
1581 if (Invalid) {
1582 ++Index;
1583 return true;
1584 }
1585
1586 // Initialize the array.
1587 bool prevHadError = hadError;
1588 unsigned newStructuredIndex = FieldIndex;
1589 unsigned OldIndex = Index;
1590 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001591
1592 InitializedEntity MemberEntity =
1593 InitializedEntity::InitializeMember(*Field, &Entity);
1594 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001595 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001596
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001597 IList->setInit(OldIndex, DIE);
1598 if (hadError && !prevHadError) {
1599 ++Field;
1600 ++FieldIndex;
1601 if (NextField)
1602 *NextField = Field;
1603 StructuredIndex = FieldIndex;
1604 return true;
1605 }
1606 } else {
1607 // Recurse to check later designated subobjects.
1608 QualType FieldType = (*Field)->getType();
1609 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001610
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001611 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001612 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1614 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001615 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001616 true, false))
1617 return true;
1618 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619
1620 // Find the position of the next field to be initialized in this
1621 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001623 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001624
1625 // If this the first designator, our caller will continue checking
1626 // the rest of this struct/class/union subobject.
1627 if (IsFirstDesignator) {
1628 if (NextField)
1629 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001630 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001631 return false;
1632 }
1633
Douglas Gregor17bd0942009-01-28 23:36:17 +00001634 if (!FinishSubobjectInit)
1635 return false;
1636
Douglas Gregord5846a12009-04-15 06:41:24 +00001637 // We've already initialized something in the union; we're done.
1638 if (RT->getDecl()->isUnion())
1639 return hadError;
1640
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001641 // Check the remaining fields within this class/struct/union subobject.
1642 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643
Anders Carlsson6cabf312010-01-23 23:23:01 +00001644 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001645 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001646 return hadError && !prevHadError;
1647 }
1648
1649 // C99 6.7.8p6:
1650 //
1651 // If a designator has the form
1652 //
1653 // [ constant-expression ]
1654 //
1655 // then the current object (defined below) shall have array
1656 // type and the expression shall be an integer constant
1657 // expression. If the array is of unknown size, any
1658 // nonnegative value is valid.
1659 //
1660 // Additionally, cope with the GNU extension that permits
1661 // designators of the form
1662 //
1663 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001664 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001665 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001666 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001667 << CurrentObjectType;
1668 ++Index;
1669 return true;
1670 }
1671
1672 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1674 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001675 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001676 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001677 DesignatedEndIndex = DesignatedStartIndex;
1678 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001679 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001680
Mike Stump11289f42009-09-09 15:08:12 +00001681 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001682 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001683 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001684 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001685 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001686
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001687 // Codegen can't handle evaluating array range designators that have side
1688 // effects, because we replicate the AST value for each initialized element.
1689 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1690 // elements with something that has a side effect, so codegen can emit an
1691 // "error unsupported" error instead of miscompiling the app.
1692 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1693 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001694 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001695 }
1696
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001697 if (isa<ConstantArrayType>(AT)) {
1698 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001699 DesignatedStartIndex
1700 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001701 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001702 DesignatedEndIndex
1703 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001704 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1705 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001706 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001707 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001708 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001709 << IndexExpr->getSourceRange();
1710 ++Index;
1711 return true;
1712 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001713 } else {
1714 // Make sure the bit-widths and signedness match.
1715 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001716 DesignatedEndIndex
1717 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001718 else if (DesignatedStartIndex.getBitWidth() <
1719 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001720 DesignatedStartIndex
1721 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001722 DesignatedStartIndex.setIsUnsigned(true);
1723 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001726 // Make sure that our non-designated initializer list has space
1727 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001728 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001729 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001730 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001731
Douglas Gregor17bd0942009-01-28 23:36:17 +00001732 // Repeatedly perform subobject initializations in the range
1733 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001734
Douglas Gregor17bd0942009-01-28 23:36:17 +00001735 // Move to the next designator
1736 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1737 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001738
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001739 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001740 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001741
Douglas Gregor17bd0942009-01-28 23:36:17 +00001742 while (DesignatedStartIndex <= DesignatedEndIndex) {
1743 // Recurse to check later designated subobjects.
1744 QualType ElementType = AT->getElementType();
1745 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001747 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001748 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1749 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001750 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001751 (DesignatedStartIndex == DesignatedEndIndex),
1752 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001753 return true;
1754
1755 // Move to the next index in the array that we'll be initializing.
1756 ++DesignatedStartIndex;
1757 ElementIndex = DesignatedStartIndex.getZExtValue();
1758 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001759
1760 // If this the first designator, our caller will continue checking
1761 // the rest of this array subobject.
1762 if (IsFirstDesignator) {
1763 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001764 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001766 return false;
1767 }
Mike Stump11289f42009-09-09 15:08:12 +00001768
Douglas Gregor17bd0942009-01-28 23:36:17 +00001769 if (!FinishSubobjectInit)
1770 return false;
1771
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001772 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001773 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001775 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001776 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001777 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001778}
1779
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780// Get the structured initializer list for a subobject of type
1781// @p CurrentObjectType.
1782InitListExpr *
1783InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1784 QualType CurrentObjectType,
1785 InitListExpr *StructuredList,
1786 unsigned StructuredIndex,
1787 SourceRange InitRange) {
1788 Expr *ExistingInit = 0;
1789 if (!StructuredList)
1790 ExistingInit = SyntacticToSemantic[IList];
1791 else if (StructuredIndex < StructuredList->getNumInits())
1792 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001793
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1795 return Result;
1796
1797 if (ExistingInit) {
1798 // We are creating an initializer list that initializes the
1799 // subobjects of the current object, but there was already an
1800 // initialization that completely initialized the current
1801 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001802 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001803 // struct X { int a, b; };
1804 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001805 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001806 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1807 // designated initializer re-initializes the whole
1808 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001809 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001810 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001811 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001812 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001813 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001814 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001815 << ExistingInit->getSourceRange();
1816 }
1817
Mike Stump11289f42009-09-09 15:08:12 +00001818 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001819 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1820 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001821 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001822
Douglas Gregora8a089b2010-07-13 18:40:04 +00001823 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001824
Douglas Gregor6d00c992009-03-20 23:58:33 +00001825 // Pre-allocate storage for the structured initializer list.
1826 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001827 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001828 bool GotNumInits = false;
1829 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001830 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001831 GotNumInits = true;
1832 } else if (Index < IList->getNumInits()) {
1833 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001834 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001835 GotNumInits = true;
1836 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001837 }
1838
Mike Stump11289f42009-09-09 15:08:12 +00001839 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001840 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1841 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1842 NumElements = CAType->getSize().getZExtValue();
1843 // Simple heuristic so that we don't allocate a very large
1844 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001845 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001846 NumElements = 0;
1847 }
John McCall9dd450b2009-09-21 23:43:11 +00001848 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001849 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001850 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001851 RecordDecl *RDecl = RType->getDecl();
1852 if (RDecl->isUnion())
1853 NumElements = 1;
1854 else
Mike Stump11289f42009-09-09 15:08:12 +00001855 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001856 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001857 }
1858
Douglas Gregor221c9a52009-03-21 18:13:52 +00001859 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001860 NumElements = IList->getNumInits();
1861
Ted Kremenekac034612010-04-13 23:39:13 +00001862 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001863
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001864 // Link this new initializer list into the structured initializer
1865 // lists.
1866 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001867 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001868 else {
1869 Result->setSyntacticForm(IList);
1870 SyntacticToSemantic[IList] = Result;
1871 }
1872
1873 return Result;
1874}
1875
1876/// Update the initializer at index @p StructuredIndex within the
1877/// structured initializer list to the value @p expr.
1878void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1879 unsigned &StructuredIndex,
1880 Expr *expr) {
1881 // No structured initializer list to update
1882 if (!StructuredList)
1883 return;
1884
Ted Kremenekac034612010-04-13 23:39:13 +00001885 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1886 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001887 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001888 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001889 diag::warn_initializer_overrides)
1890 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001891 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001892 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001893 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001894 << PrevInit->getSourceRange();
1895 }
Mike Stump11289f42009-09-09 15:08:12 +00001896
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001897 ++StructuredIndex;
1898}
1899
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001900/// Check that the given Index expression is a valid array designator
1901/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001902/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001903/// and produces a reasonable diagnostic if there is a
1904/// failure. Returns true if there was an error, false otherwise. If
1905/// everything went okay, Value will receive the value of the constant
1906/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001907static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001908CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001909 SourceLocation Loc = Index->getSourceRange().getBegin();
1910
1911 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001912 if (S.VerifyIntegerConstantExpression(Index, &Value))
1913 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001914
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001915 if (Value.isSigned() && Value.isNegative())
1916 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001917 << Value.toString(10) << Index->getSourceRange();
1918
Douglas Gregor51650d32009-01-23 21:04:18 +00001919 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001920 return false;
1921}
1922
John McCalldadc5752010-08-24 06:29:42 +00001923ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001924 SourceLocation Loc,
1925 bool GNUSyntax,
1926 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001927 typedef DesignatedInitExpr::Designator ASTDesignator;
1928
1929 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001930 SmallVector<ASTDesignator, 32> Designators;
1931 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001932
1933 // Build designators and check array designator expressions.
1934 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1935 const Designator &D = Desig.getDesignator(Idx);
1936 switch (D.getKind()) {
1937 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001938 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001939 D.getFieldLoc()));
1940 break;
1941
1942 case Designator::ArrayDesignator: {
1943 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1944 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001945 if (!Index->isTypeDependent() &&
1946 !Index->isValueDependent() &&
1947 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001948 Invalid = true;
1949 else {
1950 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001951 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001952 D.getRBracketLoc()));
1953 InitExpressions.push_back(Index);
1954 }
1955 break;
1956 }
1957
1958 case Designator::ArrayRangeDesignator: {
1959 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1960 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1961 llvm::APSInt StartValue;
1962 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001963 bool StartDependent = StartIndex->isTypeDependent() ||
1964 StartIndex->isValueDependent();
1965 bool EndDependent = EndIndex->isTypeDependent() ||
1966 EndIndex->isValueDependent();
1967 if ((!StartDependent &&
1968 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1969 (!EndDependent &&
1970 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001971 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001972 else {
1973 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001974 if (StartDependent || EndDependent) {
1975 // Nothing to compute.
1976 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001977 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001978 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001979 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00001980
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001981 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001982 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001983 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001984 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1985 Invalid = true;
1986 } else {
1987 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001988 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001989 D.getEllipsisLoc(),
1990 D.getRBracketLoc()));
1991 InitExpressions.push_back(StartIndex);
1992 InitExpressions.push_back(EndIndex);
1993 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001994 }
1995 break;
1996 }
1997 }
1998 }
1999
2000 if (Invalid || Init.isInvalid())
2001 return ExprError();
2002
2003 // Clear out the expressions within the designation.
2004 Desig.ClearExprs(*this);
2005
2006 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002007 = DesignatedInitExpr::Create(Context,
2008 Designators.data(), Designators.size(),
2009 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002010 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011
Douglas Gregorc124e592011-01-16 16:13:16 +00002012 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002013 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2014 << DIE->getSourceRange();
2015 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002016 Diag(DIE->getLocStart(), diag::ext_designated_init)
2017 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002019 return Owned(DIE);
2020}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002021
Douglas Gregor723796a2009-12-16 06:35:08 +00002022bool Sema::CheckInitList(const InitializedEntity &Entity,
2023 InitListExpr *&InitList, QualType &DeclType) {
2024 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00002025 if (!CheckInitList.HadError())
2026 InitList = CheckInitList.getFullyStructuredList();
2027
2028 return CheckInitList.HadError();
2029}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00002030
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002031//===----------------------------------------------------------------------===//
2032// Initialization entity
2033//===----------------------------------------------------------------------===//
2034
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002035InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002036 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002038{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002039 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2040 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002041 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002042 } else {
2043 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002044 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002045 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002046}
2047
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002049 CXXBaseSpecifier *Base,
2050 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002051{
2052 InitializedEntity Result;
2053 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002054 Result.Base = reinterpret_cast<uintptr_t>(Base);
2055 if (IsInheritedVirtualBase)
2056 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002057
Douglas Gregor1b303932009-12-22 15:35:07 +00002058 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002059 return Result;
2060}
2061
Douglas Gregor85dabae2009-12-16 01:38:02 +00002062DeclarationName InitializedEntity::getName() const {
2063 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002064 case EK_Parameter: {
2065 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2066 return (D ? D->getDeclName() : DeclarationName());
2067 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002068
2069 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002070 case EK_Member:
2071 return VariableOrMember->getDeclName();
2072
2073 case EK_Result:
2074 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002075 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002076 case EK_Temporary:
2077 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002078 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002079 case EK_ArrayElement:
2080 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002081 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002082 return DeclarationName();
2083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002084
Douglas Gregor85dabae2009-12-16 01:38:02 +00002085 // Silence GCC warning
2086 return DeclarationName();
2087}
2088
Douglas Gregora4b592a2009-12-19 03:01:41 +00002089DeclaratorDecl *InitializedEntity::getDecl() const {
2090 switch (getKind()) {
2091 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002092 case EK_Member:
2093 return VariableOrMember;
2094
John McCall31168b02011-06-15 23:02:42 +00002095 case EK_Parameter:
2096 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2097
Douglas Gregora4b592a2009-12-19 03:01:41 +00002098 case EK_Result:
2099 case EK_Exception:
2100 case EK_New:
2101 case EK_Temporary:
2102 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002103 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002104 case EK_ArrayElement:
2105 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002106 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002107 return 0;
2108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
Douglas Gregora4b592a2009-12-19 03:01:41 +00002110 // Silence GCC warning
2111 return 0;
2112}
2113
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002114bool InitializedEntity::allowsNRVO() const {
2115 switch (getKind()) {
2116 case EK_Result:
2117 case EK_Exception:
2118 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002120 case EK_Variable:
2121 case EK_Parameter:
2122 case EK_Member:
2123 case EK_New:
2124 case EK_Temporary:
2125 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002126 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002127 case EK_ArrayElement:
2128 case EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002129 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002130 break;
2131 }
2132
2133 return false;
2134}
2135
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002136//===----------------------------------------------------------------------===//
2137// Initialization sequence
2138//===----------------------------------------------------------------------===//
2139
2140void InitializationSequence::Step::Destroy() {
2141 switch (Kind) {
2142 case SK_ResolveAddressOfOverloadedFunction:
2143 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002144 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002145 case SK_CastDerivedToBaseLValue:
2146 case SK_BindReference:
2147 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002148 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002149 case SK_UserConversion:
2150 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002151 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002152 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002153 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002154 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002155 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002156 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002157 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002158 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002159 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002160 case SK_PassByIndirectCopyRestore:
2161 case SK_PassByIndirectRestore:
2162 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002163 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002165 case SK_ConversionSequence:
2166 delete ICS;
2167 }
2168}
2169
Douglas Gregor838fcc32010-03-26 20:14:36 +00002170bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002171 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002172}
2173
2174bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002175 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002176 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177
Douglas Gregor838fcc32010-03-26 20:14:36 +00002178 switch (getFailureKind()) {
2179 case FK_TooManyInitsForReference:
2180 case FK_ArrayNeedsInitList:
2181 case FK_ArrayNeedsInitListOrStringLiteral:
2182 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2183 case FK_NonConstLValueReferenceBindingToTemporary:
2184 case FK_NonConstLValueReferenceBindingToUnrelated:
2185 case FK_RValueReferenceBindingToLValue:
2186 case FK_ReferenceInitDropsQualifiers:
2187 case FK_ReferenceInitFailed:
2188 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002189 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002190 case FK_TooManyInitsForScalar:
2191 case FK_ReferenceBindingToInitList:
2192 case FK_InitListBadDestinationType:
2193 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002194 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002195 case FK_ArrayTypeMismatch:
2196 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002197 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198
Douglas Gregor838fcc32010-03-26 20:14:36 +00002199 case FK_ReferenceInitOverloadFailed:
2200 case FK_UserConversionOverloadFailed:
2201 case FK_ConstructorOverloadFailed:
2202 return FailedOverloadResult == OR_Ambiguous;
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Douglas Gregor838fcc32010-03-26 20:14:36 +00002205 return false;
2206}
2207
Douglas Gregorb33eed02010-04-16 22:09:46 +00002208bool InitializationSequence::isConstructorInitialization() const {
2209 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2210}
2211
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002212bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2213 const Expr *Initializer,
2214 bool *isInitializerConstant,
2215 APValue *ConstantValue) const {
2216 if (Steps.empty() || Initializer->isValueDependent())
2217 return false;
2218
2219 const Step &LastStep = Steps.back();
2220 if (LastStep.Kind != SK_ConversionSequence)
2221 return false;
2222
2223 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2224 const StandardConversionSequence *SCS = NULL;
2225 switch (ICS.getKind()) {
2226 case ImplicitConversionSequence::StandardConversion:
2227 SCS = &ICS.Standard;
2228 break;
2229 case ImplicitConversionSequence::UserDefinedConversion:
2230 SCS = &ICS.UserDefined.After;
2231 break;
2232 case ImplicitConversionSequence::AmbiguousConversion:
2233 case ImplicitConversionSequence::EllipsisConversion:
2234 case ImplicitConversionSequence::BadConversion:
2235 return false;
2236 }
2237
2238 // Check if SCS represents a narrowing conversion, according to C++0x
2239 // [dcl.init.list]p7:
2240 //
2241 // A narrowing conversion is an implicit conversion ...
2242 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2243 QualType FromType = SCS->getToType(0);
2244 QualType ToType = SCS->getToType(1);
2245 switch (PossibleNarrowing) {
2246 // * from a floating-point type to an integer type, or
2247 //
2248 // * from an integer type or unscoped enumeration type to a floating-point
2249 // type, except where the source is a constant expression and the actual
2250 // value after conversion will fit into the target type and will produce
2251 // the original value when converted back to the original type, or
2252 case ICK_Floating_Integral:
2253 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2254 *isInitializerConstant = false;
2255 return true;
2256 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2257 llvm::APSInt IntConstantValue;
2258 if (Initializer &&
2259 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2260 // Convert the integer to the floating type.
2261 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2262 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2263 llvm::APFloat::rmNearestTiesToEven);
2264 // And back.
2265 llvm::APSInt ConvertedValue = IntConstantValue;
2266 bool ignored;
2267 Result.convertToInteger(ConvertedValue,
2268 llvm::APFloat::rmTowardZero, &ignored);
2269 // If the resulting value is different, this was a narrowing conversion.
2270 if (IntConstantValue != ConvertedValue) {
2271 *isInitializerConstant = true;
2272 *ConstantValue = APValue(IntConstantValue);
2273 return true;
2274 }
2275 } else {
2276 // Variables are always narrowings.
2277 *isInitializerConstant = false;
2278 return true;
2279 }
2280 }
2281 return false;
2282
2283 // * from long double to double or float, or from double to float, except
2284 // where the source is a constant expression and the actual value after
2285 // conversion is within the range of values that can be represented (even
2286 // if it cannot be represented exactly), or
2287 case ICK_Floating_Conversion:
2288 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2289 // FromType is larger than ToType.
2290 Expr::EvalResult InitializerValue;
2291 // FIXME: Check whether Initializer is a constant expression according
2292 // to C++0x [expr.const], rather than just whether it can be folded.
2293 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2294 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2295 // Constant! (Except for FIXME above.)
2296 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2297 // Convert the source value into the target type.
2298 bool ignored;
2299 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2300 Ctx.getFloatTypeSemantics(ToType),
2301 llvm::APFloat::rmNearestTiesToEven, &ignored);
2302 // If there was no overflow, the source value is within the range of
2303 // values that can be represented.
2304 if (ConvertStatus & llvm::APFloat::opOverflow) {
2305 *isInitializerConstant = true;
2306 *ConstantValue = InitializerValue.Val;
2307 return true;
2308 }
2309 } else {
2310 *isInitializerConstant = false;
2311 return true;
2312 }
2313 }
2314 return false;
2315
2316 // * from an integer type or unscoped enumeration type to an integer type
2317 // that cannot represent all the values of the original type, except where
2318 // the source is a constant expression and the actual value after
2319 // conversion will fit into the target type and will produce the original
2320 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002321 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002322 case ICK_Integral_Conversion: {
2323 assert(FromType->isIntegralOrUnscopedEnumerationType());
2324 assert(ToType->isIntegralOrUnscopedEnumerationType());
2325 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2326 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2327 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2328 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2329
2330 if (FromWidth > ToWidth ||
2331 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2332 // Not all values of FromType can be represented in ToType.
2333 llvm::APSInt InitializerValue;
2334 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2335 *isInitializerConstant = true;
2336 *ConstantValue = APValue(InitializerValue);
2337
2338 // Add a bit to the InitializerValue so we don't have to worry about
2339 // signed vs. unsigned comparisons.
2340 InitializerValue = InitializerValue.extend(
2341 InitializerValue.getBitWidth() + 1);
2342 // Convert the initializer to and from the target width and signed-ness.
2343 llvm::APSInt ConvertedValue = InitializerValue;
2344 ConvertedValue = ConvertedValue.trunc(ToWidth);
2345 ConvertedValue.setIsSigned(ToSigned);
2346 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2347 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2348 // If the result is different, this was a narrowing conversion.
2349 return ConvertedValue != InitializerValue;
2350 } else {
2351 // Variables are always narrowings.
2352 *isInitializerConstant = false;
2353 return true;
2354 }
2355 }
2356 return false;
2357 }
2358
2359 default:
2360 // Other kinds of conversions are not narrowings.
2361 return false;
2362 }
2363}
2364
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002365void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002366 FunctionDecl *Function,
2367 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002368 Step S;
2369 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2370 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002371 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002372 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002373 Steps.push_back(S);
2374}
2375
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002376void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002377 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002378 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002379 switch (VK) {
2380 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2381 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2382 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002383 default: llvm_unreachable("No such category");
2384 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002385 S.Type = BaseType;
2386 Steps.push_back(S);
2387}
2388
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002390 bool BindingTemporary) {
2391 Step S;
2392 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2393 S.Type = T;
2394 Steps.push_back(S);
2395}
2396
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002397void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2398 Step S;
2399 S.Kind = SK_ExtraneousCopyToTemporary;
2400 S.Type = T;
2401 Steps.push_back(S);
2402}
2403
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002404void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002405 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002406 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002407 Step S;
2408 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002409 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002410 S.Function.Function = Function;
2411 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002412 Steps.push_back(S);
2413}
2414
2415void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002416 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002417 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002418 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002419 switch (VK) {
2420 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002421 S.Kind = SK_QualificationConversionRValue;
2422 break;
John McCall2536c6d2010-08-25 10:28:54 +00002423 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002424 S.Kind = SK_QualificationConversionXValue;
2425 break;
John McCall2536c6d2010-08-25 10:28:54 +00002426 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002427 S.Kind = SK_QualificationConversionLValue;
2428 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002429 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002430 S.Type = Ty;
2431 Steps.push_back(S);
2432}
2433
2434void InitializationSequence::AddConversionSequenceStep(
2435 const ImplicitConversionSequence &ICS,
2436 QualType T) {
2437 Step S;
2438 S.Kind = SK_ConversionSequence;
2439 S.Type = T;
2440 S.ICS = new ImplicitConversionSequence(ICS);
2441 Steps.push_back(S);
2442}
2443
Douglas Gregor51e77d52009-12-10 17:56:55 +00002444void InitializationSequence::AddListInitializationStep(QualType T) {
2445 Step S;
2446 S.Kind = SK_ListInitialization;
2447 S.Type = T;
2448 Steps.push_back(S);
2449}
2450
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002451void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002452InitializationSequence::AddConstructorInitializationStep(
2453 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002454 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002455 QualType T) {
2456 Step S;
2457 S.Kind = SK_ConstructorInitialization;
2458 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002459 S.Function.Function = Constructor;
2460 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002461 Steps.push_back(S);
2462}
2463
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002464void InitializationSequence::AddZeroInitializationStep(QualType T) {
2465 Step S;
2466 S.Kind = SK_ZeroInitialization;
2467 S.Type = T;
2468 Steps.push_back(S);
2469}
2470
Douglas Gregore1314a62009-12-18 05:02:21 +00002471void InitializationSequence::AddCAssignmentStep(QualType T) {
2472 Step S;
2473 S.Kind = SK_CAssignment;
2474 S.Type = T;
2475 Steps.push_back(S);
2476}
2477
Eli Friedman78275202009-12-19 08:11:05 +00002478void InitializationSequence::AddStringInitStep(QualType T) {
2479 Step S;
2480 S.Kind = SK_StringInit;
2481 S.Type = T;
2482 Steps.push_back(S);
2483}
2484
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002485void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2486 Step S;
2487 S.Kind = SK_ObjCObjectConversion;
2488 S.Type = T;
2489 Steps.push_back(S);
2490}
2491
Douglas Gregore2f943b2011-02-22 18:29:51 +00002492void InitializationSequence::AddArrayInitStep(QualType T) {
2493 Step S;
2494 S.Kind = SK_ArrayInit;
2495 S.Type = T;
2496 Steps.push_back(S);
2497}
2498
John McCall31168b02011-06-15 23:02:42 +00002499void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2500 bool shouldCopy) {
2501 Step s;
2502 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2503 : SK_PassByIndirectRestore);
2504 s.Type = type;
2505 Steps.push_back(s);
2506}
2507
2508void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2509 Step S;
2510 S.Kind = SK_ProduceObjCObject;
2511 S.Type = T;
2512 Steps.push_back(S);
2513}
2514
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002516 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002517 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002518 this->Failure = Failure;
2519 this->FailedOverloadResult = Result;
2520}
2521
2522//===----------------------------------------------------------------------===//
2523// Attempt initialization
2524//===----------------------------------------------------------------------===//
2525
John McCall31168b02011-06-15 23:02:42 +00002526static void MaybeProduceObjCObject(Sema &S,
2527 InitializationSequence &Sequence,
2528 const InitializedEntity &Entity) {
2529 if (!S.getLangOptions().ObjCAutoRefCount) return;
2530
2531 /// When initializing a parameter, produce the value if it's marked
2532 /// __attribute__((ns_consumed)).
2533 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2534 if (!Entity.isParameterConsumed())
2535 return;
2536
2537 assert(Entity.getType()->isObjCRetainableType() &&
2538 "consuming an object of unretainable type?");
2539 Sequence.AddProduceObjCObjectStep(Entity.getType());
2540
2541 /// When initializing a return value, if the return type is a
2542 /// retainable type, then returns need to immediately retain the
2543 /// object. If an autorelease is required, it will be done at the
2544 /// last instant.
2545 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2546 if (!Entity.getType()->isObjCRetainableType())
2547 return;
2548
2549 Sequence.AddProduceObjCObjectStep(Entity.getType());
2550 }
2551}
2552
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002553/// \brief Attempt list initialization (C++0x [dcl.init.list])
2554static void TryListInitialization(Sema &S,
2555 const InitializedEntity &Entity,
2556 const InitializationKind &Kind,
2557 InitListExpr *InitList,
2558 InitializationSequence &Sequence) {
2559 // FIXME: We only perform rudimentary checking of list
2560 // initializations at this point, then assume that any list
2561 // initialization of an array, aggregate, or scalar will be
2562 // well-formed. When we actually "perform" list initialization, we'll
2563 // do all of the necessary checking. C++0x initializer lists will
2564 // force us to perform more checking here.
2565
2566 QualType DestType = Entity.getType();
2567
2568 // C++ [dcl.init]p13:
2569 // If T is a scalar type, then a declaration of the form
2570 //
2571 // T x = { a };
2572 //
2573 // is equivalent to
2574 //
2575 // T x = a;
2576 if (DestType->isScalarType()) {
2577 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2578 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2579 return;
2580 }
2581
2582 // Assume scalar initialization from a single value works.
2583 } else if (DestType->isAggregateType()) {
2584 // Assume aggregate initialization works.
2585 } else if (DestType->isVectorType()) {
2586 // Assume vector initialization works.
2587 } else if (DestType->isReferenceType()) {
2588 // FIXME: C++0x defines behavior for this.
2589 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2590 return;
2591 } else if (DestType->isRecordType()) {
2592 // FIXME: C++0x defines behavior for this
2593 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2594 }
2595
2596 // Add a general "list initialization" step.
2597 Sequence.AddListInitializationStep(DestType);
2598}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002599
2600/// \brief Try a reference initialization that involves calling a conversion
2601/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002602static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2603 const InitializedEntity &Entity,
2604 const InitializationKind &Kind,
2605 Expr *Initializer,
2606 bool AllowRValues,
2607 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002608 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002609 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2610 QualType T1 = cv1T1.getUnqualifiedType();
2611 QualType cv2T2 = Initializer->getType();
2612 QualType T2 = cv2T2.getUnqualifiedType();
2613
2614 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002615 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002616 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002618 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002619 ObjCConversion,
2620 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002621 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002622 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002623 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002624 (void)ObjCLifetimeConversion;
2625
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002626 // Build the candidate set directly in the initialization sequence
2627 // structure, so that it will persist if we fail.
2628 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2629 CandidateSet.clear();
2630
2631 // Determine whether we are allowed to call explicit constructors or
2632 // explicit conversion operators.
2633 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002635 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002636 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2637 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002638 // The type we're converting to is a class type. Enumerate its constructors
2639 // to see if there is a suitable conversion.
2640 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002641
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002642 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002643 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002644 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002645 NamedDecl *D = *Con;
2646 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002648 // Find the constructor (which may be a template).
2649 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002650 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002651 if (ConstructorTmpl)
2652 Constructor = cast<CXXConstructorDecl>(
2653 ConstructorTmpl->getTemplatedDecl());
2654 else
John McCalla0296f72010-03-19 07:35:19 +00002655 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002657 if (!Constructor->isInvalidDecl() &&
2658 Constructor->isConvertingConstructor(AllowExplicit)) {
2659 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002660 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002661 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002662 &Initializer, 1, CandidateSet,
2663 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002664 else
John McCalla0296f72010-03-19 07:35:19 +00002665 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002666 &Initializer, 1, CandidateSet,
2667 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 }
John McCall3696dcb2010-08-17 07:23:57 +00002671 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2672 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673
Douglas Gregor496e8b342010-05-07 19:42:26 +00002674 const RecordType *T2RecordType = 0;
2675 if ((T2RecordType = T2->getAs<RecordType>()) &&
2676 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677 // The type we're converting from is a class type, enumerate its conversion
2678 // functions.
2679 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2680
John McCallad371252010-01-20 00:46:10 +00002681 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002683 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2684 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002685 NamedDecl *D = *I;
2686 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2687 if (isa<UsingShadowDecl>(D))
2688 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002689
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002690 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2691 CXXConversionDecl *Conv;
2692 if (ConvTemplate)
2693 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2694 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002695 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002696
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002697 // If the conversion function doesn't return a reference type,
2698 // it can't be considered for this conversion unless we're allowed to
2699 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700 // FIXME: Do we need to make sure that we only consider conversion
2701 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002702 // break recursion.
2703 if ((AllowExplicit || !Conv->isExplicit()) &&
2704 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2705 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002706 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002707 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002708 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002709 else
John McCalla0296f72010-03-19 07:35:19 +00002710 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002711 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002712 }
2713 }
2714 }
John McCall3696dcb2010-08-17 07:23:57 +00002715 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2716 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002717
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002718 SourceLocation DeclLoc = Initializer->getLocStart();
2719
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002721 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002722 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002723 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002724 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002725
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002727
Chandler Carruth30141632011-02-25 19:41:05 +00002728 // This is the overload that will actually be used for the initialization, so
2729 // mark it as used.
2730 S.MarkDeclarationReferenced(DeclLoc, Function);
2731
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002732 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002733 if (isa<CXXConversionDecl>(Function))
2734 T2 = Function->getResultType();
2735 else
2736 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002737
2738 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002739 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002740 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002741
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002742 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002743 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002744 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002745 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002746 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002747 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002748 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002749
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002750 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002751 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002752 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002753 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002754 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002755 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002756 NewDerivedToBase, NewObjCConversion,
2757 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002758 if (NewRefRelationship == Sema::Ref_Incompatible) {
2759 // If the type we've converted to is not reference-related to the
2760 // type we're looking for, then there is another conversion step
2761 // we need to perform to produce a temporary of the right type
2762 // that we'll be binding to.
2763 ImplicitConversionSequence ICS;
2764 ICS.setStandard();
2765 ICS.Standard = Best->FinalConversion;
2766 T2 = ICS.Standard.getToType(2);
2767 Sequence.AddConversionSequenceStep(ICS, T2);
2768 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 Sequence.AddDerivedToBaseCastStep(
2770 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002772 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002773 else if (NewObjCConversion)
2774 Sequence.AddObjCObjectConversionStep(
2775 S.Context.getQualifiedType(T1,
2776 T2.getNonReferenceType().getQualifiers()));
2777
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002778 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002779 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002781 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2782 return OR_Success;
2783}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784
2785/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2786static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002787 const InitializedEntity &Entity,
2788 const InitializationKind &Kind,
2789 Expr *Initializer,
2790 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002791 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002792 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002793 Qualifiers T1Quals;
2794 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002795 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002796 Qualifiers T2Quals;
2797 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002798 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002799
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002800 // If the initializer is the address of an overloaded function, try
2801 // to resolve the overloaded function. If all goes well, T2 is the
2802 // type of the resulting function.
2803 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002804 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002806 T1,
2807 false,
2808 Found)) {
2809 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2810 cv2T2 = Fn->getType();
2811 T2 = cv2T2.getUnqualifiedType();
2812 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002813 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2814 return;
2815 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002816 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002817
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002818 // Compute some basic properties of the types and the initializer.
2819 bool isLValueRef = DestType->isLValueReferenceType();
2820 bool isRValueRef = !isLValueRef;
2821 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002822 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002823 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002824 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002825 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002826 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002827 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002828
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002829 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002831 // "cv2 T2" as follows:
2832 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002833 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002834 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002835 // Note the analogous bullet points for rvlaue refs to functions. Because
2836 // there are no function rvalues in C++, rvalue refs to functions are treated
2837 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002838 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002839 bool T1Function = T1->isFunctionType();
2840 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002842 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002843 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002844 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002845 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002846 // reference-compatible with "cv2 T2," or
2847 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002849 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002850 // can occur. However, we do pay attention to whether it is a bit-field
2851 // to decide whether we're actually binding to a temporary created from
2852 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002853 if (DerivedToBase)
2854 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002856 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002857 else if (ObjCConversion)
2858 Sequence.AddObjCObjectConversionStep(
2859 S.Context.getQualifiedType(T1, T2Quals));
2860
Chandler Carruth04bdce62010-01-12 20:32:25 +00002861 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002862 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002863 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002864 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002865 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866 return;
2867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868
2869 // - has a class type (i.e., T2 is a class type), where T1 is not
2870 // reference-related to T2, and can be implicitly converted to an
2871 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2872 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002873 // applicable conversion functions (13.3.1.6) and choosing the best
2874 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002875 // If we have an rvalue ref to function type here, the rhs must be
2876 // an rvalue.
2877 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2878 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002879 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002880 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002881 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882 Sequence);
2883 if (ConvOvlResult == OR_Success)
2884 return;
John McCall0d1da222010-01-12 00:44:57 +00002885 if (ConvOvlResult != OR_No_Viable_Function) {
2886 Sequence.SetOverloadFailure(
2887 InitializationSequence::FK_ReferenceInitOverloadFailed,
2888 ConvOvlResult);
2889 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002890 }
2891 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002894 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002895 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002896 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002897 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2898 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2899 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002900 Sequence.SetOverloadFailure(
2901 InitializationSequence::FK_ReferenceInitOverloadFailed,
2902 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002903 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002904 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002905 ? (RefRelationship == Sema::Ref_Related
2906 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2907 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2908 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002909
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002910 return;
2911 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002912
Douglas Gregor92e460e2011-01-20 16:44:54 +00002913 // - If the initializer expression
2914 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2915 // "cv1 T1" is reference-compatible with "cv2 T2"
2916 // Note: functions are handled below.
2917 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002918 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002920 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002921 (InitCategory.isXValue() ||
2922 (InitCategory.isPRValue() && T2->isRecordType()) ||
2923 (InitCategory.isPRValue() && T2->isArrayType()))) {
2924 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2925 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002926 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2927 // compiler the freedom to perform a copy here or bind to the
2928 // object, while C++0x requires that we bind directly to the
2929 // object. Hence, we always bind to the object without making an
2930 // extra copy. However, in C++03 requires that we check for the
2931 // presence of a suitable copy constructor:
2932 //
2933 // The constructor that would be used to make the copy shall
2934 // be callable whether or not the copy is actually done.
Francois Pichet687aaf02010-12-31 10:43:42 +00002935 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002936 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Douglas Gregor92e460e2011-01-20 16:44:54 +00002939 if (DerivedToBase)
2940 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2941 ValueKind);
2942 else if (ObjCConversion)
2943 Sequence.AddObjCObjectConversionStep(
2944 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
Douglas Gregor92e460e2011-01-20 16:44:54 +00002946 if (T1Quals != T2Quals)
2947 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00002949 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00002951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
2953 // - has a class type (i.e., T2 is a class type), where T1 is not
2954 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00002955 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2956 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00002957 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002958 if (RefRelationship == Sema::Ref_Incompatible) {
2959 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2960 Kind, Initializer,
2961 /*AllowRValues=*/true,
2962 Sequence);
2963 if (ConvOvlResult)
2964 Sequence.SetOverloadFailure(
2965 InitializationSequence::FK_ReferenceInitOverloadFailed,
2966 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002968 return;
2969 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002970
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002971 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2972 return;
2973 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002974
2975 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002976 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002977 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002978 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00002979
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002980 // Determine whether we are allowed to call explicit constructors or
2981 // explicit conversion operators.
2982 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00002983
2984 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2985
John McCall31168b02011-06-15 23:02:42 +00002986 ImplicitConversionSequence ICS
2987 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00002988 /*SuppressUserConversions*/ false,
2989 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00002990 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00002991 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
2992 /*AllowObjCWritebackConversion=*/false);
2993
2994 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002995 // FIXME: Use the conversion function set stored in ICS to turn
2996 // this into an overloading ambiguity diagnostic. However, we need
2997 // to keep that set as an OverloadCandidateSet rather than as some
2998 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002999 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3000 Sequence.SetOverloadFailure(
3001 InitializationSequence::FK_ReferenceInitOverloadFailed,
3002 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003003 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3004 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003005 else
3006 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003007 return;
John McCall31168b02011-06-15 23:02:42 +00003008 } else {
3009 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003010 }
3011
3012 // [...] If T1 is reference-related to T2, cv1 must be the
3013 // same cv-qualification as, or greater cv-qualification
3014 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003015 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3016 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003018 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003019 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3020 return;
3021 }
3022
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003024 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003026 InitCategory.isLValue()) {
3027 Sequence.SetFailed(
3028 InitializationSequence::FK_RValueReferenceBindingToLValue);
3029 return;
3030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003031
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003032 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3033 return;
3034}
3035
3036/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003037/// (C++ [dcl.init.string], C99 6.7.8).
3038static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003039 const InitializedEntity &Entity,
3040 const InitializationKind &Kind,
3041 Expr *Initializer,
3042 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003043 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003044}
3045
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003046/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3047/// enumerates the constructors of the initialized entity and performs overload
3048/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003049static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003050 const InitializedEntity &Entity,
3051 const InitializationKind &Kind,
3052 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003053 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003054 InitializationSequence &Sequence) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003055 // Build the candidate set directly in the initialization sequence
3056 // structure, so that it will persist if we fail.
3057 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3058 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003060 // Determine whether we are allowed to call explicit constructors or
3061 // explicit conversion operators.
3062 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3063 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003064 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003065
3066 // The type we're constructing needs to be complete.
3067 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003068 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003069 return;
3070 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003071
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003072 // The type we're converting to is a class type. Enumerate its constructors
3073 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003074 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003075 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003076 CXXRecordDecl *DestRecordDecl
3077 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003078
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003079 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003080 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003081 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003082 NamedDecl *D = *Con;
3083 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003084 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003085
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003086 // Find the constructor (which may be a template).
3087 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003088 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003089 if (ConstructorTmpl)
3090 Constructor = cast<CXXConstructorDecl>(
3091 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003092 else {
John McCalla0296f72010-03-19 07:35:19 +00003093 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003094
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003096 // suppress user-defined conversions on the arguments.
3097 // FIXME: Move constructors?
3098 if (Kind.getKind() == InitializationKind::IK_Copy &&
3099 Constructor->isCopyConstructor())
3100 SuppressUserConversions = true;
3101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003102
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003103 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003104 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003105 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003106 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003107 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003108 Args, NumArgs, CandidateSet,
3109 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003110 else
John McCalla0296f72010-03-19 07:35:19 +00003111 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003112 Args, NumArgs, CandidateSet,
3113 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115 }
3116
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003117 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118
3119 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003120 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003122 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003123 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003125 Result);
3126 return;
3127 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003128
3129 // C++0x [dcl.init]p6:
3130 // If a program calls for the default initialization of an object
3131 // of a const-qualified type T, T shall be a class type with a
3132 // user-provided default constructor.
3133 if (Kind.getKind() == InitializationKind::IK_Default &&
3134 Entity.getType().isConstQualified() &&
3135 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3136 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3137 return;
3138 }
3139
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003140 // Add the constructor initialization step. Any cv-qualification conversion is
3141 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003142 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003144 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003145 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003146}
3147
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003148/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003150 const InitializedEntity &Entity,
3151 const InitializationKind &Kind,
3152 InitializationSequence &Sequence) {
3153 // C++ [dcl.init]p5:
3154 //
3155 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003156 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003158 // -- if T is an array type, then each element is value-initialized;
3159 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3160 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003162 if (const RecordType *RT = T->getAs<RecordType>()) {
3163 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3164 // -- if T is a class type (clause 9) with a user-declared
3165 // constructor (12.1), then the default constructor for T is
3166 // called (and the initialization is ill-formed if T has no
3167 // accessible default constructor);
3168 //
3169 // FIXME: we really want to refer to a single subobject of the array,
3170 // but Entity doesn't have a way to capture that (yet).
3171 if (ClassDecl->hasUserDeclaredConstructor())
3172 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003173
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003174 // -- if T is a (possibly cv-qualified) non-union class type
3175 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003176 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003177 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003178 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003179 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003180 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003182 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003183 }
3184 }
3185
Douglas Gregor1b303932009-12-22 15:35:07 +00003186 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003187}
3188
Douglas Gregor85dabae2009-12-16 01:38:02 +00003189/// \brief Attempt default initialization (C++ [dcl.init]p6).
3190static void TryDefaultInitialization(Sema &S,
3191 const InitializedEntity &Entity,
3192 const InitializationKind &Kind,
3193 InitializationSequence &Sequence) {
3194 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195
Douglas Gregor85dabae2009-12-16 01:38:02 +00003196 // C++ [dcl.init]p6:
3197 // To default-initialize an object of type T means:
3198 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003199 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3200
Douglas Gregor85dabae2009-12-16 01:38:02 +00003201 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3202 // constructor for T is called (and the initialization is ill-formed if
3203 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003204 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003205 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3206 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003208
Douglas Gregor85dabae2009-12-16 01:38:02 +00003209 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
Douglas Gregor85dabae2009-12-16 01:38:02 +00003211 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003213 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003214 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003215 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003216 return;
3217 }
3218
3219 // If the destination type has a lifetime property, zero-initialize it.
3220 if (DestType.getQualifiers().hasObjCLifetime()) {
3221 Sequence.AddZeroInitializationStep(Entity.getType());
3222 return;
3223 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003224}
3225
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003226/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3227/// which enumerates all conversion functions and performs overload resolution
3228/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003230 const InitializedEntity &Entity,
3231 const InitializationKind &Kind,
3232 Expr *Initializer,
3233 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003234 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003235 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3236 QualType SourceType = Initializer->getType();
3237 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3238 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239
Douglas Gregor540c3b02009-12-14 17:27:33 +00003240 // Build the candidate set directly in the initialization sequence
3241 // structure, so that it will persist if we fail.
3242 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3243 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244
Douglas Gregor540c3b02009-12-14 17:27:33 +00003245 // Determine whether we are allowed to call explicit constructors or
3246 // explicit conversion operators.
3247 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Douglas Gregor540c3b02009-12-14 17:27:33 +00003249 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3250 // The type we're converting to is a class type. Enumerate its constructors
3251 // to see if there is a suitable conversion.
3252 CXXRecordDecl *DestRecordDecl
3253 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Douglas Gregord9848152010-04-26 14:36:57 +00003255 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003257 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003258 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003259 Con != ConEnd; ++Con) {
3260 NamedDecl *D = *Con;
3261 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262
Douglas Gregord9848152010-04-26 14:36:57 +00003263 // Find the constructor (which may be a template).
3264 CXXConstructorDecl *Constructor = 0;
3265 FunctionTemplateDecl *ConstructorTmpl
3266 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003267 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003268 Constructor = cast<CXXConstructorDecl>(
3269 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003270 else
Douglas Gregord9848152010-04-26 14:36:57 +00003271 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272
Douglas Gregord9848152010-04-26 14:36:57 +00003273 if (!Constructor->isInvalidDecl() &&
3274 Constructor->isConvertingConstructor(AllowExplicit)) {
3275 if (ConstructorTmpl)
3276 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3277 /*ExplicitArgs*/ 0,
3278 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003279 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003280 else
3281 S.AddOverloadCandidate(Constructor, FoundDecl,
3282 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003283 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003285 }
Douglas Gregord9848152010-04-26 14:36:57 +00003286 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003287 }
Eli Friedman78275202009-12-19 08:11:05 +00003288
3289 SourceLocation DeclLoc = Initializer->getLocStart();
3290
Douglas Gregor540c3b02009-12-14 17:27:33 +00003291 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3292 // The type we're converting from is a class type, enumerate its conversion
3293 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003294
Eli Friedman4afe9a32009-12-20 22:12:03 +00003295 // We can only enumerate the conversion functions for a complete type; if
3296 // the type isn't complete, simply skip this step.
3297 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3298 CXXRecordDecl *SourceRecordDecl
3299 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300
John McCallad371252010-01-20 00:46:10 +00003301 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003302 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003303 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003305 I != E; ++I) {
3306 NamedDecl *D = *I;
3307 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3308 if (isa<UsingShadowDecl>(D))
3309 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310
Eli Friedman4afe9a32009-12-20 22:12:03 +00003311 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3312 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003313 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003314 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003315 else
John McCallda4458e2010-03-31 01:36:47 +00003316 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003317
Eli Friedman4afe9a32009-12-20 22:12:03 +00003318 if (AllowExplicit || !Conv->isExplicit()) {
3319 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003320 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003321 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003322 CandidateSet);
3323 else
John McCalla0296f72010-03-19 07:35:19 +00003324 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003325 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003326 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003327 }
3328 }
3329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330
3331 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003332 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003333 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003334 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003335 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003337 Result);
3338 return;
3339 }
John McCall0d1da222010-01-12 00:44:57 +00003340
Douglas Gregor540c3b02009-12-14 17:27:33 +00003341 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003342 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
Douglas Gregor540c3b02009-12-14 17:27:33 +00003344 if (isa<CXXConstructorDecl>(Function)) {
3345 // Add the user-defined conversion step. Any cv-qualification conversion is
3346 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003347 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003348 return;
3349 }
3350
3351 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003352 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003353 if (ConvType->getAs<RecordType>()) {
3354 // If we're converting to a class type, there may be an copy if
3355 // the resulting temporary object (possible to create an object of
3356 // a base class type). That copy is not a separate conversion, so
3357 // we just make a note of the actual destination type (possibly a
3358 // base class of the type returned by the conversion function) and
3359 // let the user-defined conversion step handle the conversion.
3360 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3361 return;
3362 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003363
Douglas Gregor5ab11652010-04-17 22:01:05 +00003364 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
Douglas Gregor5ab11652010-04-17 22:01:05 +00003366 // If the conversion following the call to the conversion function
3367 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003368 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3369 Best->FinalConversion.Third) {
3370 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003371 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003372 ICS.Standard = Best->FinalConversion;
3373 Sequence.AddConversionSequenceStep(ICS, DestType);
3374 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003375}
3376
John McCall31168b02011-06-15 23:02:42 +00003377/// The non-zero enum values here are indexes into diagnostic alternatives.
3378enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3379
3380/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003381static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3382 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003383 // Skip parens.
3384 e = e->IgnoreParens();
3385
3386 // Skip address-of nodes.
3387 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3388 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003389 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003390
3391 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003392 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3393 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003394 case CK_Dependent:
3395 case CK_BitCast:
3396 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003397 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003398 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003399
3400 case CK_ArrayToPointerDecay:
3401 return IIK_nonscalar;
3402
3403 case CK_NullToPointer:
3404 return IIK_okay;
3405
3406 default:
3407 break;
3408 }
3409
3410 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003411 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3412 if (!isAddressOf) return IIK_nonlocal;
3413
3414 VarDecl *var;
3415 if (isa<DeclRefExpr>(e)) {
3416 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3417 if (!var) return IIK_nonlocal;
3418 } else {
3419 var = cast<BlockDeclRefExpr>(e)->getDecl();
3420 }
3421
3422 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003423
3424 // If we have a conditional operator, check both sides.
3425 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003426 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003427 return iik;
3428
John McCall63f84442011-06-27 23:59:58 +00003429 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003430
3431 // These are never scalar.
3432 } else if (isa<ArraySubscriptExpr>(e)) {
3433 return IIK_nonscalar;
3434
3435 // Otherwise, it needs to be a null pointer constant.
3436 } else {
3437 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3438 ? IIK_okay : IIK_nonlocal);
3439 }
3440
3441 return IIK_nonlocal;
3442}
3443
3444/// Check whether the given expression is a valid operand for an
3445/// indirect copy/restore.
3446static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3447 assert(src->isRValue());
3448
John McCall63f84442011-06-27 23:59:58 +00003449 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003450 if (iik == IIK_okay) return;
3451
3452 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3453 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3454 << src->getSourceRange();
3455}
3456
Douglas Gregore2f943b2011-02-22 18:29:51 +00003457/// \brief Determine whether we have compatible array types for the
3458/// purposes of GNU by-copy array initialization.
3459static bool hasCompatibleArrayTypes(ASTContext &Context,
3460 const ArrayType *Dest,
3461 const ArrayType *Source) {
3462 // If the source and destination array types are equivalent, we're
3463 // done.
3464 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3465 return true;
3466
3467 // Make sure that the element types are the same.
3468 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3469 return false;
3470
3471 // The only mismatch we allow is when the destination is an
3472 // incomplete array type and the source is a constant array type.
3473 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3474}
3475
John McCall31168b02011-06-15 23:02:42 +00003476static bool tryObjCWritebackConversion(Sema &S,
3477 InitializationSequence &Sequence,
3478 const InitializedEntity &Entity,
3479 Expr *Initializer) {
3480 bool ArrayDecay = false;
3481 QualType ArgType = Initializer->getType();
3482 QualType ArgPointee;
3483 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3484 ArrayDecay = true;
3485 ArgPointee = ArgArrayType->getElementType();
3486 ArgType = S.Context.getPointerType(ArgPointee);
3487 }
3488
3489 // Handle write-back conversion.
3490 QualType ConvertedArgType;
3491 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3492 ConvertedArgType))
3493 return false;
3494
3495 // We should copy unless we're passing to an argument explicitly
3496 // marked 'out'.
3497 bool ShouldCopy = true;
3498 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3499 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3500
3501 // Do we need an lvalue conversion?
3502 if (ArrayDecay || Initializer->isGLValue()) {
3503 ImplicitConversionSequence ICS;
3504 ICS.setStandard();
3505 ICS.Standard.setAsIdentityConversion();
3506
3507 QualType ResultType;
3508 if (ArrayDecay) {
3509 ICS.Standard.First = ICK_Array_To_Pointer;
3510 ResultType = S.Context.getPointerType(ArgPointee);
3511 } else {
3512 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3513 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3514 }
3515
3516 Sequence.AddConversionSequenceStep(ICS, ResultType);
3517 }
3518
3519 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3520 return true;
3521}
3522
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003523InitializationSequence::InitializationSequence(Sema &S,
3524 const InitializedEntity &Entity,
3525 const InitializationKind &Kind,
3526 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003527 unsigned NumArgs)
3528 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003529 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003531 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003532 // The semantics of initializers are as follows. The destination type is
3533 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003534 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003536 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003537 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003539 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003540 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3541 SequenceKind = DependentSequence;
3542 return;
3543 }
3544
Sebastian Redld201edf2011-06-05 13:59:11 +00003545 // Almost everything is a normal sequence.
3546 setSequenceKind(NormalSequence);
3547
John McCalled75c092010-12-07 22:54:16 +00003548 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003549 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3550 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3551 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003552 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003553 return;
3554 }
3555 Args[I] = Result.take();
3556 }
John McCalled75c092010-12-07 22:54:16 +00003557
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003558 QualType SourceType;
3559 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003560 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003561 Initializer = Args[0];
3562 if (!isa<InitListExpr>(Initializer))
3563 SourceType = Initializer->getType();
3564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565
3566 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003567 // list-initialized (8.5.4).
3568 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003569 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003570 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003573 // - If the destination type is a reference type, see 8.5.3.
3574 if (DestType->isReferenceType()) {
3575 // C++0x [dcl.init.ref]p1:
3576 // A variable declared to be a T& or T&&, that is, "reference to type T"
3577 // (8.3.2), shall be initialized by an object, or function, of type T or
3578 // by an object that can be converted into a T.
3579 // (Therefore, multiple arguments are not permitted.)
3580 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003581 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003582 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003583 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003584 return;
3585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003587 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003588 if (Kind.getKind() == InitializationKind::IK_Value ||
3589 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003590 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003591 return;
3592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003593
Douglas Gregor85dabae2009-12-16 01:38:02 +00003594 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003595 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003596 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003597 return;
3598 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003599
John McCall66884dd2011-02-21 07:22:22 +00003600 // - If the destination type is an array of characters, an array of
3601 // char16_t, an array of char32_t, or an array of wchar_t, and the
3602 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003605 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3606 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003607 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003608 return;
3609 }
3610
Douglas Gregore2f943b2011-02-22 18:29:51 +00003611 // Note: as an GNU C extension, we allow initialization of an
3612 // array from a compound literal that creates an array of the same
3613 // type, so long as the initializer has no side effects.
3614 if (!S.getLangOptions().CPlusPlus && Initializer &&
3615 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3616 Initializer->getType()->isArrayType()) {
3617 const ArrayType *SourceAT
3618 = Context.getAsArrayType(Initializer->getType());
3619 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003620 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003621 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003622 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003623 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003624 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003625 }
3626 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003627 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003628 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003629 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003631 return;
3632 }
Eli Friedman78275202009-12-19 08:11:05 +00003633
John McCall31168b02011-06-15 23:02:42 +00003634 // Determine whether we should consider writeback conversions for
3635 // Objective-C ARC.
3636 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3637 Entity.getKind() == InitializedEntity::EK_Parameter;
3638
3639 // We're at the end of the line for C: it's either a write-back conversion
3640 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003641 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003642 // If allowed, check whether this is an Objective-C writeback conversion.
3643 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003644 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003645 return;
3646 }
3647
3648 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003649 AddCAssignmentStep(DestType);
3650 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003651 return;
3652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653
John McCall31168b02011-06-15 23:02:42 +00003654 assert(S.getLangOptions().CPlusPlus);
3655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 // - If the destination type is a (possibly cv-qualified) class type:
3657 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 // - If the initialization is direct-initialization, or if it is
3659 // copy-initialization where the cv-unqualified version of the
3660 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003661 // class of the destination, constructors are considered. [...]
3662 if (Kind.getKind() == InitializationKind::IK_Direct ||
3663 (Kind.getKind() == InitializationKind::IK_Copy &&
3664 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3665 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003667 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003669 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003670 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003671 // used) to a derived class thereof are enumerated as described in
3672 // 13.3.1.4, and the best one is chosen through overload resolution
3673 // (13.3).
3674 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003675 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003676 return;
3677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Douglas Gregor85dabae2009-12-16 01:38:02 +00003679 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003680 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003681 return;
3682 }
3683 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684
3685 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003686 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003687 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003688 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3689 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003690 return;
3691 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003692
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003693 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003694 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003695 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003696 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003697 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003698
3699 ImplicitConversionSequence ICS
3700 = S.TryImplicitConversion(Initializer, Entity.getType(),
3701 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003702 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003703 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003704 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3705 allowObjCWritebackConversion);
3706
3707 if (ICS.isStandard() &&
3708 ICS.Standard.Second == ICK_Writeback_Conversion) {
3709 // Objective-C ARC writeback conversion.
3710
3711 // We should copy unless we're passing to an argument explicitly
3712 // marked 'out'.
3713 bool ShouldCopy = true;
3714 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3715 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3716
3717 // If there was an lvalue adjustment, add it as a separate conversion.
3718 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3719 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3720 ImplicitConversionSequence LvalueICS;
3721 LvalueICS.setStandard();
3722 LvalueICS.Standard.setAsIdentityConversion();
3723 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3724 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003725 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003726 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003727
3728 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003729 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003730 DeclAccessPair dap;
3731 if (Initializer->getType() == Context.OverloadTy &&
3732 !S.ResolveAddressOfOverloadedFunction(Initializer
3733 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003734 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003735 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003736 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003737 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003738 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003739
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003740 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003741 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742}
3743
3744InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003745 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003746 StepEnd = Steps.end();
3747 Step != StepEnd; ++Step)
3748 Step->Destroy();
3749}
3750
3751//===----------------------------------------------------------------------===//
3752// Perform initialization
3753//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003755getAssignmentAction(const InitializedEntity &Entity) {
3756 switch(Entity.getKind()) {
3757 case InitializedEntity::EK_Variable:
3758 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003759 case InitializedEntity::EK_Exception:
3760 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003761 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003762 return Sema::AA_Initializing;
3763
3764 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003766 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3767 return Sema::AA_Sending;
3768
Douglas Gregore1314a62009-12-18 05:02:21 +00003769 return Sema::AA_Passing;
3770
3771 case InitializedEntity::EK_Result:
3772 return Sema::AA_Returning;
3773
Douglas Gregore1314a62009-12-18 05:02:21 +00003774 case InitializedEntity::EK_Temporary:
3775 // FIXME: Can we tell apart casting vs. converting?
3776 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
Douglas Gregore1314a62009-12-18 05:02:21 +00003778 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003779 case InitializedEntity::EK_ArrayElement:
3780 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003781 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003782 return Sema::AA_Initializing;
3783 }
3784
3785 return Sema::AA_Converting;
3786}
3787
Douglas Gregor95562572010-04-24 23:45:46 +00003788/// \brief Whether we should binding a created object as a temporary when
3789/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003790static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003791 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003792 case InitializedEntity::EK_ArrayElement:
3793 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003794 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003795 case InitializedEntity::EK_New:
3796 case InitializedEntity::EK_Variable:
3797 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003798 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003799 case InitializedEntity::EK_VectorElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003800 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003801 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003802 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregore1314a62009-12-18 05:02:21 +00003804 case InitializedEntity::EK_Parameter:
3805 case InitializedEntity::EK_Temporary:
3806 return true;
3807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808
Douglas Gregore1314a62009-12-18 05:02:21 +00003809 llvm_unreachable("missed an InitializedEntity kind?");
3810}
3811
Douglas Gregor95562572010-04-24 23:45:46 +00003812/// \brief Whether the given entity, when initialized with an object
3813/// created for that initialization, requires destruction.
3814static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3815 switch (Entity.getKind()) {
3816 case InitializedEntity::EK_Member:
3817 case InitializedEntity::EK_Result:
3818 case InitializedEntity::EK_New:
3819 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003820 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003821 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003822 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003823 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824
Douglas Gregor95562572010-04-24 23:45:46 +00003825 case InitializedEntity::EK_Variable:
3826 case InitializedEntity::EK_Parameter:
3827 case InitializedEntity::EK_Temporary:
3828 case InitializedEntity::EK_ArrayElement:
3829 case InitializedEntity::EK_Exception:
3830 return true;
3831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832
3833 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003834}
3835
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003836/// \brief Make a (potentially elidable) temporary copy of the object
3837/// provided by the given initializer by calling the appropriate copy
3838/// constructor.
3839///
3840/// \param S The Sema object used for type-checking.
3841///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003842/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003843/// the type of the initializer expression or a superclass thereof.
3844///
3845/// \param Enter The entity being initialized.
3846///
3847/// \param CurInit The initializer expression.
3848///
3849/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3850/// is permitted in C++03 (but not C++0x) when binding a reference to
3851/// an rvalue.
3852///
3853/// \returns An expression that copies the initializer expression into
3854/// a temporary object, or an error expression if a copy could not be
3855/// created.
John McCalldadc5752010-08-24 06:29:42 +00003856static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003857 QualType T,
3858 const InitializedEntity &Entity,
3859 ExprResult CurInit,
3860 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003861 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003862 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003864 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003865 Class = cast<CXXRecordDecl>(Record->getDecl());
3866 if (!Class)
3867 return move(CurInit);
3868
Douglas Gregor5d369002011-01-21 18:05:27 +00003869 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003870 // When certain criteria are met, an implementation is allowed to
3871 // omit the copy/move construction of a class object, even if the
3872 // copy/move constructor and/or destructor for the object have
3873 // side effects. [...]
3874 // - when a temporary class object that has not been bound to a
3875 // reference (12.2) would be copied/moved to a class object
3876 // with the same cv-unqualified type, the copy/move operation
3877 // can be omitted by constructing the temporary object
3878 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003880 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003881 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003883 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003884 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003885 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003886 switch (Entity.getKind()) {
3887 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003888 Loc = Entity.getReturnLoc();
3889 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890
Douglas Gregore1314a62009-12-18 05:02:21 +00003891 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003892 Loc = Entity.getThrowLoc();
3893 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894
Douglas Gregore1314a62009-12-18 05:02:21 +00003895 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003896 Loc = Entity.getDecl()->getLocation();
3897 break;
3898
Anders Carlsson0bd52402010-01-24 00:19:41 +00003899 case InitializedEntity::EK_ArrayElement:
3900 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003901 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003902 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003903 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003904 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003905 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003906 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003907 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003908 Loc = CurInitExpr->getLocStart();
3909 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003910 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003911
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003913 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3914 return move(CurInit);
3915
Douglas Gregorf282a762011-01-21 19:38:21 +00003916 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00003917 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00003918 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00003919 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003920 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003921 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00003922 // C++0x [dcl.init]p16, second bullet to class types, this
3923 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003924 CXXConstructorDecl *Constructor = 0;
3925
3926 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00003927 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003928 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00003929 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00003930 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003931 continue;
3932
3933 DeclAccessPair FoundDecl
3934 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3935 S.AddOverloadCandidate(Constructor, FoundDecl,
3936 &CurInitExpr, 1, CandidateSet);
3937 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003939
3940 // Handle constructor templates.
3941 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3942 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00003943 continue;
John McCalla0296f72010-03-19 07:35:19 +00003944
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003945 Constructor = cast<CXXConstructorDecl>(
3946 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00003947 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003948 continue;
3949
3950 // FIXME: Do we need to limit this to copy-constructor-like
3951 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00003952 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003953 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3954 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3955 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957
Douglas Gregore1314a62009-12-18 05:02:21 +00003958 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00003959 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003960 case OR_Success:
3961 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003962
Douglas Gregore1314a62009-12-18 05:02:21 +00003963 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003964 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3965 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3966 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003967 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003968 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003969 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003970 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00003971 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003972 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregore1314a62009-12-18 05:02:21 +00003974 case OR_Ambiguous:
3975 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003976 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003977 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00003978 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00003979 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980
Douglas Gregore1314a62009-12-18 05:02:21 +00003981 case OR_Deleted:
3982 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003983 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003984 << CurInitExpr->getSourceRange();
3985 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00003986 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00003987 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003988 }
3989
Douglas Gregor5ab11652010-04-17 22:01:05 +00003990 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00003991 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00003992 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003993
Anders Carlssona01874b2010-04-21 18:47:17 +00003994 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00003995 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003996
3997 if (IsExtraneousCopy) {
3998 // If this is a totally extraneous copy for C++03 reference
3999 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004000 // expression. We don't generate an (elided) copy operation here
4001 // because doing so would require us to pass down a flag to avoid
4002 // infinite recursion, where each step adds another extraneous,
4003 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004004
Douglas Gregor30b52772010-04-18 07:57:34 +00004005 // Instantiate the default arguments of any extra parameters in
4006 // the selected copy constructor, as if we were going to create a
4007 // proper call to the copy constructor.
4008 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4009 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4010 if (S.RequireCompleteType(Loc, Parm->getType(),
4011 S.PDiag(diag::err_call_incomplete_argument)))
4012 break;
4013
4014 // Build the default argument expression; we don't actually care
4015 // if this succeeds or not, because this routine will complain
4016 // if there was a problem.
4017 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4018 }
4019
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004020 return S.Owned(CurInitExpr);
4021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022
Chandler Carruth30141632011-02-25 19:41:05 +00004023 S.MarkDeclarationReferenced(Loc, Constructor);
4024
Douglas Gregor5ab11652010-04-17 22:01:05 +00004025 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004026 // constructor call (we might have derived-to-base conversions, or
4027 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004028 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004029 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004030 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004031
Douglas Gregord0ace022010-04-25 00:55:24 +00004032 // Actually perform the constructor call.
4033 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004034 move_arg(ConstructorArgs),
4035 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004036 CXXConstructExpr::CK_Complete,
4037 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004038
Douglas Gregord0ace022010-04-25 00:55:24 +00004039 // If we're supposed to bind temporaries, do so.
4040 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4041 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4042 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004043}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004044
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004045void InitializationSequence::PrintInitLocationNote(Sema &S,
4046 const InitializedEntity &Entity) {
4047 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4048 if (Entity.getDecl()->getLocation().isInvalid())
4049 return;
4050
4051 if (Entity.getDecl()->getDeclName())
4052 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4053 << Entity.getDecl()->getDeclName();
4054 else
4055 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4056 }
4057}
4058
Sebastian Redl112aa822011-07-14 19:07:55 +00004059static bool isReferenceBinding(const InitializationSequence::Step &s) {
4060 return s.Kind == InitializationSequence::SK_BindReference ||
4061 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4062}
4063
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004064ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004065InitializationSequence::Perform(Sema &S,
4066 const InitializedEntity &Entity,
4067 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004068 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004069 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004070 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004071 unsigned NumArgs = Args.size();
4072 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004073 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075
Sebastian Redld201edf2011-06-05 13:59:11 +00004076 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004077 // If the declaration is a non-dependent, incomplete array type
4078 // that has an initializer, then its type will be completed once
4079 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004080 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004081 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004082 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004083 if (const IncompleteArrayType *ArrayT
4084 = S.Context.getAsIncompleteArrayType(DeclType)) {
4085 // FIXME: We don't currently have the ability to accurately
4086 // compute the length of an initializer list without
4087 // performing full type-checking of the initializer list
4088 // (since we have to determine where braces are implicitly
4089 // introduced and such). So, we fall back to making the array
4090 // type a dependently-sized array type with no specified
4091 // bound.
4092 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4093 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004094
Douglas Gregor51e77d52009-12-10 17:56:55 +00004095 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004096 if (DeclaratorDecl *DD = Entity.getDecl()) {
4097 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4098 TypeLoc TL = TInfo->getTypeLoc();
4099 if (IncompleteArrayTypeLoc *ArrayLoc
4100 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4101 Brackets = ArrayLoc->getBracketsRange();
4102 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004103 }
4104
4105 *ResultType
4106 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4107 /*NumElts=*/0,
4108 ArrayT->getSizeModifier(),
4109 ArrayT->getIndexTypeCVRQualifiers(),
4110 Brackets);
4111 }
4112
4113 }
4114 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004115 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4116 Kind.isExplicitCast());
4117 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004118 }
4119
Sebastian Redld201edf2011-06-05 13:59:11 +00004120 // No steps means no initialization.
4121 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004122 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004123
Douglas Gregor1b303932009-12-22 15:35:07 +00004124 QualType DestType = Entity.getType().getNonReferenceType();
4125 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004126 // the same as Entity.getDecl()->getType() in cases involving type merging,
4127 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004128 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004129 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004130 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004131
John McCalldadc5752010-08-24 06:29:42 +00004132 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004135 // grab the only argument out the Args and place it into the "current"
4136 // initializer.
4137 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004138 case SK_ResolveAddressOfOverloadedFunction:
4139 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004140 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004141 case SK_CastDerivedToBaseLValue:
4142 case SK_BindReference:
4143 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004144 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004145 case SK_UserConversion:
4146 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004147 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004148 case SK_QualificationConversionRValue:
4149 case SK_ConversionSequence:
4150 case SK_ListInitialization:
4151 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004152 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004153 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004154 case SK_ArrayInit:
4155 case SK_PassByIndirectCopyRestore:
4156 case SK_PassByIndirectRestore:
4157 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004158 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004159 CurInit = Args.get()[0];
4160 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004161
4162 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004163 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4164 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4165 if (CurInit.isInvalid())
4166 return ExprError();
4167 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004168 break;
John McCall34376a62010-12-04 03:47:34 +00004169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregore1314a62009-12-18 05:02:21 +00004171 case SK_ConstructorInitialization:
4172 case SK_ZeroInitialization:
4173 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175
4176 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004177 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004178 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004179 for (step_iterator Step = step_begin(), StepEnd = step_end();
4180 Step != StepEnd; ++Step) {
4181 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004182 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183
John Wiegley01296292011-04-08 18:41:53 +00004184 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004185
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004186 switch (Step->Kind) {
4187 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004189 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004190 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004191 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004192 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004193 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004194 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004195 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004196
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004197 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004198 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004199 case SK_CastDerivedToBaseLValue: {
4200 // We have a derived-to-base cast that produces either an rvalue or an
4201 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202
John McCallcf142162010-08-07 06:22:56 +00004203 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004204
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004205 // Casts to inaccessible base classes are allowed with C-style casts.
4206 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4207 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004208 CurInit.get()->getLocStart(),
4209 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004210 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004211 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212
Douglas Gregor88d292c2010-05-13 16:44:06 +00004213 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4214 QualType T = SourceType;
4215 if (const PointerType *Pointer = T->getAs<PointerType>())
4216 T = Pointer->getPointeeType();
4217 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004218 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004219 cast<CXXRecordDecl>(RecordTy->getDecl()));
4220 }
4221
John McCall2536c6d2010-08-25 10:28:54 +00004222 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004223 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004224 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004225 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004226 VK_XValue :
4227 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004228 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4229 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004230 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004231 CurInit.get(),
4232 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004233 break;
4234 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004236 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004237 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004238 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4239 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004240 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004242 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004243 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004244 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004245 }
Anders Carlssona91be642010-01-29 02:47:33 +00004246
John Wiegley01296292011-04-08 18:41:53 +00004247 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004248 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004249 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4250 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004251 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004252 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004253 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004256 // Reference binding does not have any corresponding ASTs.
4257
4258 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004259 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004260 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004261
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004262 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004263
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004264 case SK_BindReferenceToTemporary:
4265 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004266 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004267 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004268
Douglas Gregorfe314812011-06-21 17:03:29 +00004269 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004270 CurInit = new (S.Context) MaterializeTemporaryExpr(
4271 Entity.getType().getNonReferenceType(),
4272 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004273 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004274
4275 // If we're binding to an Objective-C object that has lifetime, we
4276 // need cleanups.
4277 if (S.getLangOptions().ObjCAutoRefCount &&
4278 CurInit.get()->getType()->isObjCLifetimeType())
4279 S.ExprNeedsCleanups = true;
4280
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004281 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004283 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004285 /*IsExtraneousCopy=*/true);
4286 break;
4287
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004288 case SK_UserConversion: {
4289 // We have a user-defined conversion that invokes either a constructor
4290 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004291 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004292 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004293 FunctionDecl *Fn = Step->Function.Function;
4294 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004295 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004296 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004297 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004298 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004299 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004300 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004301 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004302
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004303 // Determine the arguments required to actually perform the constructor
4304 // call.
John Wiegley01296292011-04-08 18:41:53 +00004305 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004306 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004307 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004308 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004309 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004311 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004313 move_arg(ConstructorArgs),
4314 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004315 CXXConstructExpr::CK_Complete,
4316 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004317 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004318 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004319
Anders Carlssona01874b2010-04-21 18:47:17 +00004320 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004321 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004322 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
John McCalle3027922010-08-25 11:45:40 +00004324 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004325 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4326 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4327 S.IsDerivedFrom(SourceType, Class))
4328 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Douglas Gregor95562572010-04-24 23:45:46 +00004330 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004331 } else {
4332 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004333 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004334 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004335 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004336 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004337 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
4339 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004340 // derived-to-base conversion? I believe the answer is "no", because
4341 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004342 ExprResult CurInitExprRes =
4343 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4344 FoundFn, Conversion);
4345 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004346 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004347 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004349 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004350 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004351 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004352 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353
John McCalle3027922010-08-25 11:45:40 +00004354 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355
Douglas Gregor95562572010-04-24 23:45:46 +00004356 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358
Sebastian Redl112aa822011-07-14 19:07:55 +00004359 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004360 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004361 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004362 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004363 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004364 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004366 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004367 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004368 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004369 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4370 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004371 }
4372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004374 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004375 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004376 CurInit.get()->getType(),
4377 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004378 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004380 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004381 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4382 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004383
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004384 break;
4385 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004386
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004387 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004388 case SK_QualificationConversionXValue:
4389 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004390 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004391 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004392 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004393 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004394 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004395 VK_XValue :
4396 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004397 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004398 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004399 }
4400
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004401 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004402 Sema::CheckedConversionKind CCK
4403 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4404 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4405 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4406 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004407 ExprResult CurInitExprRes =
4408 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004409 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004410 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004411 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004412 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004413 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415
Douglas Gregor51e77d52009-12-10 17:56:55 +00004416 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004417 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004418 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00004419 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00004420 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004421
4422 CurInit.release();
4423 CurInit = S.Owned(InitList);
4424 break;
4425 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004426
4427 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004428 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004429 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004430 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004432 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004433 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004434 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4435 ? Kind.getEqualLoc()
4436 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004437
4438 if (Kind.getKind() == InitializationKind::IK_Default) {
4439 // Force even a trivial, implicit default constructor to be
4440 // semantically checked. We do this explicitly because we don't build
4441 // the definition for completely trivial constructors.
4442 CXXRecordDecl *ClassDecl = Constructor->getParent();
4443 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004444 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004445 ClassDecl->hasTrivialDefaultConstructor() &&
4446 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004447 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4448 }
4449
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004450 // Determine the arguments required to actually perform the constructor
4451 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004453 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004454 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455
4456
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004457 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004458 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004459 (Kind.getKind() == InitializationKind::IK_Direct ||
4460 Kind.getKind() == InitializationKind::IK_Value)) {
4461 // An explicitly-constructed temporary, e.g., X(1, 2).
4462 unsigned NumExprs = ConstructorArgs.size();
4463 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004464 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004465 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466
Douglas Gregor2b88c112010-09-08 00:15:04 +00004467 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4468 if (!TSInfo)
4469 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004471 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4472 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004473 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004475 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004476 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004477 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004478 } else {
4479 CXXConstructExpr::ConstructionKind ConstructKind =
4480 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004482 if (Entity.getKind() == InitializedEntity::EK_Base) {
4483 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004484 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004485 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004486 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004487 ConstructKind = CXXConstructExpr::CK_Delegating;
4488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489
Chandler Carruth01718152010-10-25 08:47:36 +00004490 // Only get the parenthesis range if it is a direct construction.
4491 SourceRange parenRange =
4492 Kind.getKind() == InitializationKind::IK_Direct ?
4493 Kind.getParenRange() : SourceRange();
4494
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004495 // If the entity allows NRVO, mark the construction as elidable
4496 // unconditionally.
4497 if (Entity.allowsNRVO())
4498 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4499 Constructor, /*Elidable=*/true,
4500 move_arg(ConstructorArgs),
4501 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004502 ConstructKind,
4503 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004504 else
4505 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004507 move_arg(ConstructorArgs),
4508 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004509 ConstructKind,
4510 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004511 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004512 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004513 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004514
4515 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004516 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004517 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004518 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004520 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004521 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004523 break;
4524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004526 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004527 step_iterator NextStep = Step;
4528 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004530 NextStep->Kind == SK_ConstructorInitialization) {
4531 // The need for zero-initialization is recorded directly into
4532 // the call to the object's constructor within the next step.
4533 ConstructorInitRequiresZeroInit = true;
4534 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4535 S.getLangOptions().CPlusPlus &&
4536 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004537 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4538 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004540 Kind.getRange().getBegin());
4541
4542 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4543 TSInfo->getType().getNonLValueExprType(S.Context),
4544 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004545 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004546 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004547 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004548 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004549 break;
4550 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004551
4552 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004553 QualType SourceType = CurInit.get()->getType();
4554 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004555 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004556 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4557 if (Result.isInvalid())
4558 return ExprError();
4559 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004560
4561 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004562 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004563 if (ConvTy != Sema::Compatible &&
4564 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004565 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004566 == Sema::Compatible)
4567 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004568 if (CurInitExprRes.isInvalid())
4569 return ExprError();
4570 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004571
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004572 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004573 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4574 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004575 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004576 getAssignmentAction(Entity),
4577 &Complained)) {
4578 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004579 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004580 } else if (Complained)
4581 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004582 break;
4583 }
Eli Friedman78275202009-12-19 08:11:05 +00004584
4585 case SK_StringInit: {
4586 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004587 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004588 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004589 break;
4590 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004591
4592 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004593 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004594 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004595 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004596 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004597
4598 case SK_ArrayInit:
4599 // Okay: we checked everything before creating this step. Note that
4600 // this is a GNU extension.
4601 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004602 << Step->Type << CurInit.get()->getType()
4603 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004604
4605 // If the destination type is an incomplete array type, update the
4606 // type accordingly.
4607 if (ResultType) {
4608 if (const IncompleteArrayType *IncompleteDest
4609 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4610 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004611 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004612 *ResultType = S.Context.getConstantArrayType(
4613 IncompleteDest->getElementType(),
4614 ConstantSource->getSize(),
4615 ArrayType::Normal, 0);
4616 }
4617 }
4618 }
John McCall31168b02011-06-15 23:02:42 +00004619 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004620
John McCall31168b02011-06-15 23:02:42 +00004621 case SK_PassByIndirectCopyRestore:
4622 case SK_PassByIndirectRestore:
4623 checkIndirectCopyRestoreSource(S, CurInit.get());
4624 CurInit = S.Owned(new (S.Context)
4625 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4626 Step->Kind == SK_PassByIndirectCopyRestore));
4627 break;
4628
4629 case SK_ProduceObjCObject:
4630 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4631 CK_ObjCProduceObject,
4632 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004633 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004634 }
4635 }
John McCall1f425642010-11-11 03:21:53 +00004636
4637 // Diagnose non-fatal problems with the completed initialization.
4638 if (Entity.getKind() == InitializedEntity::EK_Member &&
4639 cast<FieldDecl>(Entity.getDecl())->isBitField())
4640 S.CheckBitFieldInitialization(Kind.getLocation(),
4641 cast<FieldDecl>(Entity.getDecl()),
4642 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004644 return move(CurInit);
4645}
4646
4647//===----------------------------------------------------------------------===//
4648// Diagnose initialization failures
4649//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004651 const InitializedEntity &Entity,
4652 const InitializationKind &Kind,
4653 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004654 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004655 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656
Douglas Gregor1b303932009-12-22 15:35:07 +00004657 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004658 switch (Failure) {
4659 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004660 // FIXME: Customize for the initialized entity?
4661 if (NumArgs == 0)
4662 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4663 << DestType.getNonReferenceType();
4664 else // FIXME: diagnostic below could be better!
4665 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4666 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004667 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004669 case FK_ArrayNeedsInitList:
4670 case FK_ArrayNeedsInitListOrStringLiteral:
4671 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4672 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4673 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregore2f943b2011-02-22 18:29:51 +00004675 case FK_ArrayTypeMismatch:
4676 case FK_NonConstantArrayInit:
4677 S.Diag(Kind.getLocation(),
4678 (Failure == FK_ArrayTypeMismatch
4679 ? diag::err_array_init_different_type
4680 : diag::err_array_init_non_constant_array))
4681 << DestType.getNonReferenceType()
4682 << Args[0]->getType()
4683 << Args[0]->getSourceRange();
4684 break;
4685
John McCall16df1e52010-03-30 21:47:33 +00004686 case FK_AddressOfOverloadFailed: {
4687 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004689 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004690 true,
4691 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004692 break;
John McCall16df1e52010-03-30 21:47:33 +00004693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004695 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004696 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004697 switch (FailedOverloadResult) {
4698 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004699 if (Failure == FK_UserConversionOverloadFailed)
4700 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4701 << Args[0]->getType() << DestType
4702 << Args[0]->getSourceRange();
4703 else
4704 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4705 << DestType << Args[0]->getType()
4706 << Args[0]->getSourceRange();
4707
John McCall5c32be02010-08-24 20:38:10 +00004708 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004709 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004711 case OR_No_Viable_Function:
4712 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4713 << Args[0]->getType() << DestType.getNonReferenceType()
4714 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004715 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004716 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004718 case OR_Deleted: {
4719 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4720 << Args[0]->getType() << DestType.getNonReferenceType()
4721 << Args[0]->getSourceRange();
4722 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004723 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004724 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4725 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004726 if (Ovl == OR_Deleted) {
4727 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004728 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004729 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004730 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004731 }
4732 break;
4733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004735 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004736 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004737 break;
4738 }
4739 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004741 case FK_NonConstLValueReferenceBindingToTemporary:
4742 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004744 Failure == FK_NonConstLValueReferenceBindingToTemporary
4745 ? diag::err_lvalue_reference_bind_to_temporary
4746 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004747 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004748 << DestType.getNonReferenceType()
4749 << Args[0]->getType()
4750 << Args[0]->getSourceRange();
4751 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004753 case FK_RValueReferenceBindingToLValue:
4754 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004755 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004756 << Args[0]->getSourceRange();
4757 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004759 case FK_ReferenceInitDropsQualifiers:
4760 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4761 << DestType.getNonReferenceType()
4762 << Args[0]->getType()
4763 << Args[0]->getSourceRange();
4764 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004766 case FK_ReferenceInitFailed:
4767 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4768 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004769 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004770 << Args[0]->getType()
4771 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004772 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4773 Args[0]->getType()->isObjCObjectPointerType())
4774 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004775 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776
Douglas Gregorb491ed32011-02-19 21:32:49 +00004777 case FK_ConversionFailed: {
4778 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004779 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4780 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004781 << DestType
John McCall086a4642010-11-24 05:12:34 +00004782 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004783 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004784 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004785 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4786 Args[0]->getType()->isObjCObjectPointerType())
4787 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004788 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004789 }
John Wiegley01296292011-04-08 18:41:53 +00004790
4791 case FK_ConversionFromPropertyFailed:
4792 // No-op. This error has already been reported.
4793 break;
4794
Douglas Gregor51e77d52009-12-10 17:56:55 +00004795 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004796 SourceRange R;
4797
4798 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004799 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004800 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004802 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004803
Douglas Gregor8ec51732010-09-08 21:40:08 +00004804 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4805 if (Kind.isCStyleOrFunctionalCast())
4806 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4807 << R;
4808 else
4809 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4810 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004811 break;
4812 }
4813
4814 case FK_ReferenceBindingToInitList:
4815 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4816 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4817 break;
4818
4819 case FK_InitListBadDestinationType:
4820 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4821 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4822 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004823
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004824 case FK_ConstructorOverloadFailed: {
4825 SourceRange ArgsRange;
4826 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004828 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004830 // FIXME: Using "DestType" for the entity we're printing is probably
4831 // bad.
4832 switch (FailedOverloadResult) {
4833 case OR_Ambiguous:
4834 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4835 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004836 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4837 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004838 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004840 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004841 if (Kind.getKind() == InitializationKind::IK_Default &&
4842 (Entity.getKind() == InitializedEntity::EK_Base ||
4843 Entity.getKind() == InitializedEntity::EK_Member) &&
4844 isa<CXXConstructorDecl>(S.CurContext)) {
4845 // This is implicit default initialization of a member or
4846 // base within a constructor. If no viable function was
4847 // found, notify the user that she needs to explicitly
4848 // initialize this base/member.
4849 CXXConstructorDecl *Constructor
4850 = cast<CXXConstructorDecl>(S.CurContext);
4851 if (Entity.getKind() == InitializedEntity::EK_Base) {
4852 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4853 << Constructor->isImplicit()
4854 << S.Context.getTypeDeclType(Constructor->getParent())
4855 << /*base=*/0
4856 << Entity.getType();
4857
4858 RecordDecl *BaseDecl
4859 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4860 ->getDecl();
4861 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4862 << S.Context.getTagDeclType(BaseDecl);
4863 } else {
4864 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4865 << Constructor->isImplicit()
4866 << S.Context.getTypeDeclType(Constructor->getParent())
4867 << /*member=*/1
4868 << Entity.getName();
4869 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4870
4871 if (const RecordType *Record
4872 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004874 diag::note_previous_decl)
4875 << S.Context.getTagDeclType(Record->getDecl());
4876 }
4877 break;
4878 }
4879
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004880 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4881 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004882 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004883 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004885 case OR_Deleted: {
4886 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4887 << true << DestType << ArgsRange;
4888 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004889 OverloadingResult Ovl
4890 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004891 if (Ovl == OR_Deleted) {
4892 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004893 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004894 } else {
4895 llvm_unreachable("Inconsistent overload resolution?");
4896 }
4897 break;
4898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004900 case OR_Success:
4901 llvm_unreachable("Conversion did not fail!");
4902 break;
4903 }
4904 break;
4905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004906
Douglas Gregor85dabae2009-12-16 01:38:02 +00004907 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004908 if (Entity.getKind() == InitializedEntity::EK_Member &&
4909 isa<CXXConstructorDecl>(S.CurContext)) {
4910 // This is implicit default-initialization of a const member in
4911 // a constructor. Complain that it needs to be explicitly
4912 // initialized.
4913 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4914 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4915 << Constructor->isImplicit()
4916 << S.Context.getTypeDeclType(Constructor->getParent())
4917 << /*const=*/1
4918 << Entity.getName();
4919 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4920 << Entity.getName();
4921 } else {
4922 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4923 << DestType << (bool)DestType->getAs<RecordType>();
4924 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004925 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004927 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004929 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004933 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004934 return true;
4935}
Douglas Gregore1314a62009-12-18 05:02:21 +00004936
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004937void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004938 switch (SequenceKind) {
4939 case FailedSequence: {
4940 OS << "Failed sequence: ";
4941 switch (Failure) {
4942 case FK_TooManyInitsForReference:
4943 OS << "too many initializers for reference";
4944 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004946 case FK_ArrayNeedsInitList:
4947 OS << "array requires initializer list";
4948 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004949
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004950 case FK_ArrayNeedsInitListOrStringLiteral:
4951 OS << "array requires initializer list or string literal";
4952 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregore2f943b2011-02-22 18:29:51 +00004954 case FK_ArrayTypeMismatch:
4955 OS << "array type mismatch";
4956 break;
4957
4958 case FK_NonConstantArrayInit:
4959 OS << "non-constant array initializer";
4960 break;
4961
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004962 case FK_AddressOfOverloadFailed:
4963 OS << "address of overloaded function failed";
4964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004966 case FK_ReferenceInitOverloadFailed:
4967 OS << "overload resolution for reference initialization failed";
4968 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004970 case FK_NonConstLValueReferenceBindingToTemporary:
4971 OS << "non-const lvalue reference bound to temporary";
4972 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004973
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004974 case FK_NonConstLValueReferenceBindingToUnrelated:
4975 OS << "non-const lvalue reference bound to unrelated type";
4976 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004978 case FK_RValueReferenceBindingToLValue:
4979 OS << "rvalue reference bound to an lvalue";
4980 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004981
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004982 case FK_ReferenceInitDropsQualifiers:
4983 OS << "reference initialization drops qualifiers";
4984 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004985
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004986 case FK_ReferenceInitFailed:
4987 OS << "reference initialization failed";
4988 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004990 case FK_ConversionFailed:
4991 OS << "conversion failed";
4992 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993
John Wiegley01296292011-04-08 18:41:53 +00004994 case FK_ConversionFromPropertyFailed:
4995 OS << "conversion from property failed";
4996 break;
4997
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004998 case FK_TooManyInitsForScalar:
4999 OS << "too many initializers for scalar";
5000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005002 case FK_ReferenceBindingToInitList:
5003 OS << "referencing binding to initializer list";
5004 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005006 case FK_InitListBadDestinationType:
5007 OS << "initializer list for non-aggregate, non-scalar type";
5008 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005010 case FK_UserConversionOverloadFailed:
5011 OS << "overloading failed for user-defined conversion";
5012 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005014 case FK_ConstructorOverloadFailed:
5015 OS << "constructor overloading failed";
5016 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005018 case FK_DefaultInitOfConst:
5019 OS << "default initialization of a const variable";
5020 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005021
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005022 case FK_Incomplete:
5023 OS << "initialization of incomplete type";
5024 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005026 OS << '\n';
5027 return;
5028 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005029
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005030 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005031 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005032 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033
Sebastian Redld201edf2011-06-05 13:59:11 +00005034 case NormalSequence:
5035 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005036 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005039 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5040 if (S != step_begin()) {
5041 OS << " -> ";
5042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005044 switch (S->Kind) {
5045 case SK_ResolveAddressOfOverloadedFunction:
5046 OS << "resolve address of overloaded function";
5047 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005049 case SK_CastDerivedToBaseRValue:
5050 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5051 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005053 case SK_CastDerivedToBaseXValue:
5054 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5055 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005057 case SK_CastDerivedToBaseLValue:
5058 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5059 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005061 case SK_BindReference:
5062 OS << "bind reference to lvalue";
5063 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005065 case SK_BindReferenceToTemporary:
5066 OS << "bind reference to a temporary";
5067 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005068
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005069 case SK_ExtraneousCopyToTemporary:
5070 OS << "extraneous C++03 copy to temporary";
5071 break;
5072
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005073 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005074 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005075 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005076
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005077 case SK_QualificationConversionRValue:
5078 OS << "qualification conversion (rvalue)";
5079
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005080 case SK_QualificationConversionXValue:
5081 OS << "qualification conversion (xvalue)";
5082
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005083 case SK_QualificationConversionLValue:
5084 OS << "qualification conversion (lvalue)";
5085 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005086
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005087 case SK_ConversionSequence:
5088 OS << "implicit conversion sequence (";
5089 S->ICS->DebugPrint(); // FIXME: use OS
5090 OS << ")";
5091 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005093 case SK_ListInitialization:
5094 OS << "list initialization";
5095 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005097 case SK_ConstructorInitialization:
5098 OS << "constructor initialization";
5099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005100
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005101 case SK_ZeroInitialization:
5102 OS << "zero initialization";
5103 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005104
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005105 case SK_CAssignment:
5106 OS << "C assignment";
5107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005108
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005109 case SK_StringInit:
5110 OS << "string initialization";
5111 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005112
5113 case SK_ObjCObjectConversion:
5114 OS << "Objective-C object conversion";
5115 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005116
5117 case SK_ArrayInit:
5118 OS << "array initialization";
5119 break;
John McCall31168b02011-06-15 23:02:42 +00005120
5121 case SK_PassByIndirectCopyRestore:
5122 OS << "pass by indirect copy and restore";
5123 break;
5124
5125 case SK_PassByIndirectRestore:
5126 OS << "pass by indirect restore";
5127 break;
5128
5129 case SK_ProduceObjCObject:
5130 OS << "Objective-C object retension";
5131 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005132 }
5133 }
5134}
5135
5136void InitializationSequence::dump() const {
5137 dump(llvm::errs());
5138}
5139
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005140static void DiagnoseNarrowingInInitList(
5141 Sema& S, QualType EntityType, const Expr *InitE,
5142 bool Constant, const APValue &ConstantValue) {
5143 if (Constant) {
5144 S.Diag(InitE->getLocStart(),
Francois Pichet4c726942011-08-18 00:04:08 +00005145 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005146 ? diag::err_init_list_constant_narrowing
5147 : diag::warn_init_list_constant_narrowing)
5148 << InitE->getSourceRange()
5149 << ConstantValue
5150 << EntityType;
5151 } else
5152 S.Diag(InitE->getLocStart(),
Francois Pichet4c726942011-08-18 00:04:08 +00005153 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005154 ? diag::err_init_list_variable_narrowing
5155 : diag::warn_init_list_variable_narrowing)
5156 << InitE->getSourceRange()
5157 << InitE->getType()
5158 << EntityType;
5159
5160 llvm::SmallString<128> StaticCast;
5161 llvm::raw_svector_ostream OS(StaticCast);
5162 OS << "static_cast<";
5163 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5164 // It's important to use the typedef's name if there is one so that the
5165 // fixit doesn't break code using types like int64_t.
5166 //
5167 // FIXME: This will break if the typedef requires qualification. But
5168 // getQualifiedNameAsString() includes non-machine-parsable components.
5169 OS << TT->getDecl();
5170 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5171 OS << BT->getName(S.getLangOptions());
5172 else {
5173 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5174 // with a broken cast.
5175 return;
5176 }
5177 OS << ">(";
5178 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5179 << InitE->getSourceRange()
5180 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5181 << FixItHint::CreateInsertion(
5182 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5183}
5184
Douglas Gregore1314a62009-12-18 05:02:21 +00005185//===----------------------------------------------------------------------===//
5186// Initialization helper functions
5187//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005188bool
5189Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5190 ExprResult Init) {
5191 if (Init.isInvalid())
5192 return false;
5193
5194 Expr *InitE = Init.get();
5195 assert(InitE && "No initialization expression");
5196
5197 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5198 SourceLocation());
5199 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005200 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005201}
5202
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005204Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5205 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005206 ExprResult Init,
5207 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005208 if (Init.isInvalid())
5209 return ExprError();
5210
John McCall1f425642010-11-11 03:21:53 +00005211 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005212 assert(InitE && "No initialization expression?");
5213
5214 if (EqualLoc.isInvalid())
5215 EqualLoc = InitE->getLocStart();
5216
5217 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5218 EqualLoc);
5219 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5220 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005221
5222 bool Constant = false;
5223 APValue Result;
5224 if (TopLevelOfInitList &&
5225 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5226 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5227 Constant, Result);
5228 }
John McCallfaf5fb42010-08-26 23:41:50 +00005229 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005230}