blob: e8a35ad12ba61d61ba02f8a3c3bf5ba6f2b004c5 [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//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000026#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000027using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000028
Chris Lattner0cb78032009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCall66884dd2011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattnera9196812009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000040
Chris Lattnera9196812009-02-26 23:26:43 +000041 // Handle @encode, which is a narrow string.
42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
43 return Init;
44
45 // Otherwise we can only handle string literals.
46 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000050
51 switch (SL->getKind()) {
52 case StringLiteral::Ascii:
53 case StringLiteral::UTF8:
54 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000057 case StringLiteral::UTF16:
58 return ElemTy->isChar16Type() ? Init : 0;
59 case StringLiteral::UTF32:
60 return ElemTy->isChar32Type() ? Init : 0;
61 case StringLiteral::Wide:
62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63 // correction from DR343): "An array with element type compatible with a
64 // qualified or unqualified version of wchar_t may be initialized by a wide
65 // string literal, optionally enclosed in braces."
66 if (Context.typesAreCompatible(Context.getWCharType(),
67 ElemTy.getUnqualifiedType()))
68 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000069
Douglas Gregorfb65e592011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump11289f42009-09-09 15:08:12 +000072
Douglas Gregorfb65e592011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000074}
75
John McCall66884dd2011-02-21 07:22:22 +000076static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77 const ArrayType *arrayType = Context.getAsArrayType(declType);
78 if (!arrayType) return 0;
79
80 return IsStringInit(init, arrayType, Context);
81}
82
John McCall5decec92011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000085 // Get the length of the string as parsed.
86 uint64_t StrLength =
87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
88
Mike Stump11289f42009-09-09 15:08:12 +000089
Chris Lattner0cb78032009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000099 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000100 }
Mike Stump11289f42009-09-09 15:08:12 +0000101
Eli Friedman893abe42009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman554eba92011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000105 // the size may be smaller or larger than the string we are initializing.
106 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109 // For Pascal strings it's OK to strip off the terminating null character,
110 // so the example below is valid:
111 //
112 // unsigned char a[2] = "\pa";
113 if (SL->isPascal())
114 StrLength--;
115 }
116
Eli Friedman554eba92011-04-11 00:23:45 +0000117 // [dcl.init.string]p2
118 if (StrLength > CAT->getSize().getZExtValue())
119 S.Diag(Str->getSourceRange().getBegin(),
120 diag::err_initializer_string_for_char_array_too_long)
121 << Str->getSourceRange();
122 } else {
123 // C99 6.7.8p14.
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
128 }
Mike Stump11289f42009-09-09 15:08:12 +0000129
Eli Friedman893abe42009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000135}
136
Chris Lattner0cb78032009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregorcde232f2009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000168namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171 bool hadError;
172 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
173 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000174
Anders Carlsson6cabf312010-01-23 23:23:01 +0000175 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000176 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000177 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000178 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000179 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000180 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000182 unsigned &StructuredIndex,
183 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000184 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000185 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000186 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000187 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000188 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000189 unsigned &StructuredIndex,
190 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000191 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000192 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000193 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000194 InitListExpr *StructuredList,
195 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000196 void CheckComplexType(const InitializedEntity &Entity,
197 InitListExpr *IList, QualType DeclType,
198 unsigned &Index,
199 InitListExpr *StructuredList,
200 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000201 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000202 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000206 void CheckReferenceType(const InitializedEntity &Entity,
207 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000208 unsigned &Index,
209 InitListExpr *StructuredList,
210 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000211 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000212 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000215 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000216 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000217 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000218 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000219 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000220 unsigned &StructuredIndex,
221 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000222 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000223 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000224 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000225 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000226 InitListExpr *StructuredList,
227 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000228 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000229 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000230 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000231 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000232 RecordDecl::field_iterator *NextField,
233 llvm::APSInt *NextElementIndex,
234 unsigned &Index,
235 InitListExpr *StructuredList,
236 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000237 bool FinishSubobjectInit,
238 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000239 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
240 QualType CurrentObjectType,
241 InitListExpr *StructuredList,
242 unsigned StructuredIndex,
243 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 void UpdateStructuredListElement(InitListExpr *StructuredList,
245 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000246 Expr *expr);
247 int numArrayElements(QualType DeclType);
248 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000249
Douglas Gregor2bb07652009-12-22 00:05:34 +0000250 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
251 const InitializedEntity &ParentEntity,
252 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000253 void FillInValueInitializations(const InitializedEntity &Entity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000255 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
256 Expr *InitExpr, FieldDecl *Field,
257 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000258public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000259 InitListChecker(Sema &S, const InitializedEntity &Entity,
260 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000261 bool HadError() { return hadError; }
262
263 // @brief Retrieves the fully-structured initializer list used for
264 // semantic analysis and code generation.
265 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
266};
Chris Lattner9ececce2009-02-24 22:48:58 +0000267} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000268
Douglas Gregor2bb07652009-12-22 00:05:34 +0000269void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
270 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000271 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000272 bool &RequiresSecondPass) {
273 SourceLocation Loc = ILE->getSourceRange().getBegin();
274 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000276 = InitializedEntity::InitializeMember(Field, &ParentEntity);
277 if (Init >= NumInits || !ILE->getInit(Init)) {
278 // FIXME: We probably don't need to handle references
279 // specially here, since value-initialization of references is
280 // handled in InitializationSequence.
281 if (Field->getType()->isReferenceType()) {
282 // C++ [dcl.init.aggr]p9:
283 // If an incomplete or empty initializer-list leaves a
284 // member of reference type uninitialized, the program is
285 // ill-formed.
286 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
287 << Field->getType()
288 << ILE->getSyntacticForm()->getSourceRange();
289 SemaRef.Diag(Field->getLocation(),
290 diag::note_uninit_reference_member);
291 hadError = true;
292 return;
293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
Douglas Gregor2bb07652009-12-22 00:05:34 +0000295 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
296 true);
297 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
298 if (!InitSeq) {
299 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
300 hadError = true;
301 return;
302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000303
John McCalldadc5752010-08-24 06:29:42 +0000304 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000305 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000306 if (MemberInit.isInvalid()) {
307 hadError = true;
308 return;
309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Douglas Gregor2bb07652009-12-22 00:05:34 +0000311 if (hadError) {
312 // Do nothing
313 } else if (Init < NumInits) {
314 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000315 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000316 // Value-initialization requires a constructor call, so
317 // extend the initializer list to include the constructor
318 // call and make a note that we'll need to take another pass
319 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000320 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000321 RequiresSecondPass = true;
322 }
323 } else if (InitListExpr *InnerILE
324 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000325 FillInValueInitializations(MemberEntity, InnerILE,
326 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000327}
328
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000329/// Recursively replaces NULL values within the given initializer list
330/// with expressions that perform value-initialization of the
331/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000332void
Douglas Gregor723796a2009-12-16 06:35:08 +0000333InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
334 InitListExpr *ILE,
335 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000336 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000337 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000338 SourceLocation Loc = ILE->getSourceRange().getBegin();
339 if (ILE->getSyntacticForm())
340 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000341
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000342 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343 if (RType->getDecl()->isUnion() &&
344 ILE->getInitializedFieldInUnion())
345 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
346 Entity, ILE, RequiresSecondPass);
347 else {
348 unsigned Init = 0;
349 for (RecordDecl::field_iterator
350 Field = RType->getDecl()->field_begin(),
351 FieldEnd = RType->getDecl()->field_end();
352 Field != FieldEnd; ++Field) {
353 if (Field->isUnnamedBitfield())
354 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000355
Douglas Gregor2bb07652009-12-22 00:05:34 +0000356 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000357 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000358
359 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
360 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000361 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000362
Douglas Gregor2bb07652009-12-22 00:05:34 +0000363 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000364
Douglas Gregor2bb07652009-12-22 00:05:34 +0000365 // Only look at the first initialization of a union.
366 if (RType->getDecl()->isUnion())
367 break;
368 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000369 }
370
371 return;
Mike Stump11289f42009-09-09 15:08:12 +0000372 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000373
374 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000375
Douglas Gregor723796a2009-12-16 06:35:08 +0000376 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000377 unsigned NumInits = ILE->getNumInits();
378 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000379 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000380 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
382 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000383 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000384 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000385 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000386 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000387 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000389 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000390 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000391 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000392
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000394 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000395 if (hadError)
396 return;
397
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000398 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
399 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000400 ElementEntity.setElementIndex(Init);
401
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000402 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
404 true);
405 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
406 if (!InitSeq) {
407 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000408 hadError = true;
409 return;
410 }
411
John McCalldadc5752010-08-24 06:29:42 +0000412 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000413 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000414 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000415 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000416 return;
417 }
418
419 if (hadError) {
420 // Do nothing
421 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000422 // For arrays, just set the expression used for value-initialization
423 // of the "holes" in the array.
424 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
425 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
426 else
427 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000428 } else {
429 // For arrays, just set the expression used for value-initialization
430 // of the rest of elements and exit.
431 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
432 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
433 return;
434 }
435
Sebastian Redld201edf2011-06-05 13:59:11 +0000436 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000437 // Value-initialization requires a constructor call, so
438 // extend the initializer list to include the constructor
439 // call and make a note that we'll need to take another pass
440 // through the initializer list.
441 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
442 RequiresSecondPass = true;
443 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000444 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000445 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000446 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
447 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000448 }
449}
450
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000451
Douglas Gregor723796a2009-12-16 06:35:08 +0000452InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
453 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000454 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000455 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000456
Eli Friedman23a9e312008-05-19 19:16:24 +0000457 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000458 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000459 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000460 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000462 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000463 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000464
Douglas Gregor723796a2009-12-16 06:35:08 +0000465 if (!hadError) {
466 bool RequiresSecondPass = false;
467 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000468 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000469 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000470 RequiresSecondPass);
471 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000472}
473
474int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000475 // FIXME: use a proper constant
476 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000477 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000478 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000479 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
480 }
481 return maxElements;
482}
483
484int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000485 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000486 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000487 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000488 Field = structDecl->field_begin(),
489 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000490 Field != FieldEnd; ++Field) {
491 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
492 ++InitializableMembers;
493 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000494 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000495 return std::min(InitializableMembers, 1);
496 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000497}
498
Anders Carlsson6cabf312010-01-23 23:23:01 +0000499void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000500 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000501 QualType T, unsigned &Index,
502 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000503 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000504 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Steve Narofff8ecff22008-05-01 22:18:59 +0000506 if (T->isArrayType())
507 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000508 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000509 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000510 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000511 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000512 else
David Blaikie83d382b2011-09-23 05:06:16 +0000513 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000514
Eli Friedmane0f832b2008-05-25 13:49:22 +0000515 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000516 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000517 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000518 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000519 hadError = true;
520 return;
521 }
522
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000523 // Build a structured initializer list corresponding to this subobject.
524 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000525 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
526 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000527 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
528 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000529 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000530
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000531 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000532 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000534 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000535 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000536 StructuredSubobjectInitIndex);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000537 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000538 StructuredSubobjectInitList->setType(T);
539
Douglas Gregor5741efb2009-03-01 17:12:46 +0000540 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000541 // range corresponds with the end of the last initializer it used.
542 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000543 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000544 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
545 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
Tanya Lattner5029d562010-03-07 04:17:15 +0000548 // Warn about missing braces.
549 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000550 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
551 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000552 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000553 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000554 "{")
555 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000557 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000558 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000559}
560
Anders Carlsson6cabf312010-01-23 23:23:01 +0000561void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000562 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000563 unsigned &Index,
564 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000565 unsigned &StructuredIndex,
566 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000567 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000568 SyntacticToSemantic[IList] = StructuredList;
569 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000571 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000572 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
573 IList->setType(ExprTy);
574 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000575 if (hadError)
576 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000577
Eli Friedman85f54972008-05-25 13:22:35 +0000578 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000579 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000580 if (StructuredIndex == 1 &&
581 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000582 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000583 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000584 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000585 hadError = true;
586 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000587 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000588 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000589 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000590 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000591 // Don't complain for incomplete types, since we'll get an error
592 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000593 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000594 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 CurrentObjectType->isArrayType()? 0 :
596 CurrentObjectType->isVectorType()? 1 :
597 CurrentObjectType->isScalarType()? 2 :
598 CurrentObjectType->isUnionType()? 3 :
599 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000600
601 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000602 if (SemaRef.getLangOptions().CPlusPlus) {
603 DK = diag::err_excess_initializers;
604 hadError = true;
605 }
Nate Begeman425038c2009-07-07 21:53:06 +0000606 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
607 DK = diag::err_excess_initializers;
608 hadError = true;
609 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000610
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000612 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613 }
614 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000615
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000616 if (T->isScalarType() && IList->getNumInits() == 1 && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000617 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000618 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000619 << FixItHint::CreateRemoval(IList->getLocStart())
620 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000621}
622
Anders Carlsson6cabf312010-01-23 23:23:01 +0000623void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000624 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000625 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000626 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000627 unsigned &Index,
628 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000629 unsigned &StructuredIndex,
630 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000631 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
632 // Explicitly braced initializer for complex type can be real+imaginary
633 // parts.
634 CheckComplexType(Entity, IList, DeclType, Index,
635 StructuredList, StructuredIndex);
636 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000637 CheckScalarType(Entity, IList, DeclType, Index,
638 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000639 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000640 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000641 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000642 } else if (DeclType->isAggregateType()) {
643 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000644 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000645 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000646 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000647 StructuredList, StructuredIndex,
648 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000649 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000650 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000651 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000652 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000654 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000656 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000657 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000658 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
659 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000660 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000661 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000662 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000663 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000664 } else if (DeclType->isRecordType()) {
665 // C++ [dcl.init]p14:
666 // [...] If the class is an aggregate (8.5.1), and the initializer
667 // is a brace-enclosed list, see 8.5.1.
668 //
669 // Note: 8.5.1 is handled below; here, we diagnose the case where
670 // we have an initializer list and a destination type that is not
671 // an aggregate.
672 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000673 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000674 << DeclType << IList->getSourceRange();
675 hadError = true;
676 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000677 CheckReferenceType(Entity, IList, DeclType, Index,
678 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000679 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000680 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
681 << DeclType;
682 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000683 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000684 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
685 << DeclType;
686 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000687 }
688}
689
Anders Carlsson6cabf312010-01-23 23:23:01 +0000690void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000691 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000692 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000693 unsigned &Index,
694 InitListExpr *StructuredList,
695 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000696 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000697 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
698 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000699 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000700 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 = getStructuredSubobjectInit(IList, Index, ElemType,
702 StructuredList, StructuredIndex,
703 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000704 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000705 newStructuredList, newStructuredIndex);
706 ++StructuredIndex;
707 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000708 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000709 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000710 return CheckScalarType(Entity, IList, ElemType, Index,
711 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000712 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000713 return CheckReferenceType(Entity, IList, ElemType, Index,
714 StructuredList, StructuredIndex);
715 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000716
John McCall5decec92011-02-21 07:57:55 +0000717 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
718 // arrayType can be incomplete if we're initializing a flexible
719 // array member. There's nothing we can do with the completed
720 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
John McCall5decec92011-02-21 07:57:55 +0000722 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
723 CheckStringInit(Str, ElemType, arrayType, SemaRef);
724 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000725 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000726 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000727 }
John McCall5decec92011-02-21 07:57:55 +0000728
729 // Fall through for subaggregate initialization.
730
731 } else if (SemaRef.getLangOptions().CPlusPlus) {
732 // C++ [dcl.init.aggr]p12:
733 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000734 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000735 // an initializer-list. If the initializer can initialize a
736 // member, the member is initialized. [...]
737
738 // FIXME: Better EqualLoc?
739 InitializationKind Kind =
740 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
741 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
742
743 if (Seq) {
744 ExprResult Result =
745 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
746 if (Result.isInvalid())
747 hadError = true;
748
749 UpdateStructuredListElement(StructuredList, StructuredIndex,
750 Result.takeAs<Expr>());
751 ++Index;
752 return;
753 }
754
755 // Fall through for subaggregate initialization
756 } else {
757 // C99 6.7.8p13:
758 //
759 // The initializer for a structure or union object that has
760 // automatic storage duration shall be either an initializer
761 // list as described below, or a single expression that has
762 // compatible structure or union type. In the latter case, the
763 // initial value of the object, including unnamed members, is
764 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000765 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000766 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000767 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000768 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000769 if (ExprRes.isInvalid())
770 hadError = true;
771 else {
772 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
773 if (ExprRes.isInvalid())
774 hadError = true;
775 }
776 UpdateStructuredListElement(StructuredList, StructuredIndex,
777 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000778 ++Index;
779 return;
780 }
John Wiegley01296292011-04-08 18:41:53 +0000781 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000782 // Fall through for subaggregate initialization
783 }
784
785 // C++ [dcl.init.aggr]p12:
786 //
787 // [...] Otherwise, if the member is itself a non-empty
788 // subaggregate, brace elision is assumed and the initializer is
789 // considered for the initialization of the first member of
790 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000791 if (!SemaRef.getLangOptions().OpenCL &&
792 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000793 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
794 StructuredIndex);
795 ++StructuredIndex;
796 } else {
797 // We cannot initialize this element, so let
798 // PerformCopyInitialization produce the appropriate diagnostic.
799 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000800 SemaRef.Owned(expr),
801 /*TopLevelOfInitList=*/true);
John McCall5decec92011-02-21 07:57:55 +0000802 hadError = true;
803 ++Index;
804 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000805 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000806}
807
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000808void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
809 InitListExpr *IList, QualType DeclType,
810 unsigned &Index,
811 InitListExpr *StructuredList,
812 unsigned &StructuredIndex) {
813 assert(Index == 0 && "Index in explicit init list must be zero");
814
815 // As an extension, clang supports complex initializers, which initialize
816 // a complex number component-wise. When an explicit initializer list for
817 // a complex number contains two two initializers, this extension kicks in:
818 // it exepcts the initializer list to contain two elements convertible to
819 // the element type of the complex type. The first element initializes
820 // the real part, and the second element intitializes the imaginary part.
821
822 if (IList->getNumInits() != 2)
823 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
824 StructuredIndex);
825
826 // This is an extension in C. (The builtin _Complex type does not exist
827 // in the C++ standard.)
828 if (!SemaRef.getLangOptions().CPlusPlus)
829 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
830 << IList->getSourceRange();
831
832 // Initialize the complex number.
833 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
834 InitializedEntity ElementEntity =
835 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
836
837 for (unsigned i = 0; i < 2; ++i) {
838 ElementEntity.setElementIndex(Index);
839 CheckSubElementType(ElementEntity, IList, elementType, Index,
840 StructuredList, StructuredIndex);
841 }
842}
843
844
Anders Carlsson6cabf312010-01-23 23:23:01 +0000845void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000846 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000847 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000848 InitListExpr *StructuredList,
849 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000850 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000851 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000852 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000853 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000854 ++Index;
855 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000856 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000857 }
John McCall643169b2010-11-11 00:46:36 +0000858
859 Expr *expr = IList->getInit(Index);
860 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
861 SemaRef.Diag(SubIList->getLocStart(),
862 diag::warn_many_braces_around_scalar_init)
863 << SubIList->getSourceRange();
864
865 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
866 StructuredIndex);
867 return;
868 } else if (isa<DesignatedInitExpr>(expr)) {
869 SemaRef.Diag(expr->getSourceRange().getBegin(),
870 diag::err_designator_for_scalar_init)
871 << DeclType << expr->getSourceRange();
872 hadError = true;
873 ++Index;
874 ++StructuredIndex;
875 return;
876 }
877
878 ExprResult Result =
879 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000880 SemaRef.Owned(expr),
881 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000882
883 Expr *ResultExpr = 0;
884
885 if (Result.isInvalid())
886 hadError = true; // types weren't compatible.
887 else {
888 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
John McCall643169b2010-11-11 00:46:36 +0000890 if (ResultExpr != expr) {
891 // The type was promoted, update initializer list.
892 IList->setInit(Index, ResultExpr);
893 }
894 }
895 if (hadError)
896 ++StructuredIndex;
897 else
898 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
899 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000900}
901
Anders Carlsson6cabf312010-01-23 23:23:01 +0000902void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
903 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000904 unsigned &Index,
905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
907 if (Index < IList->getNumInits()) {
908 Expr *expr = IList->getInit(Index);
909 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000910 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000911 << DeclType << IList->getSourceRange();
912 hadError = true;
913 ++Index;
914 ++StructuredIndex;
915 return;
Mike Stump11289f42009-09-09 15:08:12 +0000916 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000917
John McCalldadc5752010-08-24 06:29:42 +0000918 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000919 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000920 SemaRef.Owned(expr),
921 /*TopLevelOfInitList=*/true);
Anders Carlssona91be642010-01-29 02:47:33 +0000922
923 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000924 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000925
926 expr = Result.takeAs<Expr>();
927 IList->setInit(Index, expr);
928
Douglas Gregord14247a2009-01-30 22:09:00 +0000929 if (hadError)
930 ++StructuredIndex;
931 else
932 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
933 ++Index;
934 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000935 // FIXME: It would be wonderful if we could point at the actual member. In
936 // general, it would be useful to pass location information down the stack,
937 // so that we know the location (or decl) of the "current object" being
938 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000939 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000940 diag::err_init_reference_member_uninitialized)
941 << DeclType
942 << IList->getSourceRange();
943 hadError = true;
944 ++Index;
945 ++StructuredIndex;
946 return;
947 }
948}
949
Anders Carlsson6cabf312010-01-23 23:23:01 +0000950void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000951 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000952 unsigned &Index,
953 InitListExpr *StructuredList,
954 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000955 if (Index >= IList->getNumInits())
956 return;
Mike Stump11289f42009-09-09 15:08:12 +0000957
John McCall6a16b2f2010-10-30 00:11:39 +0000958 const VectorType *VT = DeclType->getAs<VectorType>();
959 unsigned maxElements = VT->getNumElements();
960 unsigned numEltsInit = 0;
961 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000962
John McCall6a16b2f2010-10-30 00:11:39 +0000963 if (!SemaRef.getLangOptions().OpenCL) {
964 // If the initializing element is a vector, try to copy-initialize
965 // instead of breaking it apart (which is doomed to failure anyway).
966 Expr *Init = IList->getInit(Index);
967 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
968 ExprResult Result =
969 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000970 SemaRef.Owned(Init),
971 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +0000972
973 Expr *ResultExpr = 0;
974 if (Result.isInvalid())
975 hadError = true; // types weren't compatible.
976 else {
977 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000978
John McCall6a16b2f2010-10-30 00:11:39 +0000979 if (ResultExpr != Init) {
980 // The type was promoted, update initializer list.
981 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000982 }
983 }
John McCall6a16b2f2010-10-30 00:11:39 +0000984 if (hadError)
985 ++StructuredIndex;
986 else
987 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
988 ++Index;
989 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000990 }
Mike Stump11289f42009-09-09 15:08:12 +0000991
John McCall6a16b2f2010-10-30 00:11:39 +0000992 InitializedEntity ElementEntity =
993 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000994
John McCall6a16b2f2010-10-30 00:11:39 +0000995 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
996 // Don't attempt to go past the end of the init list
997 if (Index >= IList->getNumInits())
998 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
John McCall6a16b2f2010-10-30 00:11:39 +00001000 ElementEntity.setElementIndex(Index);
1001 CheckSubElementType(ElementEntity, IList, elementType, Index,
1002 StructuredList, StructuredIndex);
1003 }
1004 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001005 }
John McCall6a16b2f2010-10-30 00:11:39 +00001006
1007 InitializedEntity ElementEntity =
1008 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
John McCall6a16b2f2010-10-30 00:11:39 +00001010 // OpenCL initializers allows vectors to be constructed from vectors.
1011 for (unsigned i = 0; i < maxElements; ++i) {
1012 // Don't attempt to go past the end of the init list
1013 if (Index >= IList->getNumInits())
1014 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015
John McCall6a16b2f2010-10-30 00:11:39 +00001016 ElementEntity.setElementIndex(Index);
1017
1018 QualType IType = IList->getInit(Index)->getType();
1019 if (!IType->isVectorType()) {
1020 CheckSubElementType(ElementEntity, IList, elementType, Index,
1021 StructuredList, StructuredIndex);
1022 ++numEltsInit;
1023 } else {
1024 QualType VecType;
1025 const VectorType *IVT = IType->getAs<VectorType>();
1026 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
John McCall6a16b2f2010-10-30 00:11:39 +00001028 if (IType->isExtVectorType())
1029 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1030 else
1031 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001032 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001033 CheckSubElementType(ElementEntity, IList, VecType, Index,
1034 StructuredList, StructuredIndex);
1035 numEltsInit += numIElts;
1036 }
1037 }
1038
1039 // OpenCL requires all elements to be initialized.
1040 if (numEltsInit != maxElements)
1041 if (SemaRef.getLangOptions().OpenCL)
1042 SemaRef.Diag(IList->getSourceRange().getBegin(),
1043 diag::err_vector_incorrect_num_initializers)
1044 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +00001045}
1046
Anders Carlsson6cabf312010-01-23 23:23:01 +00001047void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001048 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001049 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001050 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001051 unsigned &Index,
1052 InitListExpr *StructuredList,
1053 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001054 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1055
Steve Narofff8ecff22008-05-01 22:18:59 +00001056 // Check for the special-case of initializing an array with a string.
1057 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001058 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001059 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +00001060 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001061 // We place the string literal directly into the resulting
1062 // initializer list. This is the only place where the structure
1063 // of the structured initializer list doesn't match exactly,
1064 // because doing so would involve allocating one character
1065 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001066 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001067 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001068 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001069 return;
1070 }
1071 }
John McCall66884dd2011-02-21 07:22:22 +00001072 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001073 // Check for VLAs; in standard C it would be possible to check this
1074 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1075 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001076 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001077 diag::err_variable_object_no_init)
1078 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001079 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001080 ++Index;
1081 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001082 return;
1083 }
1084
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001085 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001086 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1087 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001088 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001089 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001090 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001091 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001092 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001093 maxElementsKnown = true;
1094 }
1095
John McCall66884dd2011-02-21 07:22:22 +00001096 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001097 while (Index < IList->getNumInits()) {
1098 Expr *Init = IList->getInit(Index);
1099 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001100 // If we're not the subobject that matches up with the '{' for
1101 // the designator, we shouldn't be handling the
1102 // designator. Return immediately.
1103 if (!SubobjectIsDesignatorContext)
1104 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001105
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001106 // Handle this designated initializer. elementIndex will be
1107 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001108 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001109 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001110 StructuredList, StructuredIndex, true,
1111 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001112 hadError = true;
1113 continue;
1114 }
1115
Douglas Gregor033d1252009-01-23 16:54:12 +00001116 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001117 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001118 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001119 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001120 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001121
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001122 // If the array is of incomplete type, keep track of the number of
1123 // elements in the initializer.
1124 if (!maxElementsKnown && elementIndex > maxElements)
1125 maxElements = elementIndex;
1126
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001127 continue;
1128 }
1129
1130 // If we know the maximum number of elements, and we've already
1131 // hit it, stop consuming elements in the initializer list.
1132 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001133 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001134
Anders Carlsson6cabf312010-01-23 23:23:01 +00001135 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001136 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001137 Entity);
1138 // Check this element.
1139 CheckSubElementType(ElementEntity, IList, elementType, Index,
1140 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001141 ++elementIndex;
1142
1143 // If the array is of incomplete type, keep track of the number of
1144 // elements in the initializer.
1145 if (!maxElementsKnown && elementIndex > maxElements)
1146 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001147 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001148 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001149 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001150 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001151 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001152 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001153 // Sizing an array implicitly to zero is not allowed by ISO C,
1154 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001155 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001156 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001157 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001158
Mike Stump11289f42009-09-09 15:08:12 +00001159 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001160 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001161 }
1162}
1163
Eli Friedman3fa64df2011-08-23 22:24:57 +00001164bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1165 Expr *InitExpr,
1166 FieldDecl *Field,
1167 bool TopLevelObject) {
1168 // Handle GNU flexible array initializers.
1169 unsigned FlexArrayDiag;
1170 if (isa<InitListExpr>(InitExpr) &&
1171 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1172 // Empty flexible array init always allowed as an extension
1173 FlexArrayDiag = diag::ext_flexible_array_init;
1174 } else if (SemaRef.getLangOptions().CPlusPlus) {
1175 // Disallow flexible array init in C++; it is not required for gcc
1176 // compatibility, and it needs work to IRGen correctly in general.
1177 FlexArrayDiag = diag::err_flexible_array_init;
1178 } else if (!TopLevelObject) {
1179 // Disallow flexible array init on non-top-level object
1180 FlexArrayDiag = diag::err_flexible_array_init;
1181 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1182 // Disallow flexible array init on anything which is not a variable.
1183 FlexArrayDiag = diag::err_flexible_array_init;
1184 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1185 // Disallow flexible array init on local variables.
1186 FlexArrayDiag = diag::err_flexible_array_init;
1187 } else {
1188 // Allow other cases.
1189 FlexArrayDiag = diag::ext_flexible_array_init;
1190 }
1191
1192 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1193 FlexArrayDiag)
1194 << InitExpr->getSourceRange().getBegin();
1195 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1196 << Field;
1197
1198 return FlexArrayDiag != diag::ext_flexible_array_init;
1199}
1200
Anders Carlsson6cabf312010-01-23 23:23:01 +00001201void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001202 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001203 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001204 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001205 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001206 unsigned &Index,
1207 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001208 unsigned &StructuredIndex,
1209 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001210 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001211
Eli Friedman23a9e312008-05-19 19:16:24 +00001212 // If the record is invalid, some of it's members are invalid. To avoid
1213 // confusion, we forgo checking the intializer for the entire record.
1214 if (structDecl->isInvalidDecl()) {
1215 hadError = true;
1216 return;
Mike Stump11289f42009-09-09 15:08:12 +00001217 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001218
1219 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1220 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001221 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001222 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001223 Field != FieldEnd; ++Field) {
1224 if (Field->getDeclName()) {
1225 StructuredList->setInitializedFieldInUnion(*Field);
1226 break;
1227 }
1228 }
1229 return;
1230 }
1231
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001232 // If structDecl is a forward declaration, this loop won't do
1233 // anything except look at designated initializers; That's okay,
1234 // because an error should get printed out elsewhere. It might be
1235 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001236 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001237 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001238 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001239 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001240 while (Index < IList->getNumInits()) {
1241 Expr *Init = IList->getInit(Index);
1242
1243 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001244 // If we're not the subobject that matches up with the '{' for
1245 // the designator, we shouldn't be handling the
1246 // designator. Return immediately.
1247 if (!SubobjectIsDesignatorContext)
1248 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001249
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001250 // Handle this designated initializer. Field will be updated to
1251 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001252 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001253 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001254 StructuredList, StructuredIndex,
1255 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001256 hadError = true;
1257
Douglas Gregora9add4e2009-02-12 19:00:39 +00001258 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001259
1260 // Disable check for missing fields when designators are used.
1261 // This matches gcc behaviour.
1262 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001263 continue;
1264 }
1265
1266 if (Field == FieldEnd) {
1267 // We've run out of fields. We're done.
1268 break;
1269 }
1270
Douglas Gregora9add4e2009-02-12 19:00:39 +00001271 // We've already initialized a member of a union. We're done.
1272 if (InitializedSomething && DeclType->isUnionType())
1273 break;
1274
Douglas Gregor91f84212008-12-11 16:49:14 +00001275 // If we've hit the flexible array member at the end, we're done.
1276 if (Field->getType()->isIncompleteArrayType())
1277 break;
1278
Douglas Gregor51695702009-01-29 16:53:55 +00001279 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001280 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001281 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001282 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001283 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001284
Douglas Gregora82064c2011-06-29 21:51:31 +00001285 // Make sure we can use this declaration.
1286 if (SemaRef.DiagnoseUseOfDecl(*Field,
1287 IList->getInit(Index)->getLocStart())) {
1288 ++Index;
1289 ++Field;
1290 hadError = true;
1291 continue;
1292 }
1293
Anders Carlsson6cabf312010-01-23 23:23:01 +00001294 InitializedEntity MemberEntity =
1295 InitializedEntity::InitializeMember(*Field, &Entity);
1296 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1297 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001298 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001299
1300 if (DeclType->isUnionType()) {
1301 // Initialize the first field within the union.
1302 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001303 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001304
1305 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001306 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001307
John McCalle40b58e2010-03-11 19:32:38 +00001308 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001309 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001310 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1311 // It is possible we have one or more unnamed bitfields remaining.
1312 // Find first (if any) named field and emit warning.
1313 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1314 it != end; ++it) {
1315 if (!it->isUnnamedBitfield()) {
1316 SemaRef.Diag(IList->getSourceRange().getEnd(),
1317 diag::warn_missing_field_initializers) << it->getName();
1318 break;
1319 }
1320 }
1321 }
1322
Mike Stump11289f42009-09-09 15:08:12 +00001323 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001324 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001325 return;
1326
Eli Friedman3fa64df2011-08-23 22:24:57 +00001327 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1328 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001329 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001330 ++Index;
1331 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001332 }
1333
Anders Carlsson6cabf312010-01-23 23:23:01 +00001334 InitializedEntity MemberEntity =
1335 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
Anders Carlsson6cabf312010-01-23 23:23:01 +00001337 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001339 StructuredList, StructuredIndex);
1340 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001342 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001343}
Steve Narofff8ecff22008-05-01 22:18:59 +00001344
Douglas Gregord5846a12009-04-15 06:41:24 +00001345/// \brief Expand a field designator that refers to a member of an
1346/// anonymous struct or union into a series of field designators that
1347/// refers to the field within the appropriate subobject.
1348///
Douglas Gregord5846a12009-04-15 06:41:24 +00001349static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001350 DesignatedInitExpr *DIE,
1351 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001352 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001353 typedef DesignatedInitExpr::Designator Designator;
1354
Douglas Gregord5846a12009-04-15 06:41:24 +00001355 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001356 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001357 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1358 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1359 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001360 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001361 DIE->getDesignator(DesigIdx)->getDotLoc(),
1362 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1363 else
1364 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1365 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001366 assert(isa<FieldDecl>(*PI));
1367 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001368 }
1369
1370 // Expand the current designator into the set of replacement
1371 // designators, so we have a full subobject path down to where the
1372 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001373 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001374 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001375}
Mike Stump11289f42009-09-09 15:08:12 +00001376
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001378/// corresponds to FieldName.
1379static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1380 IdentifierInfo *FieldName) {
1381 assert(AnonField->isAnonymousStructOrUnion());
1382 Decl *NextDecl = AnonField->getNextDeclInContext();
1383 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1384 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1385 return IF;
1386 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001387 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001388 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001389}
1390
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001391/// @brief Check the well-formedness of a C99 designated initializer.
1392///
1393/// Determines whether the designated initializer @p DIE, which
1394/// resides at the given @p Index within the initializer list @p
1395/// IList, is well-formed for a current object of type @p DeclType
1396/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001397/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001398/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001399///
1400/// @param IList The initializer list in which this designated
1401/// initializer occurs.
1402///
Douglas Gregora5324162009-04-15 04:56:10 +00001403/// @param DIE The designated initializer expression.
1404///
1405/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001406///
1407/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1408/// into which the designation in @p DIE should refer.
1409///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001410/// @param NextField If non-NULL and the first designator in @p DIE is
1411/// a field, this will be set to the field declaration corresponding
1412/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001413///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001414/// @param NextElementIndex If non-NULL and the first designator in @p
1415/// DIE is an array designator or GNU array-range designator, this
1416/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001417///
1418/// @param Index Index into @p IList where the designated initializer
1419/// @p DIE occurs.
1420///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001421/// @param StructuredList The initializer list expression that
1422/// describes all of the subobject initializers in the order they'll
1423/// actually be initialized.
1424///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001425/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001426bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001427InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001428 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001429 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001430 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001431 QualType &CurrentObjectType,
1432 RecordDecl::field_iterator *NextField,
1433 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001434 unsigned &Index,
1435 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001436 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001437 bool FinishSubobjectInit,
1438 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001439 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001440 // Check the actual initialization for the designated object type.
1441 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001442
1443 // Temporarily remove the designator expression from the
1444 // initializer list that the child calls see, so that we don't try
1445 // to re-process the designator.
1446 unsigned OldIndex = Index;
1447 IList->setInit(OldIndex, DIE->getInit());
1448
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001449 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001450 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001451
1452 // Restore the designated initializer expression in the syntactic
1453 // form of the initializer list.
1454 if (IList->getInit(OldIndex) != DIE->getInit())
1455 DIE->setInit(IList->getInit(OldIndex));
1456 IList->setInit(OldIndex, DIE);
1457
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001458 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001459 }
1460
Douglas Gregora5324162009-04-15 04:56:10 +00001461 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001462 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001463 "Need a non-designated initializer list to start from");
1464
Douglas Gregora5324162009-04-15 04:56:10 +00001465 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001466 // Determine the structural initializer list that corresponds to the
1467 // current subobject.
1468 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001469 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001470 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001471 SourceRange(D->getStartLocation(),
1472 DIE->getSourceRange().getEnd()));
1473 assert(StructuredList && "Expected a structured initializer list");
1474
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001475 if (D->isFieldDesignator()) {
1476 // C99 6.7.8p7:
1477 //
1478 // If a designator has the form
1479 //
1480 // . identifier
1481 //
1482 // then the current object (defined below) shall have
1483 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001484 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001485 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001486 if (!RT) {
1487 SourceLocation Loc = D->getDotLoc();
1488 if (Loc.isInvalid())
1489 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001490 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1491 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001492 ++Index;
1493 return true;
1494 }
1495
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001496 // Note: we perform a linear search of the fields here, despite
1497 // the fact that we have a faster lookup method, because we always
1498 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001499 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001500 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001501 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001502 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001503 Field = RT->getDecl()->field_begin(),
1504 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001505 for (; Field != FieldEnd; ++Field) {
1506 if (Field->isUnnamedBitfield())
1507 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001508
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001509 // If we find a field representing an anonymous field, look in the
1510 // IndirectFieldDecl that follow for the designated initializer.
1511 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1512 if (IndirectFieldDecl *IF =
1513 FindIndirectFieldDesignator(*Field, FieldName)) {
1514 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1515 D = DIE->getDesignator(DesigIdx);
1516 break;
1517 }
1518 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001519 if (KnownField && KnownField == *Field)
1520 break;
1521 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001522 break;
1523
1524 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001525 }
1526
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001527 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001528 // There was no normal field in the struct with the designated
1529 // name. Perform another lookup for this name, which may find
1530 // something that we can't designate (e.g., a member function),
1531 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001532 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001533 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001534 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001535 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001536 // Name lookup didn't find anything. Determine whether this
1537 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001538 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001539 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001540 TypoCorrection Corrected = SemaRef.CorrectTypo(
1541 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1542 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1543 RT->getDecl(), false, Sema::CTC_NoKeywords);
1544 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001545 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001546 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001547 std::string CorrectedStr(
1548 Corrected.getAsString(SemaRef.getLangOptions()));
1549 std::string CorrectedQuotedStr(
1550 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001552 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001553 << FieldName << CurrentObjectType << CorrectedQuotedStr
1554 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001555 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001556 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001557 } else {
1558 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1559 << FieldName << CurrentObjectType;
1560 ++Index;
1561 return true;
1562 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001564
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001565 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001566 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001567 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001568 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001569 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001570 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001571 ++Index;
1572 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001573 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001574
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001575 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001576 // The replacement field comes from typo correction; find it
1577 // in the list of fields.
1578 FieldIndex = 0;
1579 Field = RT->getDecl()->field_begin();
1580 for (; Field != FieldEnd; ++Field) {
1581 if (Field->isUnnamedBitfield())
1582 continue;
1583
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001584 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001585 Field->getIdentifier() == ReplacementField->getIdentifier())
1586 break;
1587
1588 ++FieldIndex;
1589 }
1590 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001591 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001592
1593 // All of the fields of a union are located at the same place in
1594 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001595 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001596 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001597 StructuredList->setInitializedFieldInUnion(*Field);
1598 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001599
Douglas Gregora82064c2011-06-29 21:51:31 +00001600 // Make sure we can use this declaration.
1601 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1602 ++Index;
1603 return true;
1604 }
1605
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001607 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001608
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001609 // Make sure that our non-designated initializer list has space
1610 // for a subobject corresponding to this field.
1611 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001612 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001613
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001614 // This designator names a flexible array member.
1615 if (Field->getType()->isIncompleteArrayType()) {
1616 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001617 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001618 // We can't designate an object within the flexible array
1619 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001620 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001621 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001622 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001623 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001624 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001625 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001626 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001627 << *Field;
1628 Invalid = true;
1629 }
1630
Chris Lattner001b29c2010-10-10 17:49:49 +00001631 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1632 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001633 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001634 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001635 diag::err_flexible_array_init_needs_braces)
1636 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001637 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001638 << *Field;
1639 Invalid = true;
1640 }
1641
Eli Friedman3fa64df2011-08-23 22:24:57 +00001642 // Check GNU flexible array initializer.
1643 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1644 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001645 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001646
1647 if (Invalid) {
1648 ++Index;
1649 return true;
1650 }
1651
1652 // Initialize the array.
1653 bool prevHadError = hadError;
1654 unsigned newStructuredIndex = FieldIndex;
1655 unsigned OldIndex = Index;
1656 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001657
1658 InitializedEntity MemberEntity =
1659 InitializedEntity::InitializeMember(*Field, &Entity);
1660 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001661 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001662
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001663 IList->setInit(OldIndex, DIE);
1664 if (hadError && !prevHadError) {
1665 ++Field;
1666 ++FieldIndex;
1667 if (NextField)
1668 *NextField = Field;
1669 StructuredIndex = FieldIndex;
1670 return true;
1671 }
1672 } else {
1673 // Recurse to check later designated subobjects.
1674 QualType FieldType = (*Field)->getType();
1675 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001676
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001677 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001678 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1680 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001681 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001682 true, false))
1683 return true;
1684 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001685
1686 // Find the position of the next field to be initialized in this
1687 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001688 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001689 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001690
1691 // If this the first designator, our caller will continue checking
1692 // the rest of this struct/class/union subobject.
1693 if (IsFirstDesignator) {
1694 if (NextField)
1695 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001697 return false;
1698 }
1699
Douglas Gregor17bd0942009-01-28 23:36:17 +00001700 if (!FinishSubobjectInit)
1701 return false;
1702
Douglas Gregord5846a12009-04-15 06:41:24 +00001703 // We've already initialized something in the union; we're done.
1704 if (RT->getDecl()->isUnion())
1705 return hadError;
1706
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001707 // Check the remaining fields within this class/struct/union subobject.
1708 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001709
Anders Carlsson6cabf312010-01-23 23:23:01 +00001710 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001711 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001712 return hadError && !prevHadError;
1713 }
1714
1715 // C99 6.7.8p6:
1716 //
1717 // If a designator has the form
1718 //
1719 // [ constant-expression ]
1720 //
1721 // then the current object (defined below) shall have array
1722 // type and the expression shall be an integer constant
1723 // expression. If the array is of unknown size, any
1724 // nonnegative value is valid.
1725 //
1726 // Additionally, cope with the GNU extension that permits
1727 // designators of the form
1728 //
1729 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001730 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001731 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001732 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001733 << CurrentObjectType;
1734 ++Index;
1735 return true;
1736 }
1737
1738 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001739 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1740 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001741 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001742 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001743 DesignatedEndIndex = DesignatedStartIndex;
1744 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001745 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001746
Mike Stump11289f42009-09-09 15:08:12 +00001747 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001748 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001749 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001750 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001751 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001752
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001753 // Codegen can't handle evaluating array range designators that have side
1754 // effects, because we replicate the AST value for each initialized element.
1755 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1756 // elements with something that has a side effect, so codegen can emit an
1757 // "error unsupported" error instead of miscompiling the app.
1758 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1759 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001760 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001761 }
1762
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001763 if (isa<ConstantArrayType>(AT)) {
1764 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001765 DesignatedStartIndex
1766 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001767 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001768 DesignatedEndIndex
1769 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001770 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1771 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001772 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001773 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001774 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001775 << IndexExpr->getSourceRange();
1776 ++Index;
1777 return true;
1778 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001779 } else {
1780 // Make sure the bit-widths and signedness match.
1781 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001782 DesignatedEndIndex
1783 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001784 else if (DesignatedStartIndex.getBitWidth() <
1785 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001786 DesignatedStartIndex
1787 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001788 DesignatedStartIndex.setIsUnsigned(true);
1789 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001790 }
Mike Stump11289f42009-09-09 15:08:12 +00001791
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001792 // Make sure that our non-designated initializer list has space
1793 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001794 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001795 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001796 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001797
Douglas Gregor17bd0942009-01-28 23:36:17 +00001798 // Repeatedly perform subobject initializations in the range
1799 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001800
Douglas Gregor17bd0942009-01-28 23:36:17 +00001801 // Move to the next designator
1802 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1803 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001804
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001805 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001806 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001807
Douglas Gregor17bd0942009-01-28 23:36:17 +00001808 while (DesignatedStartIndex <= DesignatedEndIndex) {
1809 // Recurse to check later designated subobjects.
1810 QualType ElementType = AT->getElementType();
1811 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001813 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1815 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001816 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001817 (DesignatedStartIndex == DesignatedEndIndex),
1818 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001819 return true;
1820
1821 // Move to the next index in the array that we'll be initializing.
1822 ++DesignatedStartIndex;
1823 ElementIndex = DesignatedStartIndex.getZExtValue();
1824 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001825
1826 // If this the first designator, our caller will continue checking
1827 // the rest of this array subobject.
1828 if (IsFirstDesignator) {
1829 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001830 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001831 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001832 return false;
1833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregor17bd0942009-01-28 23:36:17 +00001835 if (!FinishSubobjectInit)
1836 return false;
1837
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001838 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001839 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001841 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001842 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001843 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001844}
1845
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001846// Get the structured initializer list for a subobject of type
1847// @p CurrentObjectType.
1848InitListExpr *
1849InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1850 QualType CurrentObjectType,
1851 InitListExpr *StructuredList,
1852 unsigned StructuredIndex,
1853 SourceRange InitRange) {
1854 Expr *ExistingInit = 0;
1855 if (!StructuredList)
1856 ExistingInit = SyntacticToSemantic[IList];
1857 else if (StructuredIndex < StructuredList->getNumInits())
1858 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001859
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001860 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1861 return Result;
1862
1863 if (ExistingInit) {
1864 // We are creating an initializer list that initializes the
1865 // subobjects of the current object, but there was already an
1866 // initialization that completely initialized the current
1867 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001868 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001869 // struct X { int a, b; };
1870 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001871 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001872 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1873 // designated initializer re-initializes the whole
1874 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001875 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001876 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001877 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001878 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001879 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001880 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 << ExistingInit->getSourceRange();
1882 }
1883
Mike Stump11289f42009-09-09 15:08:12 +00001884 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001885 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1886 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001887 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001888
Douglas Gregora8a089b2010-07-13 18:40:04 +00001889 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001890
Douglas Gregor6d00c992009-03-20 23:58:33 +00001891 // Pre-allocate storage for the structured initializer list.
1892 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001893 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001894 bool GotNumInits = false;
1895 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001896 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001897 GotNumInits = true;
1898 } else if (Index < IList->getNumInits()) {
1899 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001900 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001901 GotNumInits = true;
1902 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001903 }
1904
Mike Stump11289f42009-09-09 15:08:12 +00001905 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001906 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1907 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1908 NumElements = CAType->getSize().getZExtValue();
1909 // Simple heuristic so that we don't allocate a very large
1910 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001911 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001912 NumElements = 0;
1913 }
John McCall9dd450b2009-09-21 23:43:11 +00001914 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001915 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001916 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001917 RecordDecl *RDecl = RType->getDecl();
1918 if (RDecl->isUnion())
1919 NumElements = 1;
1920 else
Mike Stump11289f42009-09-09 15:08:12 +00001921 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001922 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001923 }
1924
Douglas Gregor221c9a52009-03-21 18:13:52 +00001925 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001926 NumElements = IList->getNumInits();
1927
Ted Kremenekac034612010-04-13 23:39:13 +00001928 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001929
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001930 // Link this new initializer list into the structured initializer
1931 // lists.
1932 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001933 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001934 else {
1935 Result->setSyntacticForm(IList);
1936 SyntacticToSemantic[IList] = Result;
1937 }
1938
1939 return Result;
1940}
1941
1942/// Update the initializer at index @p StructuredIndex within the
1943/// structured initializer list to the value @p expr.
1944void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1945 unsigned &StructuredIndex,
1946 Expr *expr) {
1947 // No structured initializer list to update
1948 if (!StructuredList)
1949 return;
1950
Ted Kremenekac034612010-04-13 23:39:13 +00001951 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1952 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001953 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001954 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001955 diag::warn_initializer_overrides)
1956 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001957 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001958 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001959 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001960 << PrevInit->getSourceRange();
1961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001963 ++StructuredIndex;
1964}
1965
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001966/// Check that the given Index expression is a valid array designator
1967/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001968/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001969/// and produces a reasonable diagnostic if there is a
1970/// failure. Returns true if there was an error, false otherwise. If
1971/// everything went okay, Value will receive the value of the constant
1972/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001973static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001974CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001975 SourceLocation Loc = Index->getSourceRange().getBegin();
1976
1977 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001978 if (S.VerifyIntegerConstantExpression(Index, &Value))
1979 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001980
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001981 if (Value.isSigned() && Value.isNegative())
1982 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001983 << Value.toString(10) << Index->getSourceRange();
1984
Douglas Gregor51650d32009-01-23 21:04:18 +00001985 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001986 return false;
1987}
1988
John McCalldadc5752010-08-24 06:29:42 +00001989ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001990 SourceLocation Loc,
1991 bool GNUSyntax,
1992 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001993 typedef DesignatedInitExpr::Designator ASTDesignator;
1994
1995 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001996 SmallVector<ASTDesignator, 32> Designators;
1997 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001998
1999 // Build designators and check array designator expressions.
2000 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2001 const Designator &D = Desig.getDesignator(Idx);
2002 switch (D.getKind()) {
2003 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002004 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002005 D.getFieldLoc()));
2006 break;
2007
2008 case Designator::ArrayDesignator: {
2009 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2010 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002011 if (!Index->isTypeDependent() &&
2012 !Index->isValueDependent() &&
2013 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002014 Invalid = true;
2015 else {
2016 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002017 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002018 D.getRBracketLoc()));
2019 InitExpressions.push_back(Index);
2020 }
2021 break;
2022 }
2023
2024 case Designator::ArrayRangeDesignator: {
2025 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2026 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2027 llvm::APSInt StartValue;
2028 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002029 bool StartDependent = StartIndex->isTypeDependent() ||
2030 StartIndex->isValueDependent();
2031 bool EndDependent = EndIndex->isTypeDependent() ||
2032 EndIndex->isValueDependent();
2033 if ((!StartDependent &&
2034 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2035 (!EndDependent &&
2036 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002037 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002038 else {
2039 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002040 if (StartDependent || EndDependent) {
2041 // Nothing to compute.
2042 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002043 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002044 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002045 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002046
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002047 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002048 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002049 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002050 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2051 Invalid = true;
2052 } else {
2053 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002054 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002055 D.getEllipsisLoc(),
2056 D.getRBracketLoc()));
2057 InitExpressions.push_back(StartIndex);
2058 InitExpressions.push_back(EndIndex);
2059 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002060 }
2061 break;
2062 }
2063 }
2064 }
2065
2066 if (Invalid || Init.isInvalid())
2067 return ExprError();
2068
2069 // Clear out the expressions within the designation.
2070 Desig.ClearExprs(*this);
2071
2072 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002073 = DesignatedInitExpr::Create(Context,
2074 Designators.data(), Designators.size(),
2075 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002076 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Douglas Gregorc124e592011-01-16 16:13:16 +00002078 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002079 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2080 << DIE->getSourceRange();
2081 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002082 Diag(DIE->getLocStart(), diag::ext_designated_init)
2083 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002084
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002085 return Owned(DIE);
2086}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002087
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002088//===----------------------------------------------------------------------===//
2089// Initialization entity
2090//===----------------------------------------------------------------------===//
2091
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002092InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002093 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002095{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002096 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2097 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002098 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002099 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002100 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002101 Type = VT->getElementType();
2102 } else {
2103 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2104 assert(CT && "Unexpected type");
2105 Kind = EK_ComplexElement;
2106 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002107 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002108}
2109
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002111 CXXBaseSpecifier *Base,
2112 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002113{
2114 InitializedEntity Result;
2115 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002116 Result.Base = reinterpret_cast<uintptr_t>(Base);
2117 if (IsInheritedVirtualBase)
2118 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregor1b303932009-12-22 15:35:07 +00002120 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002121 return Result;
2122}
2123
Douglas Gregor85dabae2009-12-16 01:38:02 +00002124DeclarationName InitializedEntity::getName() const {
2125 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002126 case EK_Parameter: {
2127 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2128 return (D ? D->getDeclName() : DeclarationName());
2129 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002130
2131 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002132 case EK_Member:
2133 return VariableOrMember->getDeclName();
2134
2135 case EK_Result:
2136 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002137 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002138 case EK_Temporary:
2139 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002140 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002141 case EK_ArrayElement:
2142 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002143 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002144 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002145 return DeclarationName();
2146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
Douglas Gregor85dabae2009-12-16 01:38:02 +00002148 // Silence GCC warning
2149 return DeclarationName();
2150}
2151
Douglas Gregora4b592a2009-12-19 03:01:41 +00002152DeclaratorDecl *InitializedEntity::getDecl() const {
2153 switch (getKind()) {
2154 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002155 case EK_Member:
2156 return VariableOrMember;
2157
John McCall31168b02011-06-15 23:02:42 +00002158 case EK_Parameter:
2159 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2160
Douglas Gregora4b592a2009-12-19 03:01:41 +00002161 case EK_Result:
2162 case EK_Exception:
2163 case EK_New:
2164 case EK_Temporary:
2165 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002166 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002167 case EK_ArrayElement:
2168 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002169 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002170 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002171 return 0;
2172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173
Douglas Gregora4b592a2009-12-19 03:01:41 +00002174 // Silence GCC warning
2175 return 0;
2176}
2177
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002178bool InitializedEntity::allowsNRVO() const {
2179 switch (getKind()) {
2180 case EK_Result:
2181 case EK_Exception:
2182 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002184 case EK_Variable:
2185 case EK_Parameter:
2186 case EK_Member:
2187 case EK_New:
2188 case EK_Temporary:
2189 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002190 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002191 case EK_ArrayElement:
2192 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002193 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002194 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002195 break;
2196 }
2197
2198 return false;
2199}
2200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002201//===----------------------------------------------------------------------===//
2202// Initialization sequence
2203//===----------------------------------------------------------------------===//
2204
2205void InitializationSequence::Step::Destroy() {
2206 switch (Kind) {
2207 case SK_ResolveAddressOfOverloadedFunction:
2208 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002209 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002210 case SK_CastDerivedToBaseLValue:
2211 case SK_BindReference:
2212 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002213 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002214 case SK_UserConversion:
2215 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002216 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002217 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002218 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002219 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002220 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002221 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002222 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002223 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002224 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002225 case SK_PassByIndirectCopyRestore:
2226 case SK_PassByIndirectRestore:
2227 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002228 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002230 case SK_ConversionSequence:
2231 delete ICS;
2232 }
2233}
2234
Douglas Gregor838fcc32010-03-26 20:14:36 +00002235bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002236 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002237}
2238
2239bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002240 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002241 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Douglas Gregor838fcc32010-03-26 20:14:36 +00002243 switch (getFailureKind()) {
2244 case FK_TooManyInitsForReference:
2245 case FK_ArrayNeedsInitList:
2246 case FK_ArrayNeedsInitListOrStringLiteral:
2247 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2248 case FK_NonConstLValueReferenceBindingToTemporary:
2249 case FK_NonConstLValueReferenceBindingToUnrelated:
2250 case FK_RValueReferenceBindingToLValue:
2251 case FK_ReferenceInitDropsQualifiers:
2252 case FK_ReferenceInitFailed:
2253 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002254 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002255 case FK_TooManyInitsForScalar:
2256 case FK_ReferenceBindingToInitList:
2257 case FK_InitListBadDestinationType:
2258 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002259 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002260 case FK_ArrayTypeMismatch:
2261 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002262 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002263
Douglas Gregor838fcc32010-03-26 20:14:36 +00002264 case FK_ReferenceInitOverloadFailed:
2265 case FK_UserConversionOverloadFailed:
2266 case FK_ConstructorOverloadFailed:
2267 return FailedOverloadResult == OR_Ambiguous;
2268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269
Douglas Gregor838fcc32010-03-26 20:14:36 +00002270 return false;
2271}
2272
Douglas Gregorb33eed02010-04-16 22:09:46 +00002273bool InitializationSequence::isConstructorInitialization() const {
2274 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2275}
2276
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002277bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2278 const Expr *Initializer,
2279 bool *isInitializerConstant,
2280 APValue *ConstantValue) const {
2281 if (Steps.empty() || Initializer->isValueDependent())
2282 return false;
2283
2284 const Step &LastStep = Steps.back();
2285 if (LastStep.Kind != SK_ConversionSequence)
2286 return false;
2287
2288 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2289 const StandardConversionSequence *SCS = NULL;
2290 switch (ICS.getKind()) {
2291 case ImplicitConversionSequence::StandardConversion:
2292 SCS = &ICS.Standard;
2293 break;
2294 case ImplicitConversionSequence::UserDefinedConversion:
2295 SCS = &ICS.UserDefined.After;
2296 break;
2297 case ImplicitConversionSequence::AmbiguousConversion:
2298 case ImplicitConversionSequence::EllipsisConversion:
2299 case ImplicitConversionSequence::BadConversion:
2300 return false;
2301 }
2302
2303 // Check if SCS represents a narrowing conversion, according to C++0x
2304 // [dcl.init.list]p7:
2305 //
2306 // A narrowing conversion is an implicit conversion ...
2307 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2308 QualType FromType = SCS->getToType(0);
2309 QualType ToType = SCS->getToType(1);
2310 switch (PossibleNarrowing) {
2311 // * from a floating-point type to an integer type, or
2312 //
2313 // * from an integer type or unscoped enumeration type to a floating-point
2314 // type, except where the source is a constant expression and the actual
2315 // value after conversion will fit into the target type and will produce
2316 // the original value when converted back to the original type, or
2317 case ICK_Floating_Integral:
2318 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2319 *isInitializerConstant = false;
2320 return true;
2321 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2322 llvm::APSInt IntConstantValue;
2323 if (Initializer &&
2324 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2325 // Convert the integer to the floating type.
2326 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2327 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2328 llvm::APFloat::rmNearestTiesToEven);
2329 // And back.
2330 llvm::APSInt ConvertedValue = IntConstantValue;
2331 bool ignored;
2332 Result.convertToInteger(ConvertedValue,
2333 llvm::APFloat::rmTowardZero, &ignored);
2334 // If the resulting value is different, this was a narrowing conversion.
2335 if (IntConstantValue != ConvertedValue) {
2336 *isInitializerConstant = true;
2337 *ConstantValue = APValue(IntConstantValue);
2338 return true;
2339 }
2340 } else {
2341 // Variables are always narrowings.
2342 *isInitializerConstant = false;
2343 return true;
2344 }
2345 }
2346 return false;
2347
2348 // * from long double to double or float, or from double to float, except
2349 // where the source is a constant expression and the actual value after
2350 // conversion is within the range of values that can be represented (even
2351 // if it cannot be represented exactly), or
2352 case ICK_Floating_Conversion:
2353 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2354 // FromType is larger than ToType.
2355 Expr::EvalResult InitializerValue;
2356 // FIXME: Check whether Initializer is a constant expression according
2357 // to C++0x [expr.const], rather than just whether it can be folded.
2358 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2359 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2360 // Constant! (Except for FIXME above.)
2361 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2362 // Convert the source value into the target type.
2363 bool ignored;
2364 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2365 Ctx.getFloatTypeSemantics(ToType),
2366 llvm::APFloat::rmNearestTiesToEven, &ignored);
2367 // If there was no overflow, the source value is within the range of
2368 // values that can be represented.
2369 if (ConvertStatus & llvm::APFloat::opOverflow) {
2370 *isInitializerConstant = true;
2371 *ConstantValue = InitializerValue.Val;
2372 return true;
2373 }
2374 } else {
2375 *isInitializerConstant = false;
2376 return true;
2377 }
2378 }
2379 return false;
2380
2381 // * from an integer type or unscoped enumeration type to an integer type
2382 // that cannot represent all the values of the original type, except where
2383 // the source is a constant expression and the actual value after
2384 // conversion will fit into the target type and will produce the original
2385 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002386 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002387 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2388 // Boolean conversions can be from pointers and pointers to members
2389 // [conv.bool], and those aren't considered narrowing conversions.
2390 return false;
2391 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002392 case ICK_Integral_Conversion: {
2393 assert(FromType->isIntegralOrUnscopedEnumerationType());
2394 assert(ToType->isIntegralOrUnscopedEnumerationType());
2395 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2396 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2397 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2398 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2399
2400 if (FromWidth > ToWidth ||
2401 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2402 // Not all values of FromType can be represented in ToType.
2403 llvm::APSInt InitializerValue;
2404 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2405 *isInitializerConstant = true;
2406 *ConstantValue = APValue(InitializerValue);
2407
2408 // Add a bit to the InitializerValue so we don't have to worry about
2409 // signed vs. unsigned comparisons.
2410 InitializerValue = InitializerValue.extend(
2411 InitializerValue.getBitWidth() + 1);
2412 // Convert the initializer to and from the target width and signed-ness.
2413 llvm::APSInt ConvertedValue = InitializerValue;
2414 ConvertedValue = ConvertedValue.trunc(ToWidth);
2415 ConvertedValue.setIsSigned(ToSigned);
2416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2417 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2418 // If the result is different, this was a narrowing conversion.
2419 return ConvertedValue != InitializerValue;
2420 } else {
2421 // Variables are always narrowings.
2422 *isInitializerConstant = false;
2423 return true;
2424 }
2425 }
2426 return false;
2427 }
2428
2429 default:
2430 // Other kinds of conversions are not narrowings.
2431 return false;
2432 }
2433}
2434
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002435void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002436 FunctionDecl *Function,
2437 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002438 Step S;
2439 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2440 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002441 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002442 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002443 Steps.push_back(S);
2444}
2445
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002446void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002447 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002448 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002449 switch (VK) {
2450 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2451 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2452 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002453 default: llvm_unreachable("No such category");
2454 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002455 S.Type = BaseType;
2456 Steps.push_back(S);
2457}
2458
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002460 bool BindingTemporary) {
2461 Step S;
2462 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2463 S.Type = T;
2464 Steps.push_back(S);
2465}
2466
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002467void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2468 Step S;
2469 S.Kind = SK_ExtraneousCopyToTemporary;
2470 S.Type = T;
2471 Steps.push_back(S);
2472}
2473
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002474void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002475 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002476 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002477 Step S;
2478 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002479 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002480 S.Function.Function = Function;
2481 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002482 Steps.push_back(S);
2483}
2484
2485void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002486 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002488 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002489 switch (VK) {
2490 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002491 S.Kind = SK_QualificationConversionRValue;
2492 break;
John McCall2536c6d2010-08-25 10:28:54 +00002493 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002494 S.Kind = SK_QualificationConversionXValue;
2495 break;
John McCall2536c6d2010-08-25 10:28:54 +00002496 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002497 S.Kind = SK_QualificationConversionLValue;
2498 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002499 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002500 S.Type = Ty;
2501 Steps.push_back(S);
2502}
2503
2504void InitializationSequence::AddConversionSequenceStep(
2505 const ImplicitConversionSequence &ICS,
2506 QualType T) {
2507 Step S;
2508 S.Kind = SK_ConversionSequence;
2509 S.Type = T;
2510 S.ICS = new ImplicitConversionSequence(ICS);
2511 Steps.push_back(S);
2512}
2513
Douglas Gregor51e77d52009-12-10 17:56:55 +00002514void InitializationSequence::AddListInitializationStep(QualType T) {
2515 Step S;
2516 S.Kind = SK_ListInitialization;
2517 S.Type = T;
2518 Steps.push_back(S);
2519}
2520
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002521void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002522InitializationSequence::AddConstructorInitializationStep(
2523 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002524 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002525 QualType T) {
2526 Step S;
2527 S.Kind = SK_ConstructorInitialization;
2528 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002529 S.Function.Function = Constructor;
2530 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002531 Steps.push_back(S);
2532}
2533
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002534void InitializationSequence::AddZeroInitializationStep(QualType T) {
2535 Step S;
2536 S.Kind = SK_ZeroInitialization;
2537 S.Type = T;
2538 Steps.push_back(S);
2539}
2540
Douglas Gregore1314a62009-12-18 05:02:21 +00002541void InitializationSequence::AddCAssignmentStep(QualType T) {
2542 Step S;
2543 S.Kind = SK_CAssignment;
2544 S.Type = T;
2545 Steps.push_back(S);
2546}
2547
Eli Friedman78275202009-12-19 08:11:05 +00002548void InitializationSequence::AddStringInitStep(QualType T) {
2549 Step S;
2550 S.Kind = SK_StringInit;
2551 S.Type = T;
2552 Steps.push_back(S);
2553}
2554
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002555void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2556 Step S;
2557 S.Kind = SK_ObjCObjectConversion;
2558 S.Type = T;
2559 Steps.push_back(S);
2560}
2561
Douglas Gregore2f943b2011-02-22 18:29:51 +00002562void InitializationSequence::AddArrayInitStep(QualType T) {
2563 Step S;
2564 S.Kind = SK_ArrayInit;
2565 S.Type = T;
2566 Steps.push_back(S);
2567}
2568
John McCall31168b02011-06-15 23:02:42 +00002569void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2570 bool shouldCopy) {
2571 Step s;
2572 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2573 : SK_PassByIndirectRestore);
2574 s.Type = type;
2575 Steps.push_back(s);
2576}
2577
2578void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2579 Step S;
2580 S.Kind = SK_ProduceObjCObject;
2581 S.Type = T;
2582 Steps.push_back(S);
2583}
2584
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002585void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002586 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002587 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 this->Failure = Failure;
2589 this->FailedOverloadResult = Result;
2590}
2591
2592//===----------------------------------------------------------------------===//
2593// Attempt initialization
2594//===----------------------------------------------------------------------===//
2595
John McCall31168b02011-06-15 23:02:42 +00002596static void MaybeProduceObjCObject(Sema &S,
2597 InitializationSequence &Sequence,
2598 const InitializedEntity &Entity) {
2599 if (!S.getLangOptions().ObjCAutoRefCount) return;
2600
2601 /// When initializing a parameter, produce the value if it's marked
2602 /// __attribute__((ns_consumed)).
2603 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2604 if (!Entity.isParameterConsumed())
2605 return;
2606
2607 assert(Entity.getType()->isObjCRetainableType() &&
2608 "consuming an object of unretainable type?");
2609 Sequence.AddProduceObjCObjectStep(Entity.getType());
2610
2611 /// When initializing a return value, if the return type is a
2612 /// retainable type, then returns need to immediately retain the
2613 /// object. If an autorelease is required, it will be done at the
2614 /// last instant.
2615 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2616 if (!Entity.getType()->isObjCRetainableType())
2617 return;
2618
2619 Sequence.AddProduceObjCObjectStep(Entity.getType());
2620 }
2621}
2622
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002623/// \brief Attempt list initialization (C++0x [dcl.init.list])
2624static void TryListInitialization(Sema &S,
2625 const InitializedEntity &Entity,
2626 const InitializationKind &Kind,
2627 InitListExpr *InitList,
2628 InitializationSequence &Sequence) {
2629 // FIXME: We only perform rudimentary checking of list
2630 // initializations at this point, then assume that any list
2631 // initialization of an array, aggregate, or scalar will be
2632 // well-formed. When we actually "perform" list initialization, we'll
2633 // do all of the necessary checking. C++0x initializer lists will
2634 // force us to perform more checking here.
2635
2636 QualType DestType = Entity.getType();
2637
2638 // C++ [dcl.init]p13:
2639 // If T is a scalar type, then a declaration of the form
2640 //
2641 // T x = { a };
2642 //
2643 // is equivalent to
2644 //
2645 // T x = a;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002646 if (DestType->isAnyComplexType()) {
2647 // We allow more than 1 init for complex types in some cases, even though
2648 // they are scalar.
2649 } else if (DestType->isScalarType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002650 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2651 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2652 return;
2653 }
2654
2655 // Assume scalar initialization from a single value works.
2656 } else if (DestType->isAggregateType()) {
2657 // Assume aggregate initialization works.
2658 } else if (DestType->isVectorType()) {
2659 // Assume vector initialization works.
2660 } else if (DestType->isReferenceType()) {
2661 // FIXME: C++0x defines behavior for this.
2662 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2663 return;
2664 } else if (DestType->isRecordType()) {
2665 // FIXME: C++0x defines behavior for this
2666 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2667 }
2668
2669 // Add a general "list initialization" step.
2670 Sequence.AddListInitializationStep(DestType);
2671}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002672
2673/// \brief Try a reference initialization that involves calling a conversion
2674/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002675static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2676 const InitializedEntity &Entity,
2677 const InitializationKind &Kind,
2678 Expr *Initializer,
2679 bool AllowRValues,
2680 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002681 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002682 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2683 QualType T1 = cv1T1.getUnqualifiedType();
2684 QualType cv2T2 = Initializer->getType();
2685 QualType T2 = cv2T2.getUnqualifiedType();
2686
2687 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002688 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002689 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002691 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002692 ObjCConversion,
2693 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002694 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002695 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002696 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002697 (void)ObjCLifetimeConversion;
2698
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002699 // Build the candidate set directly in the initialization sequence
2700 // structure, so that it will persist if we fail.
2701 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2702 CandidateSet.clear();
2703
2704 // Determine whether we are allowed to call explicit constructors or
2705 // explicit conversion operators.
2706 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002708 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002709 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2710 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002711 // The type we're converting to is a class type. Enumerate its constructors
2712 // to see if there is a suitable conversion.
2713 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002714
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002715 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002716 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002717 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002718 NamedDecl *D = *Con;
2719 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2720
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002721 // Find the constructor (which may be a template).
2722 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002723 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002724 if (ConstructorTmpl)
2725 Constructor = cast<CXXConstructorDecl>(
2726 ConstructorTmpl->getTemplatedDecl());
2727 else
John McCalla0296f72010-03-19 07:35:19 +00002728 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002729
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002730 if (!Constructor->isInvalidDecl() &&
2731 Constructor->isConvertingConstructor(AllowExplicit)) {
2732 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002733 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002734 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002735 &Initializer, 1, CandidateSet,
2736 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002737 else
John McCalla0296f72010-03-19 07:35:19 +00002738 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002739 &Initializer, 1, CandidateSet,
2740 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002742 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002743 }
John McCall3696dcb2010-08-17 07:23:57 +00002744 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2745 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
Douglas Gregor496e8b342010-05-07 19:42:26 +00002747 const RecordType *T2RecordType = 0;
2748 if ((T2RecordType = T2->getAs<RecordType>()) &&
2749 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002750 // The type we're converting from is a class type, enumerate its conversion
2751 // functions.
2752 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2753
John McCallad371252010-01-20 00:46:10 +00002754 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002755 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002756 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2757 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 NamedDecl *D = *I;
2759 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2760 if (isa<UsingShadowDecl>(D))
2761 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2764 CXXConversionDecl *Conv;
2765 if (ConvTemplate)
2766 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2767 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002768 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002770 // If the conversion function doesn't return a reference type,
2771 // it can't be considered for this conversion unless we're allowed to
2772 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773 // FIXME: Do we need to make sure that we only consider conversion
2774 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002775 // break recursion.
2776 if ((AllowExplicit || !Conv->isExplicit()) &&
2777 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2778 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002779 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002780 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002781 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002782 else
John McCalla0296f72010-03-19 07:35:19 +00002783 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002784 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002785 }
2786 }
2787 }
John McCall3696dcb2010-08-17 07:23:57 +00002788 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2789 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002790
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002791 SourceLocation DeclLoc = Initializer->getLocStart();
2792
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002794 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002796 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002797 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002798
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002800
Chandler Carruth30141632011-02-25 19:41:05 +00002801 // This is the overload that will actually be used for the initialization, so
2802 // mark it as used.
2803 S.MarkDeclarationReferenced(DeclLoc, Function);
2804
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002805 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002806 if (isa<CXXConversionDecl>(Function))
2807 T2 = Function->getResultType();
2808 else
2809 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002810
2811 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002812 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002813 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002814
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002815 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002816 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002817 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002818 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002819 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002820 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002821 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002822
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002823 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002824 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002825 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002826 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002828 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002829 NewDerivedToBase, NewObjCConversion,
2830 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002831 if (NewRefRelationship == Sema::Ref_Incompatible) {
2832 // If the type we've converted to is not reference-related to the
2833 // type we're looking for, then there is another conversion step
2834 // we need to perform to produce a temporary of the right type
2835 // that we'll be binding to.
2836 ImplicitConversionSequence ICS;
2837 ICS.setStandard();
2838 ICS.Standard = Best->FinalConversion;
2839 T2 = ICS.Standard.getToType(2);
2840 Sequence.AddConversionSequenceStep(ICS, T2);
2841 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002842 Sequence.AddDerivedToBaseCastStep(
2843 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002844 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002845 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002846 else if (NewObjCConversion)
2847 Sequence.AddObjCObjectConversionStep(
2848 S.Context.getQualifiedType(T1,
2849 T2.getNonReferenceType().getQualifiers()));
2850
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002851 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002852 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002854 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2855 return OR_Success;
2856}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002857
2858/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2859static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002860 const InitializedEntity &Entity,
2861 const InitializationKind &Kind,
2862 Expr *Initializer,
2863 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002864 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002865 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002866 Qualifiers T1Quals;
2867 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002868 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002869 Qualifiers T2Quals;
2870 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002871 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002872
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002873 // If the initializer is the address of an overloaded function, try
2874 // to resolve the overloaded function. If all goes well, T2 is the
2875 // type of the resulting function.
2876 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002877 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002878 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002879 T1,
2880 false,
2881 Found)) {
2882 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2883 cv2T2 = Fn->getType();
2884 T2 = cv2T2.getUnqualifiedType();
2885 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002886 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2887 return;
2888 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002889 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002890
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002891 // Compute some basic properties of the types and the initializer.
2892 bool isLValueRef = DestType->isLValueReferenceType();
2893 bool isRValueRef = !isLValueRef;
2894 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002895 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002896 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002897 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002898 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002899 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002900 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002902 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002904 // "cv2 T2" as follows:
2905 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002907 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002908 // Note the analogous bullet points for rvlaue refs to functions. Because
2909 // there are no function rvalues in C++, rvalue refs to functions are treated
2910 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002911 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002912 bool T1Function = T1->isFunctionType();
2913 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002915 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002917 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002919 // reference-compatible with "cv2 T2," or
2920 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002921 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002922 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002923 // can occur. However, we do pay attention to whether it is a bit-field
2924 // to decide whether we're actually binding to a temporary created from
2925 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002926 if (DerivedToBase)
2927 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002928 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002929 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002930 else if (ObjCConversion)
2931 Sequence.AddObjCObjectConversionStep(
2932 S.Context.getQualifiedType(T1, T2Quals));
2933
Chandler Carruth04bdce62010-01-12 20:32:25 +00002934 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002935 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002936 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002937 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002938 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002939 return;
2940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002941
2942 // - has a class type (i.e., T2 is a class type), where T1 is not
2943 // reference-related to T2, and can be implicitly converted to an
2944 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2945 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002946 // applicable conversion functions (13.3.1.6) and choosing the best
2947 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002948 // If we have an rvalue ref to function type here, the rhs must be
2949 // an rvalue.
2950 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2951 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002953 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002954 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002955 Sequence);
2956 if (ConvOvlResult == OR_Success)
2957 return;
John McCall0d1da222010-01-12 00:44:57 +00002958 if (ConvOvlResult != OR_No_Viable_Function) {
2959 Sequence.SetOverloadFailure(
2960 InitializationSequence::FK_ReferenceInitOverloadFailed,
2961 ConvOvlResult);
2962 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002963 }
2964 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002967 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002968 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002969 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002970 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2971 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2972 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002973 Sequence.SetOverloadFailure(
2974 InitializationSequence::FK_ReferenceInitOverloadFailed,
2975 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002976 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002977 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002978 ? (RefRelationship == Sema::Ref_Related
2979 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2980 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2981 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002982
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002983 return;
2984 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002985
Douglas Gregor92e460e2011-01-20 16:44:54 +00002986 // - If the initializer expression
2987 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2988 // "cv1 T1" is reference-compatible with "cv2 T2"
2989 // Note: functions are handled below.
2990 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002991 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002992 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002993 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002994 (InitCategory.isXValue() ||
2995 (InitCategory.isPRValue() && T2->isRecordType()) ||
2996 (InitCategory.isPRValue() && T2->isArrayType()))) {
2997 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2998 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002999 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3000 // compiler the freedom to perform a copy here or bind to the
3001 // object, while C++0x requires that we bind directly to the
3002 // object. Hence, we always bind to the object without making an
3003 // extra copy. However, in C++03 requires that we check for the
3004 // presence of a suitable copy constructor:
3005 //
3006 // The constructor that would be used to make the copy shall
3007 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003008 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003009 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003011
Douglas Gregor92e460e2011-01-20 16:44:54 +00003012 if (DerivedToBase)
3013 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3014 ValueKind);
3015 else if (ObjCConversion)
3016 Sequence.AddObjCObjectConversionStep(
3017 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003018
Douglas Gregor92e460e2011-01-20 16:44:54 +00003019 if (T1Quals != T2Quals)
3020 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00003022 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025
3026 // - has a class type (i.e., T2 is a class type), where T1 is not
3027 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003028 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3029 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003030 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003031 if (RefRelationship == Sema::Ref_Incompatible) {
3032 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3033 Kind, Initializer,
3034 /*AllowRValues=*/true,
3035 Sequence);
3036 if (ConvOvlResult)
3037 Sequence.SetOverloadFailure(
3038 InitializationSequence::FK_ReferenceInitOverloadFailed,
3039 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003040
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003041 return;
3042 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003044 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3045 return;
3046 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003047
3048 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003049 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003051 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003052
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003053 // Determine whether we are allowed to call explicit constructors or
3054 // explicit conversion operators.
3055 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003056
3057 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3058
John McCall31168b02011-06-15 23:02:42 +00003059 ImplicitConversionSequence ICS
3060 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003061 /*SuppressUserConversions*/ false,
3062 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003063 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003064 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3065 /*AllowObjCWritebackConversion=*/false);
3066
3067 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003068 // FIXME: Use the conversion function set stored in ICS to turn
3069 // this into an overloading ambiguity diagnostic. However, we need
3070 // to keep that set as an OverloadCandidateSet rather than as some
3071 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003072 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3073 Sequence.SetOverloadFailure(
3074 InitializationSequence::FK_ReferenceInitOverloadFailed,
3075 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003076 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3077 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003078 else
3079 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003080 return;
John McCall31168b02011-06-15 23:02:42 +00003081 } else {
3082 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003083 }
3084
3085 // [...] If T1 is reference-related to T2, cv1 must be the
3086 // same cv-qualification as, or greater cv-qualification
3087 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003088 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3089 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003091 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003092 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3093 return;
3094 }
3095
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003097 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003099 InitCategory.isLValue()) {
3100 Sequence.SetFailed(
3101 InitializationSequence::FK_RValueReferenceBindingToLValue);
3102 return;
3103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003105 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3106 return;
3107}
3108
3109/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110/// (C++ [dcl.init.string], C99 6.7.8).
3111static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003112 const InitializedEntity &Entity,
3113 const InitializationKind &Kind,
3114 Expr *Initializer,
3115 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003116 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003117}
3118
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3120/// enumerates the constructors of the initialized entity and performs overload
3121/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003123 const InitializedEntity &Entity,
3124 const InitializationKind &Kind,
3125 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003126 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003127 InitializationSequence &Sequence) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00003128 // Check constructor arguments for self reference.
3129 if (DeclaratorDecl *DD = Entity.getDecl())
3130 // Parameters arguments are occassionially constructed with itself,
3131 // for instance, in recursive functions. Skip them.
3132 if (!isa<ParmVarDecl>(DD))
3133 for (unsigned i = 0; i < NumArgs; ++i)
3134 S.CheckSelfReference(DD, Args[i]);
3135
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003136 // Build the candidate set directly in the initialization sequence
3137 // structure, so that it will persist if we fail.
3138 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3139 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003141 // Determine whether we are allowed to call explicit constructors or
3142 // explicit conversion operators.
3143 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3144 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003145 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003146
3147 // The type we're constructing needs to be complete.
3148 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003149 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003150 return;
3151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003153 // The type we're converting to is a class type. Enumerate its constructors
3154 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003155 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003157 CXXRecordDecl *DestRecordDecl
3158 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003159
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003160 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003161 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003162 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003163 NamedDecl *D = *Con;
3164 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003165 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003167 // Find the constructor (which may be a template).
3168 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003169 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003170 if (ConstructorTmpl)
3171 Constructor = cast<CXXConstructorDecl>(
3172 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003173 else {
John McCalla0296f72010-03-19 07:35:19 +00003174 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003175
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003176 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003177 // suppress user-defined conversions on the arguments.
3178 // FIXME: Move constructors?
3179 if (Kind.getKind() == InitializationKind::IK_Copy &&
3180 Constructor->isCopyConstructor())
3181 SuppressUserConversions = true;
3182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003184 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003185 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003186 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003187 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003188 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003189 Args, NumArgs, CandidateSet,
3190 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003191 else
John McCalla0296f72010-03-19 07:35:19 +00003192 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003193 Args, NumArgs, CandidateSet,
3194 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196 }
3197
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003198 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
3200 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003201 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003202 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003203 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003204 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003205 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003206 Result);
3207 return;
3208 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003209
3210 // C++0x [dcl.init]p6:
3211 // If a program calls for the default initialization of an object
3212 // of a const-qualified type T, T shall be a class type with a
3213 // user-provided default constructor.
3214 if (Kind.getKind() == InitializationKind::IK_Default &&
3215 Entity.getType().isConstQualified() &&
3216 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3217 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3218 return;
3219 }
3220
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003221 // Add the constructor initialization step. Any cv-qualification conversion is
3222 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003223 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003225 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003226 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003227}
3228
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003229/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003230static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003231 const InitializedEntity &Entity,
3232 const InitializationKind &Kind,
3233 InitializationSequence &Sequence) {
3234 // C++ [dcl.init]p5:
3235 //
3236 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003237 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003239 // -- if T is an array type, then each element is value-initialized;
3240 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3241 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003243 if (const RecordType *RT = T->getAs<RecordType>()) {
3244 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3245 // -- if T is a class type (clause 9) with a user-declared
3246 // constructor (12.1), then the default constructor for T is
3247 // called (and the initialization is ill-formed if T has no
3248 // accessible default constructor);
3249 //
3250 // FIXME: we really want to refer to a single subobject of the array,
3251 // but Entity doesn't have a way to capture that (yet).
3252 if (ClassDecl->hasUserDeclaredConstructor())
3253 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003255 // -- if T is a (possibly cv-qualified) non-union class type
3256 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003257 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003258 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003259 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003260 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003261 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003263 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003264 }
3265 }
3266
Douglas Gregor1b303932009-12-22 15:35:07 +00003267 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003268}
3269
Douglas Gregor85dabae2009-12-16 01:38:02 +00003270/// \brief Attempt default initialization (C++ [dcl.init]p6).
3271static void TryDefaultInitialization(Sema &S,
3272 const InitializedEntity &Entity,
3273 const InitializationKind &Kind,
3274 InitializationSequence &Sequence) {
3275 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276
Douglas Gregor85dabae2009-12-16 01:38:02 +00003277 // C++ [dcl.init]p6:
3278 // To default-initialize an object of type T means:
3279 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003280 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3281
Douglas Gregor85dabae2009-12-16 01:38:02 +00003282 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3283 // constructor for T is called (and the initialization is ill-formed if
3284 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003285 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003286 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3287 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003289
Douglas Gregor85dabae2009-12-16 01:38:02 +00003290 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291
Douglas Gregor85dabae2009-12-16 01:38:02 +00003292 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003294 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003295 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003296 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003297 return;
3298 }
3299
3300 // If the destination type has a lifetime property, zero-initialize it.
3301 if (DestType.getQualifiers().hasObjCLifetime()) {
3302 Sequence.AddZeroInitializationStep(Entity.getType());
3303 return;
3304 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003305}
3306
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003307/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3308/// which enumerates all conversion functions and performs overload resolution
3309/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003311 const InitializedEntity &Entity,
3312 const InitializationKind &Kind,
3313 Expr *Initializer,
3314 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003315 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003316 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3317 QualType SourceType = Initializer->getType();
3318 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3319 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003320
Douglas Gregor540c3b02009-12-14 17:27:33 +00003321 // Build the candidate set directly in the initialization sequence
3322 // structure, so that it will persist if we fail.
3323 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3324 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325
Douglas Gregor540c3b02009-12-14 17:27:33 +00003326 // Determine whether we are allowed to call explicit constructors or
3327 // explicit conversion operators.
3328 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329
Douglas Gregor540c3b02009-12-14 17:27:33 +00003330 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3331 // The type we're converting to is a class type. Enumerate its constructors
3332 // to see if there is a suitable conversion.
3333 CXXRecordDecl *DestRecordDecl
3334 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335
Douglas Gregord9848152010-04-26 14:36:57 +00003336 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003338 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003339 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003340 Con != ConEnd; ++Con) {
3341 NamedDecl *D = *Con;
3342 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
Douglas Gregord9848152010-04-26 14:36:57 +00003344 // Find the constructor (which may be a template).
3345 CXXConstructorDecl *Constructor = 0;
3346 FunctionTemplateDecl *ConstructorTmpl
3347 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003348 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003349 Constructor = cast<CXXConstructorDecl>(
3350 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003351 else
Douglas Gregord9848152010-04-26 14:36:57 +00003352 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353
Douglas Gregord9848152010-04-26 14:36:57 +00003354 if (!Constructor->isInvalidDecl() &&
3355 Constructor->isConvertingConstructor(AllowExplicit)) {
3356 if (ConstructorTmpl)
3357 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3358 /*ExplicitArgs*/ 0,
3359 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003360 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003361 else
3362 S.AddOverloadCandidate(Constructor, FoundDecl,
3363 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003364 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366 }
Douglas Gregord9848152010-04-26 14:36:57 +00003367 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003368 }
Eli Friedman78275202009-12-19 08:11:05 +00003369
3370 SourceLocation DeclLoc = Initializer->getLocStart();
3371
Douglas Gregor540c3b02009-12-14 17:27:33 +00003372 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3373 // The type we're converting from is a class type, enumerate its conversion
3374 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003375
Eli Friedman4afe9a32009-12-20 22:12:03 +00003376 // We can only enumerate the conversion functions for a complete type; if
3377 // the type isn't complete, simply skip this step.
3378 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3379 CXXRecordDecl *SourceRecordDecl
3380 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
John McCallad371252010-01-20 00:46:10 +00003382 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003383 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003384 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003386 I != E; ++I) {
3387 NamedDecl *D = *I;
3388 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3389 if (isa<UsingShadowDecl>(D))
3390 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391
Eli Friedman4afe9a32009-12-20 22:12:03 +00003392 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3393 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003394 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003395 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003396 else
John McCallda4458e2010-03-31 01:36:47 +00003397 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Eli Friedman4afe9a32009-12-20 22:12:03 +00003399 if (AllowExplicit || !Conv->isExplicit()) {
3400 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003401 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003402 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003403 CandidateSet);
3404 else
John McCalla0296f72010-03-19 07:35:19 +00003405 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003406 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003407 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003408 }
3409 }
3410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
3412 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003413 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003414 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003415 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003416 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003418 Result);
3419 return;
3420 }
John McCall0d1da222010-01-12 00:44:57 +00003421
Douglas Gregor540c3b02009-12-14 17:27:33 +00003422 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003423 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424
Douglas Gregor540c3b02009-12-14 17:27:33 +00003425 if (isa<CXXConstructorDecl>(Function)) {
3426 // Add the user-defined conversion step. Any cv-qualification conversion is
3427 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003428 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003429 return;
3430 }
3431
3432 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003433 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003434 if (ConvType->getAs<RecordType>()) {
3435 // If we're converting to a class type, there may be an copy if
3436 // the resulting temporary object (possible to create an object of
3437 // a base class type). That copy is not a separate conversion, so
3438 // we just make a note of the actual destination type (possibly a
3439 // base class of the type returned by the conversion function) and
3440 // let the user-defined conversion step handle the conversion.
3441 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3442 return;
3443 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003444
Douglas Gregor5ab11652010-04-17 22:01:05 +00003445 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446
Douglas Gregor5ab11652010-04-17 22:01:05 +00003447 // If the conversion following the call to the conversion function
3448 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003449 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3450 Best->FinalConversion.Third) {
3451 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003452 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003453 ICS.Standard = Best->FinalConversion;
3454 Sequence.AddConversionSequenceStep(ICS, DestType);
3455 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003456}
3457
John McCall31168b02011-06-15 23:02:42 +00003458/// The non-zero enum values here are indexes into diagnostic alternatives.
3459enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3460
3461/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003462static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3463 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003464 // Skip parens.
3465 e = e->IgnoreParens();
3466
3467 // Skip address-of nodes.
3468 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3469 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003470 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003471
3472 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003473 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3474 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003475 case CK_Dependent:
3476 case CK_BitCast:
3477 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003478 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003479 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003480
3481 case CK_ArrayToPointerDecay:
3482 return IIK_nonscalar;
3483
3484 case CK_NullToPointer:
3485 return IIK_okay;
3486
3487 default:
3488 break;
3489 }
3490
3491 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003492 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3493 if (!isAddressOf) return IIK_nonlocal;
3494
3495 VarDecl *var;
3496 if (isa<DeclRefExpr>(e)) {
3497 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3498 if (!var) return IIK_nonlocal;
3499 } else {
3500 var = cast<BlockDeclRefExpr>(e)->getDecl();
3501 }
3502
3503 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003504
3505 // If we have a conditional operator, check both sides.
3506 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003507 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003508 return iik;
3509
John McCall63f84442011-06-27 23:59:58 +00003510 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003511
3512 // These are never scalar.
3513 } else if (isa<ArraySubscriptExpr>(e)) {
3514 return IIK_nonscalar;
3515
3516 // Otherwise, it needs to be a null pointer constant.
3517 } else {
3518 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3519 ? IIK_okay : IIK_nonlocal);
3520 }
3521
3522 return IIK_nonlocal;
3523}
3524
3525/// Check whether the given expression is a valid operand for an
3526/// indirect copy/restore.
3527static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3528 assert(src->isRValue());
3529
John McCall63f84442011-06-27 23:59:58 +00003530 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003531 if (iik == IIK_okay) return;
3532
3533 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3534 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3535 << src->getSourceRange();
3536}
3537
Douglas Gregore2f943b2011-02-22 18:29:51 +00003538/// \brief Determine whether we have compatible array types for the
3539/// purposes of GNU by-copy array initialization.
3540static bool hasCompatibleArrayTypes(ASTContext &Context,
3541 const ArrayType *Dest,
3542 const ArrayType *Source) {
3543 // If the source and destination array types are equivalent, we're
3544 // done.
3545 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3546 return true;
3547
3548 // Make sure that the element types are the same.
3549 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3550 return false;
3551
3552 // The only mismatch we allow is when the destination is an
3553 // incomplete array type and the source is a constant array type.
3554 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3555}
3556
John McCall31168b02011-06-15 23:02:42 +00003557static bool tryObjCWritebackConversion(Sema &S,
3558 InitializationSequence &Sequence,
3559 const InitializedEntity &Entity,
3560 Expr *Initializer) {
3561 bool ArrayDecay = false;
3562 QualType ArgType = Initializer->getType();
3563 QualType ArgPointee;
3564 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3565 ArrayDecay = true;
3566 ArgPointee = ArgArrayType->getElementType();
3567 ArgType = S.Context.getPointerType(ArgPointee);
3568 }
3569
3570 // Handle write-back conversion.
3571 QualType ConvertedArgType;
3572 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3573 ConvertedArgType))
3574 return false;
3575
3576 // We should copy unless we're passing to an argument explicitly
3577 // marked 'out'.
3578 bool ShouldCopy = true;
3579 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3580 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3581
3582 // Do we need an lvalue conversion?
3583 if (ArrayDecay || Initializer->isGLValue()) {
3584 ImplicitConversionSequence ICS;
3585 ICS.setStandard();
3586 ICS.Standard.setAsIdentityConversion();
3587
3588 QualType ResultType;
3589 if (ArrayDecay) {
3590 ICS.Standard.First = ICK_Array_To_Pointer;
3591 ResultType = S.Context.getPointerType(ArgPointee);
3592 } else {
3593 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3594 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3595 }
3596
3597 Sequence.AddConversionSequenceStep(ICS, ResultType);
3598 }
3599
3600 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3601 return true;
3602}
3603
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003604InitializationSequence::InitializationSequence(Sema &S,
3605 const InitializedEntity &Entity,
3606 const InitializationKind &Kind,
3607 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003608 unsigned NumArgs)
3609 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003610 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003612 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613 // The semantics of initializers are as follows. The destination type is
3614 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003615 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003618 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003619
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003620 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3622 SequenceKind = DependentSequence;
3623 return;
3624 }
3625
Sebastian Redld201edf2011-06-05 13:59:11 +00003626 // Almost everything is a normal sequence.
3627 setSequenceKind(NormalSequence);
3628
John McCalled75c092010-12-07 22:54:16 +00003629 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003630 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3631 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3632 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003633 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003634 return;
3635 }
3636 Args[I] = Result.take();
3637 }
John McCalled75c092010-12-07 22:54:16 +00003638
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003639 QualType SourceType;
3640 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003641 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003642 Initializer = Args[0];
3643 if (!isa<InitListExpr>(Initializer))
3644 SourceType = Initializer->getType();
3645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
3647 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003648 // list-initialized (8.5.4).
3649 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003650 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003651 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003654 // - If the destination type is a reference type, see 8.5.3.
3655 if (DestType->isReferenceType()) {
3656 // C++0x [dcl.init.ref]p1:
3657 // A variable declared to be a T& or T&&, that is, "reference to type T"
3658 // (8.3.2), shall be initialized by an object, or function, of type T or
3659 // by an object that can be converted into a T.
3660 // (Therefore, multiple arguments are not permitted.)
3661 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003662 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003663 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003664 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003665 return;
3666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003668 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003669 if (Kind.getKind() == InitializationKind::IK_Value ||
3670 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003671 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003672 return;
3673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003674
Douglas Gregor85dabae2009-12-16 01:38:02 +00003675 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003676 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003677 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003678 return;
3679 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003680
John McCall66884dd2011-02-21 07:22:22 +00003681 // - If the destination type is an array of characters, an array of
3682 // char16_t, an array of char32_t, or an array of wchar_t, and the
3683 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003685 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003686 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3687 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003688 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003689 return;
3690 }
3691
Douglas Gregore2f943b2011-02-22 18:29:51 +00003692 // Note: as an GNU C extension, we allow initialization of an
3693 // array from a compound literal that creates an array of the same
3694 // type, so long as the initializer has no side effects.
3695 if (!S.getLangOptions().CPlusPlus && Initializer &&
3696 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3697 Initializer->getType()->isArrayType()) {
3698 const ArrayType *SourceAT
3699 = Context.getAsArrayType(Initializer->getType());
3700 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003701 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003702 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003703 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003704 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003705 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003706 }
3707 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003708 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003709 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003710 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003712 return;
3713 }
Eli Friedman78275202009-12-19 08:11:05 +00003714
John McCall31168b02011-06-15 23:02:42 +00003715 // Determine whether we should consider writeback conversions for
3716 // Objective-C ARC.
3717 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3718 Entity.getKind() == InitializedEntity::EK_Parameter;
3719
3720 // We're at the end of the line for C: it's either a write-back conversion
3721 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003722 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003723 // If allowed, check whether this is an Objective-C writeback conversion.
3724 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003725 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003726 return;
3727 }
3728
3729 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003730 AddCAssignmentStep(DestType);
3731 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003732 return;
3733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003734
John McCall31168b02011-06-15 23:02:42 +00003735 assert(S.getLangOptions().CPlusPlus);
3736
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003737 // - If the destination type is a (possibly cv-qualified) class type:
3738 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739 // - If the initialization is direct-initialization, or if it is
3740 // copy-initialization where the cv-unqualified version of the
3741 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003742 // class of the destination, constructors are considered. [...]
3743 if (Kind.getKind() == InitializationKind::IK_Direct ||
3744 (Kind.getKind() == InitializationKind::IK_Copy &&
3745 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3746 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003748 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003750 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 // used) to a derived class thereof are enumerated as described in
3753 // 13.3.1.4, and the best one is chosen through overload resolution
3754 // (13.3).
3755 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003756 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003757 return;
3758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759
Douglas Gregor85dabae2009-12-16 01:38:02 +00003760 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003761 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003762 return;
3763 }
3764 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765
3766 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003767 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003768 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003769 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3770 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003771 return;
3772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003774 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003775 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003776 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003779
3780 ImplicitConversionSequence ICS
3781 = S.TryImplicitConversion(Initializer, Entity.getType(),
3782 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003783 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003784 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003785 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3786 allowObjCWritebackConversion);
3787
3788 if (ICS.isStandard() &&
3789 ICS.Standard.Second == ICK_Writeback_Conversion) {
3790 // Objective-C ARC writeback conversion.
3791
3792 // We should copy unless we're passing to an argument explicitly
3793 // marked 'out'.
3794 bool ShouldCopy = true;
3795 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3796 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3797
3798 // If there was an lvalue adjustment, add it as a separate conversion.
3799 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3800 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3801 ImplicitConversionSequence LvalueICS;
3802 LvalueICS.setStandard();
3803 LvalueICS.Standard.setAsIdentityConversion();
3804 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3805 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003806 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003807 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003808
3809 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003810 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003811 DeclAccessPair dap;
3812 if (Initializer->getType() == Context.OverloadTy &&
3813 !S.ResolveAddressOfOverloadedFunction(Initializer
3814 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003815 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003816 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003817 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003818 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003819 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003820
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003821 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003822 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003823}
3824
3825InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003826 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003827 StepEnd = Steps.end();
3828 Step != StepEnd; ++Step)
3829 Step->Destroy();
3830}
3831
3832//===----------------------------------------------------------------------===//
3833// Perform initialization
3834//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003835static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003836getAssignmentAction(const InitializedEntity &Entity) {
3837 switch(Entity.getKind()) {
3838 case InitializedEntity::EK_Variable:
3839 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003840 case InitializedEntity::EK_Exception:
3841 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003842 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003843 return Sema::AA_Initializing;
3844
3845 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003847 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3848 return Sema::AA_Sending;
3849
Douglas Gregore1314a62009-12-18 05:02:21 +00003850 return Sema::AA_Passing;
3851
3852 case InitializedEntity::EK_Result:
3853 return Sema::AA_Returning;
3854
Douglas Gregore1314a62009-12-18 05:02:21 +00003855 case InitializedEntity::EK_Temporary:
3856 // FIXME: Can we tell apart casting vs. converting?
3857 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858
Douglas Gregore1314a62009-12-18 05:02:21 +00003859 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003860 case InitializedEntity::EK_ArrayElement:
3861 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003862 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003863 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003864 return Sema::AA_Initializing;
3865 }
3866
3867 return Sema::AA_Converting;
3868}
3869
Douglas Gregor95562572010-04-24 23:45:46 +00003870/// \brief Whether we should binding a created object as a temporary when
3871/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003872static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003873 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003874 case InitializedEntity::EK_ArrayElement:
3875 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003876 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003877 case InitializedEntity::EK_New:
3878 case InitializedEntity::EK_Variable:
3879 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003880 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003881 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003882 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003883 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003884 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003885 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
Douglas Gregore1314a62009-12-18 05:02:21 +00003887 case InitializedEntity::EK_Parameter:
3888 case InitializedEntity::EK_Temporary:
3889 return true;
3890 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Douglas Gregore1314a62009-12-18 05:02:21 +00003892 llvm_unreachable("missed an InitializedEntity kind?");
3893}
3894
Douglas Gregor95562572010-04-24 23:45:46 +00003895/// \brief Whether the given entity, when initialized with an object
3896/// created for that initialization, requires destruction.
3897static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3898 switch (Entity.getKind()) {
3899 case InitializedEntity::EK_Member:
3900 case InitializedEntity::EK_Result:
3901 case InitializedEntity::EK_New:
3902 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003903 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003904 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003905 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003906 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003907 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908
Douglas Gregor95562572010-04-24 23:45:46 +00003909 case InitializedEntity::EK_Variable:
3910 case InitializedEntity::EK_Parameter:
3911 case InitializedEntity::EK_Temporary:
3912 case InitializedEntity::EK_ArrayElement:
3913 case InitializedEntity::EK_Exception:
3914 return true;
3915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
3917 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003918}
3919
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003920/// \brief Make a (potentially elidable) temporary copy of the object
3921/// provided by the given initializer by calling the appropriate copy
3922/// constructor.
3923///
3924/// \param S The Sema object used for type-checking.
3925///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003926/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003927/// the type of the initializer expression or a superclass thereof.
3928///
3929/// \param Enter The entity being initialized.
3930///
3931/// \param CurInit The initializer expression.
3932///
3933/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3934/// is permitted in C++03 (but not C++0x) when binding a reference to
3935/// an rvalue.
3936///
3937/// \returns An expression that copies the initializer expression into
3938/// a temporary object, or an error expression if a copy could not be
3939/// created.
John McCalldadc5752010-08-24 06:29:42 +00003940static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003941 QualType T,
3942 const InitializedEntity &Entity,
3943 ExprResult CurInit,
3944 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003945 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003946 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003948 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003949 Class = cast<CXXRecordDecl>(Record->getDecl());
3950 if (!Class)
3951 return move(CurInit);
3952
Douglas Gregor5d369002011-01-21 18:05:27 +00003953 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003954 // When certain criteria are met, an implementation is allowed to
3955 // omit the copy/move construction of a class object, even if the
3956 // copy/move constructor and/or destructor for the object have
3957 // side effects. [...]
3958 // - when a temporary class object that has not been bound to a
3959 // reference (12.2) would be copied/moved to a class object
3960 // with the same cv-unqualified type, the copy/move operation
3961 // can be omitted by constructing the temporary object
3962 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003963 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003964 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003965 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003966 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003967 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003968 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003969 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003970 switch (Entity.getKind()) {
3971 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003972 Loc = Entity.getReturnLoc();
3973 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974
Douglas Gregore1314a62009-12-18 05:02:21 +00003975 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003976 Loc = Entity.getThrowLoc();
3977 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978
Douglas Gregore1314a62009-12-18 05:02:21 +00003979 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003980 Loc = Entity.getDecl()->getLocation();
3981 break;
3982
Anders Carlsson0bd52402010-01-24 00:19:41 +00003983 case InitializedEntity::EK_ArrayElement:
3984 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003985 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003986 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003987 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003988 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003989 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003990 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003991 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003992 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003993 Loc = CurInitExpr->getLocStart();
3994 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003995 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003996
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00003998 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3999 return move(CurInit);
4000
Douglas Gregorf282a762011-01-21 19:38:21 +00004001 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00004002 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00004003 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00004004 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004005 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004006 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00004007 // C++0x [dcl.init]p16, second bullet to class types, this
4008 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004009 CXXConstructorDecl *Constructor = 0;
4010
4011 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004012 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004013 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00004014 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00004015 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004016 continue;
4017
4018 DeclAccessPair FoundDecl
4019 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4020 S.AddOverloadCandidate(Constructor, FoundDecl,
4021 &CurInitExpr, 1, CandidateSet);
4022 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004024
4025 // Handle constructor templates.
4026 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4027 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00004028 continue;
John McCalla0296f72010-03-19 07:35:19 +00004029
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004030 Constructor = cast<CXXConstructorDecl>(
4031 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00004032 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004033 continue;
4034
4035 // FIXME: Do we need to limit this to copy-constructor-like
4036 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00004037 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004038 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4039 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4040 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Douglas Gregore1314a62009-12-18 05:02:21 +00004043 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004044 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004045 case OR_Success:
4046 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004047
Douglas Gregore1314a62009-12-18 05:02:21 +00004048 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004049 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4050 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4051 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004052 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004053 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004054 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004055 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004056 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004057 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058
Douglas Gregore1314a62009-12-18 05:02:21 +00004059 case OR_Ambiguous:
4060 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004061 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004062 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004063 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004064 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregore1314a62009-12-18 05:02:21 +00004066 case OR_Deleted:
4067 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004068 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004069 << CurInitExpr->getSourceRange();
4070 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004071 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004072 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004073 }
4074
Douglas Gregor5ab11652010-04-17 22:01:05 +00004075 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004076 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004077 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004078
Anders Carlssona01874b2010-04-21 18:47:17 +00004079 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004080 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004081
4082 if (IsExtraneousCopy) {
4083 // If this is a totally extraneous copy for C++03 reference
4084 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004085 // expression. We don't generate an (elided) copy operation here
4086 // because doing so would require us to pass down a flag to avoid
4087 // infinite recursion, where each step adds another extraneous,
4088 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004089
Douglas Gregor30b52772010-04-18 07:57:34 +00004090 // Instantiate the default arguments of any extra parameters in
4091 // the selected copy constructor, as if we were going to create a
4092 // proper call to the copy constructor.
4093 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4094 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4095 if (S.RequireCompleteType(Loc, Parm->getType(),
4096 S.PDiag(diag::err_call_incomplete_argument)))
4097 break;
4098
4099 // Build the default argument expression; we don't actually care
4100 // if this succeeds or not, because this routine will complain
4101 // if there was a problem.
4102 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4103 }
4104
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004105 return S.Owned(CurInitExpr);
4106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107
Chandler Carruth30141632011-02-25 19:41:05 +00004108 S.MarkDeclarationReferenced(Loc, Constructor);
4109
Douglas Gregor5ab11652010-04-17 22:01:05 +00004110 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004111 // constructor call (we might have derived-to-base conversions, or
4112 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004113 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004114 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004115 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004116
Douglas Gregord0ace022010-04-25 00:55:24 +00004117 // Actually perform the constructor call.
4118 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004119 move_arg(ConstructorArgs),
4120 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004121 CXXConstructExpr::CK_Complete,
4122 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004123
Douglas Gregord0ace022010-04-25 00:55:24 +00004124 // If we're supposed to bind temporaries, do so.
4125 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4126 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4127 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004128}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004129
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004130void InitializationSequence::PrintInitLocationNote(Sema &S,
4131 const InitializedEntity &Entity) {
4132 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4133 if (Entity.getDecl()->getLocation().isInvalid())
4134 return;
4135
4136 if (Entity.getDecl()->getDeclName())
4137 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4138 << Entity.getDecl()->getDeclName();
4139 else
4140 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4141 }
4142}
4143
Sebastian Redl112aa822011-07-14 19:07:55 +00004144static bool isReferenceBinding(const InitializationSequence::Step &s) {
4145 return s.Kind == InitializationSequence::SK_BindReference ||
4146 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4147}
4148
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004149ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004150InitializationSequence::Perform(Sema &S,
4151 const InitializedEntity &Entity,
4152 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004153 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004154 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004155 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004156 unsigned NumArgs = Args.size();
4157 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004158 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
Sebastian Redld201edf2011-06-05 13:59:11 +00004161 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004162 // If the declaration is a non-dependent, incomplete array type
4163 // that has an initializer, then its type will be completed once
4164 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004165 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004166 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004167 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004168 if (const IncompleteArrayType *ArrayT
4169 = S.Context.getAsIncompleteArrayType(DeclType)) {
4170 // FIXME: We don't currently have the ability to accurately
4171 // compute the length of an initializer list without
4172 // performing full type-checking of the initializer list
4173 // (since we have to determine where braces are implicitly
4174 // introduced and such). So, we fall back to making the array
4175 // type a dependently-sized array type with no specified
4176 // bound.
4177 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4178 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004179
Douglas Gregor51e77d52009-12-10 17:56:55 +00004180 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004181 if (DeclaratorDecl *DD = Entity.getDecl()) {
4182 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4183 TypeLoc TL = TInfo->getTypeLoc();
4184 if (IncompleteArrayTypeLoc *ArrayLoc
4185 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4186 Brackets = ArrayLoc->getBracketsRange();
4187 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004188 }
4189
4190 *ResultType
4191 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4192 /*NumElts=*/0,
4193 ArrayT->getSizeModifier(),
4194 ArrayT->getIndexTypeCVRQualifiers(),
4195 Brackets);
4196 }
4197
4198 }
4199 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004200 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4201 Kind.isExplicitCast());
4202 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004203 }
4204
Sebastian Redld201edf2011-06-05 13:59:11 +00004205 // No steps means no initialization.
4206 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004207 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregor1b303932009-12-22 15:35:07 +00004209 QualType DestType = Entity.getType().getNonReferenceType();
4210 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004211 // the same as Entity.getDecl()->getType() in cases involving type merging,
4212 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004213 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004214 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004215 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004216
John McCalldadc5752010-08-24 06:29:42 +00004217 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004220 // grab the only argument out the Args and place it into the "current"
4221 // initializer.
4222 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004223 case SK_ResolveAddressOfOverloadedFunction:
4224 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004225 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004226 case SK_CastDerivedToBaseLValue:
4227 case SK_BindReference:
4228 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004229 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004230 case SK_UserConversion:
4231 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004232 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004233 case SK_QualificationConversionRValue:
4234 case SK_ConversionSequence:
4235 case SK_ListInitialization:
4236 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004237 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004238 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004239 case SK_ArrayInit:
4240 case SK_PassByIndirectCopyRestore:
4241 case SK_PassByIndirectRestore:
4242 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004243 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004244 CurInit = Args.get()[0];
4245 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004246
4247 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004248 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4249 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4250 if (CurInit.isInvalid())
4251 return ExprError();
4252 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004253 break;
John McCall34376a62010-12-04 03:47:34 +00004254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregore1314a62009-12-18 05:02:21 +00004256 case SK_ConstructorInitialization:
4257 case SK_ZeroInitialization:
4258 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
4261 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004262 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004263 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004264 for (step_iterator Step = step_begin(), StepEnd = step_end();
4265 Step != StepEnd; ++Step) {
4266 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004267 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
John Wiegley01296292011-04-08 18:41:53 +00004269 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004271 switch (Step->Kind) {
4272 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004274 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004275 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004276 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004277 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004278 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004279 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004280 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004282 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004283 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004284 case SK_CastDerivedToBaseLValue: {
4285 // We have a derived-to-base cast that produces either an rvalue or an
4286 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287
John McCallcf142162010-08-07 06:22:56 +00004288 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004289
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004290 // Casts to inaccessible base classes are allowed with C-style casts.
4291 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4292 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004293 CurInit.get()->getLocStart(),
4294 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004295 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004296 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297
Douglas Gregor88d292c2010-05-13 16:44:06 +00004298 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4299 QualType T = SourceType;
4300 if (const PointerType *Pointer = T->getAs<PointerType>())
4301 T = Pointer->getPointeeType();
4302 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004303 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004304 cast<CXXRecordDecl>(RecordTy->getDecl()));
4305 }
4306
John McCall2536c6d2010-08-25 10:28:54 +00004307 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004308 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004309 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004310 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004311 VK_XValue :
4312 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004313 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4314 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004315 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004316 CurInit.get(),
4317 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004318 break;
4319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004321 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004322 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004323 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4324 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004325 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004326 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004327 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004328 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004329 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004330 }
Anders Carlssona91be642010-01-29 02:47:33 +00004331
John Wiegley01296292011-04-08 18:41:53 +00004332 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004333 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004334 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4335 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004336 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004337 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004338 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004341 // Reference binding does not have any corresponding ASTs.
4342
4343 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004344 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004345 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004346
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004347 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004348
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004349 case SK_BindReferenceToTemporary:
4350 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004351 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004352 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004353
Douglas Gregorfe314812011-06-21 17:03:29 +00004354 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004355 CurInit = new (S.Context) MaterializeTemporaryExpr(
4356 Entity.getType().getNonReferenceType(),
4357 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004358 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004359
4360 // If we're binding to an Objective-C object that has lifetime, we
4361 // need cleanups.
4362 if (S.getLangOptions().ObjCAutoRefCount &&
4363 CurInit.get()->getType()->isObjCLifetimeType())
4364 S.ExprNeedsCleanups = true;
4365
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004366 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004368 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004370 /*IsExtraneousCopy=*/true);
4371 break;
4372
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004373 case SK_UserConversion: {
4374 // We have a user-defined conversion that invokes either a constructor
4375 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004376 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004377 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004378 FunctionDecl *Fn = Step->Function.Function;
4379 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004380 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004381 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004382 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004383 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004384 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004385 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004386 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004387
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004388 // Determine the arguments required to actually perform the constructor
4389 // call.
John Wiegley01296292011-04-08 18:41:53 +00004390 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004392 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004393 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004394 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004396 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004398 move_arg(ConstructorArgs),
4399 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004400 CXXConstructExpr::CK_Complete,
4401 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004402 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004403 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004404
Anders Carlssona01874b2010-04-21 18:47:17 +00004405 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004406 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004407 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408
John McCalle3027922010-08-25 11:45:40 +00004409 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004410 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4411 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4412 S.IsDerivedFrom(SourceType, Class))
4413 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414
Douglas Gregor95562572010-04-24 23:45:46 +00004415 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004416 } else {
4417 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004418 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004419 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004420 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004421 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004422 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
4424 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004425 // derived-to-base conversion? I believe the answer is "no", because
4426 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004427 ExprResult CurInitExprRes =
4428 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4429 FoundFn, Conversion);
4430 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004431 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004432 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004434 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004435 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004436 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004437 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438
John McCalle3027922010-08-25 11:45:40 +00004439 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440
Douglas Gregor95562572010-04-24 23:45:46 +00004441 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Sebastian Redl112aa822011-07-14 19:07:55 +00004444 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004445 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004446 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004447 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004448 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004449 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004451 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004452 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004453 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004454 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4455 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004456 }
4457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004459 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004460 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004461 CurInit.get()->getType(),
4462 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004463 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004465 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004466 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4467 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004468
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004469 break;
4470 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004471
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004472 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004473 case SK_QualificationConversionXValue:
4474 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004476 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004477 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004478 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004479 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004480 VK_XValue :
4481 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004482 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004483 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004484 }
4485
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004486 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004487 Sema::CheckedConversionKind CCK
4488 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4489 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4490 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4491 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004492 ExprResult CurInitExprRes =
4493 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004494 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004495 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004496 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004497 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004498 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500
Douglas Gregor51e77d52009-12-10 17:56:55 +00004501 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004502 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004503 QualType Ty = Step->Type;
Sebastian Redla846cac2011-09-24 17:47:46 +00004504 InitListChecker CheckInitList(S, Entity, InitList,
4505 ResultType ? *ResultType : Ty);
4506 if (CheckInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004507 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004508
4509 CurInit.release();
Sebastian Redla846cac2011-09-24 17:47:46 +00004510 CurInit = S.Owned(CheckInitList.getFullyStructuredList());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004511 break;
4512 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004513
4514 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004515 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004516 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004517 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004519 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004520 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004521 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4522 ? Kind.getEqualLoc()
4523 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004524
4525 if (Kind.getKind() == InitializationKind::IK_Default) {
4526 // Force even a trivial, implicit default constructor to be
4527 // semantically checked. We do this explicitly because we don't build
4528 // the definition for completely trivial constructors.
4529 CXXRecordDecl *ClassDecl = Constructor->getParent();
4530 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004531 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004532 ClassDecl->hasTrivialDefaultConstructor() &&
4533 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004534 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4535 }
4536
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004537 // Determine the arguments required to actually perform the constructor
4538 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004540 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004541 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
4543
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004544 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004545 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004546 (Kind.getKind() == InitializationKind::IK_Direct ||
4547 Kind.getKind() == InitializationKind::IK_Value)) {
4548 // An explicitly-constructed temporary, e.g., X(1, 2).
4549 unsigned NumExprs = ConstructorArgs.size();
4550 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004551 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004552 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553
Douglas Gregor2b88c112010-09-08 00:15:04 +00004554 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4555 if (!TSInfo)
4556 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004558 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4559 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004560 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004562 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004563 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004564 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004565 } else {
4566 CXXConstructExpr::ConstructionKind ConstructKind =
4567 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004569 if (Entity.getKind() == InitializedEntity::EK_Base) {
4570 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004572 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004573 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004574 ConstructKind = CXXConstructExpr::CK_Delegating;
4575 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004576
Chandler Carruth01718152010-10-25 08:47:36 +00004577 // Only get the parenthesis range if it is a direct construction.
4578 SourceRange parenRange =
4579 Kind.getKind() == InitializationKind::IK_Direct ?
4580 Kind.getParenRange() : SourceRange();
4581
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004582 // If the entity allows NRVO, mark the construction as elidable
4583 // unconditionally.
4584 if (Entity.allowsNRVO())
4585 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4586 Constructor, /*Elidable=*/true,
4587 move_arg(ConstructorArgs),
4588 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004589 ConstructKind,
4590 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004591 else
4592 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004594 move_arg(ConstructorArgs),
4595 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004596 ConstructKind,
4597 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004598 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004599 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004600 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004601
4602 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004603 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004604 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004605 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004607 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004608 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004610 break;
4611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004613 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004614 step_iterator NextStep = Step;
4615 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004617 NextStep->Kind == SK_ConstructorInitialization) {
4618 // The need for zero-initialization is recorded directly into
4619 // the call to the object's constructor within the next step.
4620 ConstructorInitRequiresZeroInit = true;
4621 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4622 S.getLangOptions().CPlusPlus &&
4623 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004624 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4625 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004627 Kind.getRange().getBegin());
4628
4629 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4630 TSInfo->getType().getNonLValueExprType(S.Context),
4631 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004632 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004633 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004634 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004635 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004636 break;
4637 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004638
4639 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004640 QualType SourceType = CurInit.get()->getType();
4641 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004642 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004643 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4644 if (Result.isInvalid())
4645 return ExprError();
4646 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004647
4648 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004649 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004650 if (ConvTy != Sema::Compatible &&
4651 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004652 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004653 == Sema::Compatible)
4654 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004655 if (CurInitExprRes.isInvalid())
4656 return ExprError();
4657 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004658
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004659 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004660 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4661 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004662 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004663 getAssignmentAction(Entity),
4664 &Complained)) {
4665 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004666 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004667 } else if (Complained)
4668 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004669 break;
4670 }
Eli Friedman78275202009-12-19 08:11:05 +00004671
4672 case SK_StringInit: {
4673 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004674 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004675 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004676 break;
4677 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004678
4679 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004680 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004681 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004682 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004683 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004684
4685 case SK_ArrayInit:
4686 // Okay: we checked everything before creating this step. Note that
4687 // this is a GNU extension.
4688 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004689 << Step->Type << CurInit.get()->getType()
4690 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004691
4692 // If the destination type is an incomplete array type, update the
4693 // type accordingly.
4694 if (ResultType) {
4695 if (const IncompleteArrayType *IncompleteDest
4696 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4697 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004698 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004699 *ResultType = S.Context.getConstantArrayType(
4700 IncompleteDest->getElementType(),
4701 ConstantSource->getSize(),
4702 ArrayType::Normal, 0);
4703 }
4704 }
4705 }
John McCall31168b02011-06-15 23:02:42 +00004706 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004707
John McCall31168b02011-06-15 23:02:42 +00004708 case SK_PassByIndirectCopyRestore:
4709 case SK_PassByIndirectRestore:
4710 checkIndirectCopyRestoreSource(S, CurInit.get());
4711 CurInit = S.Owned(new (S.Context)
4712 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4713 Step->Kind == SK_PassByIndirectCopyRestore));
4714 break;
4715
4716 case SK_ProduceObjCObject:
4717 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00004718 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00004719 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004720 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004721 }
4722 }
John McCall1f425642010-11-11 03:21:53 +00004723
4724 // Diagnose non-fatal problems with the completed initialization.
4725 if (Entity.getKind() == InitializedEntity::EK_Member &&
4726 cast<FieldDecl>(Entity.getDecl())->isBitField())
4727 S.CheckBitFieldInitialization(Kind.getLocation(),
4728 cast<FieldDecl>(Entity.getDecl()),
4729 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004731 return move(CurInit);
4732}
4733
4734//===----------------------------------------------------------------------===//
4735// Diagnose initialization failures
4736//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004738 const InitializedEntity &Entity,
4739 const InitializationKind &Kind,
4740 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004741 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004742 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Douglas Gregor1b303932009-12-22 15:35:07 +00004744 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004745 switch (Failure) {
4746 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004747 // FIXME: Customize for the initialized entity?
4748 if (NumArgs == 0)
4749 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4750 << DestType.getNonReferenceType();
4751 else // FIXME: diagnostic below could be better!
4752 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4753 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004754 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004755
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004756 case FK_ArrayNeedsInitList:
4757 case FK_ArrayNeedsInitListOrStringLiteral:
4758 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4759 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregore2f943b2011-02-22 18:29:51 +00004762 case FK_ArrayTypeMismatch:
4763 case FK_NonConstantArrayInit:
4764 S.Diag(Kind.getLocation(),
4765 (Failure == FK_ArrayTypeMismatch
4766 ? diag::err_array_init_different_type
4767 : diag::err_array_init_non_constant_array))
4768 << DestType.getNonReferenceType()
4769 << Args[0]->getType()
4770 << Args[0]->getSourceRange();
4771 break;
4772
John McCall16df1e52010-03-30 21:47:33 +00004773 case FK_AddressOfOverloadFailed: {
4774 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004776 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004777 true,
4778 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004779 break;
John McCall16df1e52010-03-30 21:47:33 +00004780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004782 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004783 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004784 switch (FailedOverloadResult) {
4785 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004786 if (Failure == FK_UserConversionOverloadFailed)
4787 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4788 << Args[0]->getType() << DestType
4789 << Args[0]->getSourceRange();
4790 else
4791 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4792 << DestType << Args[0]->getType()
4793 << Args[0]->getSourceRange();
4794
John McCall5c32be02010-08-24 20:38:10 +00004795 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004796 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004798 case OR_No_Viable_Function:
4799 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4800 << Args[0]->getType() << DestType.getNonReferenceType()
4801 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004802 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004803 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004804
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004805 case OR_Deleted: {
4806 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4807 << Args[0]->getType() << DestType.getNonReferenceType()
4808 << Args[0]->getSourceRange();
4809 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004810 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004811 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4812 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004813 if (Ovl == OR_Deleted) {
4814 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004815 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004816 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004817 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004818 }
4819 break;
4820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004822 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004823 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004824 break;
4825 }
4826 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004828 case FK_NonConstLValueReferenceBindingToTemporary:
4829 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004831 Failure == FK_NonConstLValueReferenceBindingToTemporary
4832 ? diag::err_lvalue_reference_bind_to_temporary
4833 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004834 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 << DestType.getNonReferenceType()
4836 << Args[0]->getType()
4837 << Args[0]->getSourceRange();
4838 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004840 case FK_RValueReferenceBindingToLValue:
4841 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004842 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004843 << Args[0]->getSourceRange();
4844 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 case FK_ReferenceInitDropsQualifiers:
4847 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4848 << DestType.getNonReferenceType()
4849 << Args[0]->getType()
4850 << Args[0]->getSourceRange();
4851 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004853 case FK_ReferenceInitFailed:
4854 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4855 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004856 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004857 << Args[0]->getType()
4858 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004859 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4860 Args[0]->getType()->isObjCObjectPointerType())
4861 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004862 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Douglas Gregorb491ed32011-02-19 21:32:49 +00004864 case FK_ConversionFailed: {
4865 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004866 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4867 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004868 << DestType
John McCall086a4642010-11-24 05:12:34 +00004869 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004870 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004871 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004872 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4873 Args[0]->getType()->isObjCObjectPointerType())
4874 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004875 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004876 }
John Wiegley01296292011-04-08 18:41:53 +00004877
4878 case FK_ConversionFromPropertyFailed:
4879 // No-op. This error has already been reported.
4880 break;
4881
Douglas Gregor51e77d52009-12-10 17:56:55 +00004882 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004883 SourceRange R;
4884
4885 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004886 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004887 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004889 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004890
Douglas Gregor8ec51732010-09-08 21:40:08 +00004891 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4892 if (Kind.isCStyleOrFunctionalCast())
4893 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4894 << R;
4895 else
4896 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4897 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004898 break;
4899 }
4900
4901 case FK_ReferenceBindingToInitList:
4902 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4903 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4904 break;
4905
4906 case FK_InitListBadDestinationType:
4907 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4908 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4909 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004911 case FK_ConstructorOverloadFailed: {
4912 SourceRange ArgsRange;
4913 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004914 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004915 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004917 // FIXME: Using "DestType" for the entity we're printing is probably
4918 // bad.
4919 switch (FailedOverloadResult) {
4920 case OR_Ambiguous:
4921 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4922 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004923 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4924 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004925 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004927 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004928 if (Kind.getKind() == InitializationKind::IK_Default &&
4929 (Entity.getKind() == InitializedEntity::EK_Base ||
4930 Entity.getKind() == InitializedEntity::EK_Member) &&
4931 isa<CXXConstructorDecl>(S.CurContext)) {
4932 // This is implicit default initialization of a member or
4933 // base within a constructor. If no viable function was
4934 // found, notify the user that she needs to explicitly
4935 // initialize this base/member.
4936 CXXConstructorDecl *Constructor
4937 = cast<CXXConstructorDecl>(S.CurContext);
4938 if (Entity.getKind() == InitializedEntity::EK_Base) {
4939 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4940 << Constructor->isImplicit()
4941 << S.Context.getTypeDeclType(Constructor->getParent())
4942 << /*base=*/0
4943 << Entity.getType();
4944
4945 RecordDecl *BaseDecl
4946 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4947 ->getDecl();
4948 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4949 << S.Context.getTagDeclType(BaseDecl);
4950 } else {
4951 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4952 << Constructor->isImplicit()
4953 << S.Context.getTypeDeclType(Constructor->getParent())
4954 << /*member=*/1
4955 << Entity.getName();
4956 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4957
4958 if (const RecordType *Record
4959 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004961 diag::note_previous_decl)
4962 << S.Context.getTagDeclType(Record->getDecl());
4963 }
4964 break;
4965 }
4966
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004967 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4968 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004969 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004970 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004971
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004972 case OR_Deleted: {
4973 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4974 << true << DestType << ArgsRange;
4975 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004976 OverloadingResult Ovl
4977 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004978 if (Ovl == OR_Deleted) {
4979 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004980 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004981 } else {
4982 llvm_unreachable("Inconsistent overload resolution?");
4983 }
4984 break;
4985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004987 case OR_Success:
4988 llvm_unreachable("Conversion did not fail!");
4989 break;
4990 }
4991 break;
4992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993
Douglas Gregor85dabae2009-12-16 01:38:02 +00004994 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004995 if (Entity.getKind() == InitializedEntity::EK_Member &&
4996 isa<CXXConstructorDecl>(S.CurContext)) {
4997 // This is implicit default-initialization of a const member in
4998 // a constructor. Complain that it needs to be explicitly
4999 // initialized.
5000 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5001 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5002 << Constructor->isImplicit()
5003 << S.Context.getTypeDeclType(Constructor->getParent())
5004 << /*const=*/1
5005 << Entity.getName();
5006 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5007 << Entity.getName();
5008 } else {
5009 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5010 << DestType << (bool)DestType->getAs<RecordType>();
5011 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005012 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005013
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005014 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005016 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005020 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005021 return true;
5022}
Douglas Gregore1314a62009-12-18 05:02:21 +00005023
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005024void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005025 switch (SequenceKind) {
5026 case FailedSequence: {
5027 OS << "Failed sequence: ";
5028 switch (Failure) {
5029 case FK_TooManyInitsForReference:
5030 OS << "too many initializers for reference";
5031 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005033 case FK_ArrayNeedsInitList:
5034 OS << "array requires initializer list";
5035 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005037 case FK_ArrayNeedsInitListOrStringLiteral:
5038 OS << "array requires initializer list or string literal";
5039 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040
Douglas Gregore2f943b2011-02-22 18:29:51 +00005041 case FK_ArrayTypeMismatch:
5042 OS << "array type mismatch";
5043 break;
5044
5045 case FK_NonConstantArrayInit:
5046 OS << "non-constant array initializer";
5047 break;
5048
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005049 case FK_AddressOfOverloadFailed:
5050 OS << "address of overloaded function failed";
5051 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005053 case FK_ReferenceInitOverloadFailed:
5054 OS << "overload resolution for reference initialization failed";
5055 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005057 case FK_NonConstLValueReferenceBindingToTemporary:
5058 OS << "non-const lvalue reference bound to temporary";
5059 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005061 case FK_NonConstLValueReferenceBindingToUnrelated:
5062 OS << "non-const lvalue reference bound to unrelated type";
5063 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005065 case FK_RValueReferenceBindingToLValue:
5066 OS << "rvalue reference bound to an lvalue";
5067 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005068
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005069 case FK_ReferenceInitDropsQualifiers:
5070 OS << "reference initialization drops qualifiers";
5071 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005073 case FK_ReferenceInitFailed:
5074 OS << "reference initialization failed";
5075 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005077 case FK_ConversionFailed:
5078 OS << "conversion failed";
5079 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
John Wiegley01296292011-04-08 18:41:53 +00005081 case FK_ConversionFromPropertyFailed:
5082 OS << "conversion from property failed";
5083 break;
5084
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005085 case FK_TooManyInitsForScalar:
5086 OS << "too many initializers for scalar";
5087 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005089 case FK_ReferenceBindingToInitList:
5090 OS << "referencing binding to initializer list";
5091 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005093 case FK_InitListBadDestinationType:
5094 OS << "initializer list for non-aggregate, non-scalar type";
5095 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005096
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005097 case FK_UserConversionOverloadFailed:
5098 OS << "overloading failed for user-defined conversion";
5099 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005100
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005101 case FK_ConstructorOverloadFailed:
5102 OS << "constructor overloading failed";
5103 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005104
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005105 case FK_DefaultInitOfConst:
5106 OS << "default initialization of a const variable";
5107 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005108
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005109 case FK_Incomplete:
5110 OS << "initialization of incomplete type";
5111 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005112 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005113 OS << '\n';
5114 return;
5115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005117 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005118 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005119 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005120
Sebastian Redld201edf2011-06-05 13:59:11 +00005121 case NormalSequence:
5122 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005123 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005126 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5127 if (S != step_begin()) {
5128 OS << " -> ";
5129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005131 switch (S->Kind) {
5132 case SK_ResolveAddressOfOverloadedFunction:
5133 OS << "resolve address of overloaded function";
5134 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005135
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005136 case SK_CastDerivedToBaseRValue:
5137 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5138 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005139
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005140 case SK_CastDerivedToBaseXValue:
5141 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5142 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005143
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005144 case SK_CastDerivedToBaseLValue:
5145 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5146 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005148 case SK_BindReference:
5149 OS << "bind reference to lvalue";
5150 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005152 case SK_BindReferenceToTemporary:
5153 OS << "bind reference to a temporary";
5154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005156 case SK_ExtraneousCopyToTemporary:
5157 OS << "extraneous C++03 copy to temporary";
5158 break;
5159
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005160 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005161 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005162 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005163
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005164 case SK_QualificationConversionRValue:
5165 OS << "qualification conversion (rvalue)";
5166
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005167 case SK_QualificationConversionXValue:
5168 OS << "qualification conversion (xvalue)";
5169
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005170 case SK_QualificationConversionLValue:
5171 OS << "qualification conversion (lvalue)";
5172 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005174 case SK_ConversionSequence:
5175 OS << "implicit conversion sequence (";
5176 S->ICS->DebugPrint(); // FIXME: use OS
5177 OS << ")";
5178 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005179
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005180 case SK_ListInitialization:
5181 OS << "list initialization";
5182 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005183
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005184 case SK_ConstructorInitialization:
5185 OS << "constructor initialization";
5186 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005188 case SK_ZeroInitialization:
5189 OS << "zero initialization";
5190 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005191
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005192 case SK_CAssignment:
5193 OS << "C assignment";
5194 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005195
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005196 case SK_StringInit:
5197 OS << "string initialization";
5198 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005199
5200 case SK_ObjCObjectConversion:
5201 OS << "Objective-C object conversion";
5202 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005203
5204 case SK_ArrayInit:
5205 OS << "array initialization";
5206 break;
John McCall31168b02011-06-15 23:02:42 +00005207
5208 case SK_PassByIndirectCopyRestore:
5209 OS << "pass by indirect copy and restore";
5210 break;
5211
5212 case SK_PassByIndirectRestore:
5213 OS << "pass by indirect restore";
5214 break;
5215
5216 case SK_ProduceObjCObject:
5217 OS << "Objective-C object retension";
5218 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005219 }
5220 }
5221}
5222
5223void InitializationSequence::dump() const {
5224 dump(llvm::errs());
5225}
5226
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005227static void DiagnoseNarrowingInInitList(
5228 Sema& S, QualType EntityType, const Expr *InitE,
5229 bool Constant, const APValue &ConstantValue) {
5230 if (Constant) {
5231 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005232 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005233 ? diag::err_init_list_constant_narrowing
5234 : diag::warn_init_list_constant_narrowing)
5235 << InitE->getSourceRange()
5236 << ConstantValue
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005237 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005238 } else
5239 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005240 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005241 ? diag::err_init_list_variable_narrowing
5242 : diag::warn_init_list_variable_narrowing)
5243 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005244 << InitE->getType().getLocalUnqualifiedType()
5245 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005246
5247 llvm::SmallString<128> StaticCast;
5248 llvm::raw_svector_ostream OS(StaticCast);
5249 OS << "static_cast<";
5250 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5251 // It's important to use the typedef's name if there is one so that the
5252 // fixit doesn't break code using types like int64_t.
5253 //
5254 // FIXME: This will break if the typedef requires qualification. But
5255 // getQualifiedNameAsString() includes non-machine-parsable components.
5256 OS << TT->getDecl();
5257 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5258 OS << BT->getName(S.getLangOptions());
5259 else {
5260 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5261 // with a broken cast.
5262 return;
5263 }
5264 OS << ">(";
5265 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5266 << InitE->getSourceRange()
5267 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5268 << FixItHint::CreateInsertion(
5269 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5270}
5271
Douglas Gregore1314a62009-12-18 05:02:21 +00005272//===----------------------------------------------------------------------===//
5273// Initialization helper functions
5274//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005275bool
5276Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5277 ExprResult Init) {
5278 if (Init.isInvalid())
5279 return false;
5280
5281 Expr *InitE = Init.get();
5282 assert(InitE && "No initialization expression");
5283
5284 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5285 SourceLocation());
5286 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005287 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005288}
5289
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005290ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005291Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5292 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005293 ExprResult Init,
5294 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005295 if (Init.isInvalid())
5296 return ExprError();
5297
John McCall1f425642010-11-11 03:21:53 +00005298 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005299 assert(InitE && "No initialization expression?");
5300
5301 if (EqualLoc.isInvalid())
5302 EqualLoc = InitE->getLocStart();
5303
5304 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5305 EqualLoc);
5306 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5307 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005308
5309 bool Constant = false;
5310 APValue Result;
5311 if (TopLevelOfInitList &&
5312 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5313 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5314 Constant, Result);
5315 }
John McCallfaf5fb42010-08-26 23:41:50 +00005316 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005317}