blob: 15bcb451e54c0922d466d898903d900a32aad3fb [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:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002219 case SK_ListConstructorCall:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002220 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002221 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002222 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002223 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002224 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002225 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002226 case SK_PassByIndirectCopyRestore:
2227 case SK_PassByIndirectRestore:
2228 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002229 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002230
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002231 case SK_ConversionSequence:
2232 delete ICS;
2233 }
2234}
2235
Douglas Gregor838fcc32010-03-26 20:14:36 +00002236bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002237 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002238}
2239
2240bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002241 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002242 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243
Douglas Gregor838fcc32010-03-26 20:14:36 +00002244 switch (getFailureKind()) {
2245 case FK_TooManyInitsForReference:
2246 case FK_ArrayNeedsInitList:
2247 case FK_ArrayNeedsInitListOrStringLiteral:
2248 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2249 case FK_NonConstLValueReferenceBindingToTemporary:
2250 case FK_NonConstLValueReferenceBindingToUnrelated:
2251 case FK_RValueReferenceBindingToLValue:
2252 case FK_ReferenceInitDropsQualifiers:
2253 case FK_ReferenceInitFailed:
2254 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002255 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002256 case FK_TooManyInitsForScalar:
2257 case FK_ReferenceBindingToInitList:
2258 case FK_InitListBadDestinationType:
2259 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002260 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002261 case FK_ArrayTypeMismatch:
2262 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002263 case FK_ListInitializationFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002264 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002265
Douglas Gregor838fcc32010-03-26 20:14:36 +00002266 case FK_ReferenceInitOverloadFailed:
2267 case FK_UserConversionOverloadFailed:
2268 case FK_ConstructorOverloadFailed:
2269 return FailedOverloadResult == OR_Ambiguous;
2270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271
Douglas Gregor838fcc32010-03-26 20:14:36 +00002272 return false;
2273}
2274
Douglas Gregorb33eed02010-04-16 22:09:46 +00002275bool InitializationSequence::isConstructorInitialization() const {
2276 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2277}
2278
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002279bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2280 const Expr *Initializer,
2281 bool *isInitializerConstant,
2282 APValue *ConstantValue) const {
2283 if (Steps.empty() || Initializer->isValueDependent())
2284 return false;
2285
2286 const Step &LastStep = Steps.back();
2287 if (LastStep.Kind != SK_ConversionSequence)
2288 return false;
2289
2290 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2291 const StandardConversionSequence *SCS = NULL;
2292 switch (ICS.getKind()) {
2293 case ImplicitConversionSequence::StandardConversion:
2294 SCS = &ICS.Standard;
2295 break;
2296 case ImplicitConversionSequence::UserDefinedConversion:
2297 SCS = &ICS.UserDefined.After;
2298 break;
2299 case ImplicitConversionSequence::AmbiguousConversion:
2300 case ImplicitConversionSequence::EllipsisConversion:
2301 case ImplicitConversionSequence::BadConversion:
2302 return false;
2303 }
2304
2305 // Check if SCS represents a narrowing conversion, according to C++0x
2306 // [dcl.init.list]p7:
2307 //
2308 // A narrowing conversion is an implicit conversion ...
2309 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2310 QualType FromType = SCS->getToType(0);
2311 QualType ToType = SCS->getToType(1);
2312 switch (PossibleNarrowing) {
2313 // * from a floating-point type to an integer type, or
2314 //
2315 // * from an integer type or unscoped enumeration type to a floating-point
2316 // type, except where the source is a constant expression and the actual
2317 // value after conversion will fit into the target type and will produce
2318 // the original value when converted back to the original type, or
2319 case ICK_Floating_Integral:
2320 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2321 *isInitializerConstant = false;
2322 return true;
2323 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2324 llvm::APSInt IntConstantValue;
2325 if (Initializer &&
2326 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2327 // Convert the integer to the floating type.
2328 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2329 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2330 llvm::APFloat::rmNearestTiesToEven);
2331 // And back.
2332 llvm::APSInt ConvertedValue = IntConstantValue;
2333 bool ignored;
2334 Result.convertToInteger(ConvertedValue,
2335 llvm::APFloat::rmTowardZero, &ignored);
2336 // If the resulting value is different, this was a narrowing conversion.
2337 if (IntConstantValue != ConvertedValue) {
2338 *isInitializerConstant = true;
2339 *ConstantValue = APValue(IntConstantValue);
2340 return true;
2341 }
2342 } else {
2343 // Variables are always narrowings.
2344 *isInitializerConstant = false;
2345 return true;
2346 }
2347 }
2348 return false;
2349
2350 // * from long double to double or float, or from double to float, except
2351 // where the source is a constant expression and the actual value after
2352 // conversion is within the range of values that can be represented (even
2353 // if it cannot be represented exactly), or
2354 case ICK_Floating_Conversion:
2355 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2356 // FromType is larger than ToType.
2357 Expr::EvalResult InitializerValue;
2358 // FIXME: Check whether Initializer is a constant expression according
2359 // to C++0x [expr.const], rather than just whether it can be folded.
2360 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2361 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2362 // Constant! (Except for FIXME above.)
2363 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2364 // Convert the source value into the target type.
2365 bool ignored;
2366 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2367 Ctx.getFloatTypeSemantics(ToType),
2368 llvm::APFloat::rmNearestTiesToEven, &ignored);
2369 // If there was no overflow, the source value is within the range of
2370 // values that can be represented.
2371 if (ConvertStatus & llvm::APFloat::opOverflow) {
2372 *isInitializerConstant = true;
2373 *ConstantValue = InitializerValue.Val;
2374 return true;
2375 }
2376 } else {
2377 *isInitializerConstant = false;
2378 return true;
2379 }
2380 }
2381 return false;
2382
2383 // * from an integer type or unscoped enumeration type to an integer type
2384 // that cannot represent all the values of the original type, except where
2385 // the source is a constant expression and the actual value after
2386 // conversion will fit into the target type and will produce the original
2387 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002388 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002389 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2390 // Boolean conversions can be from pointers and pointers to members
2391 // [conv.bool], and those aren't considered narrowing conversions.
2392 return false;
2393 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002394 case ICK_Integral_Conversion: {
2395 assert(FromType->isIntegralOrUnscopedEnumerationType());
2396 assert(ToType->isIntegralOrUnscopedEnumerationType());
2397 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2398 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2399 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2400 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2401
2402 if (FromWidth > ToWidth ||
2403 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2404 // Not all values of FromType can be represented in ToType.
2405 llvm::APSInt InitializerValue;
2406 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2407 *isInitializerConstant = true;
2408 *ConstantValue = APValue(InitializerValue);
2409
2410 // Add a bit to the InitializerValue so we don't have to worry about
2411 // signed vs. unsigned comparisons.
2412 InitializerValue = InitializerValue.extend(
2413 InitializerValue.getBitWidth() + 1);
2414 // Convert the initializer to and from the target width and signed-ness.
2415 llvm::APSInt ConvertedValue = InitializerValue;
2416 ConvertedValue = ConvertedValue.trunc(ToWidth);
2417 ConvertedValue.setIsSigned(ToSigned);
2418 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2419 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2420 // If the result is different, this was a narrowing conversion.
2421 return ConvertedValue != InitializerValue;
2422 } else {
2423 // Variables are always narrowings.
2424 *isInitializerConstant = false;
2425 return true;
2426 }
2427 }
2428 return false;
2429 }
2430
2431 default:
2432 // Other kinds of conversions are not narrowings.
2433 return false;
2434 }
2435}
2436
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002437void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002438 FunctionDecl *Function,
2439 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002440 Step S;
2441 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2442 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002443 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002444 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445 Steps.push_back(S);
2446}
2447
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002449 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002450 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002451 switch (VK) {
2452 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2453 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2454 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002455 default: llvm_unreachable("No such category");
2456 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002457 S.Type = BaseType;
2458 Steps.push_back(S);
2459}
2460
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002461void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002462 bool BindingTemporary) {
2463 Step S;
2464 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2465 S.Type = T;
2466 Steps.push_back(S);
2467}
2468
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002469void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2470 Step S;
2471 S.Kind = SK_ExtraneousCopyToTemporary;
2472 S.Type = T;
2473 Steps.push_back(S);
2474}
2475
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002476void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002477 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002478 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002479 Step S;
2480 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002481 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002482 S.Function.Function = Function;
2483 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002484 Steps.push_back(S);
2485}
2486
2487void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002488 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002489 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002490 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002491 switch (VK) {
2492 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002493 S.Kind = SK_QualificationConversionRValue;
2494 break;
John McCall2536c6d2010-08-25 10:28:54 +00002495 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002496 S.Kind = SK_QualificationConversionXValue;
2497 break;
John McCall2536c6d2010-08-25 10:28:54 +00002498 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002499 S.Kind = SK_QualificationConversionLValue;
2500 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002501 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002502 S.Type = Ty;
2503 Steps.push_back(S);
2504}
2505
2506void InitializationSequence::AddConversionSequenceStep(
2507 const ImplicitConversionSequence &ICS,
2508 QualType T) {
2509 Step S;
2510 S.Kind = SK_ConversionSequence;
2511 S.Type = T;
2512 S.ICS = new ImplicitConversionSequence(ICS);
2513 Steps.push_back(S);
2514}
2515
Douglas Gregor51e77d52009-12-10 17:56:55 +00002516void InitializationSequence::AddListInitializationStep(QualType T) {
2517 Step S;
2518 S.Kind = SK_ListInitialization;
2519 S.Type = T;
2520 Steps.push_back(S);
2521}
2522
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002523void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002524InitializationSequence::AddConstructorInitializationStep(
2525 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002526 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002527 QualType T) {
2528 Step S;
2529 S.Kind = SK_ConstructorInitialization;
2530 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002531 S.Function.Function = Constructor;
2532 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002533 Steps.push_back(S);
2534}
2535
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002536void InitializationSequence::AddZeroInitializationStep(QualType T) {
2537 Step S;
2538 S.Kind = SK_ZeroInitialization;
2539 S.Type = T;
2540 Steps.push_back(S);
2541}
2542
Douglas Gregore1314a62009-12-18 05:02:21 +00002543void InitializationSequence::AddCAssignmentStep(QualType T) {
2544 Step S;
2545 S.Kind = SK_CAssignment;
2546 S.Type = T;
2547 Steps.push_back(S);
2548}
2549
Eli Friedman78275202009-12-19 08:11:05 +00002550void InitializationSequence::AddStringInitStep(QualType T) {
2551 Step S;
2552 S.Kind = SK_StringInit;
2553 S.Type = T;
2554 Steps.push_back(S);
2555}
2556
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002557void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2558 Step S;
2559 S.Kind = SK_ObjCObjectConversion;
2560 S.Type = T;
2561 Steps.push_back(S);
2562}
2563
Douglas Gregore2f943b2011-02-22 18:29:51 +00002564void InitializationSequence::AddArrayInitStep(QualType T) {
2565 Step S;
2566 S.Kind = SK_ArrayInit;
2567 S.Type = T;
2568 Steps.push_back(S);
2569}
2570
John McCall31168b02011-06-15 23:02:42 +00002571void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2572 bool shouldCopy) {
2573 Step s;
2574 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2575 : SK_PassByIndirectRestore);
2576 s.Type = type;
2577 Steps.push_back(s);
2578}
2579
2580void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2581 Step S;
2582 S.Kind = SK_ProduceObjCObject;
2583 S.Type = T;
2584 Steps.push_back(S);
2585}
2586
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002589 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002590 this->Failure = Failure;
2591 this->FailedOverloadResult = Result;
2592}
2593
2594//===----------------------------------------------------------------------===//
2595// Attempt initialization
2596//===----------------------------------------------------------------------===//
2597
John McCall31168b02011-06-15 23:02:42 +00002598static void MaybeProduceObjCObject(Sema &S,
2599 InitializationSequence &Sequence,
2600 const InitializedEntity &Entity) {
2601 if (!S.getLangOptions().ObjCAutoRefCount) return;
2602
2603 /// When initializing a parameter, produce the value if it's marked
2604 /// __attribute__((ns_consumed)).
2605 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2606 if (!Entity.isParameterConsumed())
2607 return;
2608
2609 assert(Entity.getType()->isObjCRetainableType() &&
2610 "consuming an object of unretainable type?");
2611 Sequence.AddProduceObjCObjectStep(Entity.getType());
2612
2613 /// When initializing a return value, if the return type is a
2614 /// retainable type, then returns need to immediately retain the
2615 /// object. If an autorelease is required, it will be done at the
2616 /// last instant.
2617 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2618 if (!Entity.getType()->isObjCRetainableType())
2619 return;
2620
2621 Sequence.AddProduceObjCObjectStep(Entity.getType());
2622 }
2623}
2624
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002625/// \brief Attempt list initialization (C++0x [dcl.init.list])
2626static void TryListInitialization(Sema &S,
2627 const InitializedEntity &Entity,
2628 const InitializationKind &Kind,
2629 InitListExpr *InitList,
2630 InitializationSequence &Sequence) {
2631 // FIXME: We only perform rudimentary checking of list
2632 // initializations at this point, then assume that any list
2633 // initialization of an array, aggregate, or scalar will be
2634 // well-formed. When we actually "perform" list initialization, we'll
2635 // do all of the necessary checking. C++0x initializer lists will
2636 // force us to perform more checking here.
2637
2638 QualType DestType = Entity.getType();
2639
2640 // C++ [dcl.init]p13:
2641 // If T is a scalar type, then a declaration of the form
2642 //
2643 // T x = { a };
2644 //
2645 // is equivalent to
2646 //
2647 // T x = a;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002648 if (DestType->isAnyComplexType()) {
2649 // We allow more than 1 init for complex types in some cases, even though
2650 // they are scalar.
2651 } else if (DestType->isScalarType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002652 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2653 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2654 return;
2655 }
2656
2657 // Assume scalar initialization from a single value works.
2658 } else if (DestType->isAggregateType()) {
2659 // Assume aggregate initialization works.
2660 } else if (DestType->isVectorType()) {
2661 // Assume vector initialization works.
2662 } else if (DestType->isReferenceType()) {
2663 // FIXME: C++0x defines behavior for this.
2664 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2665 return;
2666 } else if (DestType->isRecordType()) {
2667 // FIXME: C++0x defines behavior for this
2668 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2669 }
2670
2671 // Add a general "list initialization" step.
2672 Sequence.AddListInitializationStep(DestType);
2673}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002674
2675/// \brief Try a reference initialization that involves calling a conversion
2676/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002677static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2678 const InitializedEntity &Entity,
2679 const InitializationKind &Kind,
2680 Expr *Initializer,
2681 bool AllowRValues,
2682 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002683 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002684 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2685 QualType T1 = cv1T1.getUnqualifiedType();
2686 QualType cv2T2 = Initializer->getType();
2687 QualType T2 = cv2T2.getUnqualifiedType();
2688
2689 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002690 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002691 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002692 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002693 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002694 ObjCConversion,
2695 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002696 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002697 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002698 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002699 (void)ObjCLifetimeConversion;
2700
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002701 // Build the candidate set directly in the initialization sequence
2702 // structure, so that it will persist if we fail.
2703 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2704 CandidateSet.clear();
2705
2706 // Determine whether we are allowed to call explicit constructors or
2707 // explicit conversion operators.
2708 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002710 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002711 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2712 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002713 // The type we're converting to is a class type. Enumerate its constructors
2714 // to see if there is a suitable conversion.
2715 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002716
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002717 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002718 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002719 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002720 NamedDecl *D = *Con;
2721 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2722
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002723 // Find the constructor (which may be a template).
2724 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002725 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 if (ConstructorTmpl)
2727 Constructor = cast<CXXConstructorDecl>(
2728 ConstructorTmpl->getTemplatedDecl());
2729 else
John McCalla0296f72010-03-19 07:35:19 +00002730 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002732 if (!Constructor->isInvalidDecl() &&
2733 Constructor->isConvertingConstructor(AllowExplicit)) {
2734 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002735 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002736 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002737 &Initializer, 1, CandidateSet,
2738 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002739 else
John McCalla0296f72010-03-19 07:35:19 +00002740 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002741 &Initializer, 1, CandidateSet,
2742 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002744 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002745 }
John McCall3696dcb2010-08-17 07:23:57 +00002746 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2747 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002748
Douglas Gregor496e8b342010-05-07 19:42:26 +00002749 const RecordType *T2RecordType = 0;
2750 if ((T2RecordType = T2->getAs<RecordType>()) &&
2751 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002752 // The type we're converting from is a class type, enumerate its conversion
2753 // functions.
2754 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2755
John McCallad371252010-01-20 00:46:10 +00002756 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002757 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002758 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2759 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002760 NamedDecl *D = *I;
2761 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2762 if (isa<UsingShadowDecl>(D))
2763 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002764
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002765 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2766 CXXConversionDecl *Conv;
2767 if (ConvTemplate)
2768 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2769 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002770 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002772 // If the conversion function doesn't return a reference type,
2773 // it can't be considered for this conversion unless we're allowed to
2774 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775 // FIXME: Do we need to make sure that we only consider conversion
2776 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002777 // break recursion.
2778 if ((AllowExplicit || !Conv->isExplicit()) &&
2779 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2780 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002781 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002782 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002783 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002784 else
John McCalla0296f72010-03-19 07:35:19 +00002785 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002786 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002787 }
2788 }
2789 }
John McCall3696dcb2010-08-17 07:23:57 +00002790 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2791 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002792
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002793 SourceLocation DeclLoc = Initializer->getLocStart();
2794
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002796 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002798 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002799 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002800
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002801 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002802
Chandler Carruth30141632011-02-25 19:41:05 +00002803 // This is the overload that will actually be used for the initialization, so
2804 // mark it as used.
2805 S.MarkDeclarationReferenced(DeclLoc, Function);
2806
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002807 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002808 if (isa<CXXConversionDecl>(Function))
2809 T2 = Function->getResultType();
2810 else
2811 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002812
2813 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002814 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002815 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002816
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002818 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002819 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002820 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002821 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002822 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002823 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002824
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002825 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002826 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002827 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002828 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002830 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002831 NewDerivedToBase, NewObjCConversion,
2832 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002833 if (NewRefRelationship == Sema::Ref_Incompatible) {
2834 // If the type we've converted to is not reference-related to the
2835 // type we're looking for, then there is another conversion step
2836 // we need to perform to produce a temporary of the right type
2837 // that we'll be binding to.
2838 ImplicitConversionSequence ICS;
2839 ICS.setStandard();
2840 ICS.Standard = Best->FinalConversion;
2841 T2 = ICS.Standard.getToType(2);
2842 Sequence.AddConversionSequenceStep(ICS, T2);
2843 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002844 Sequence.AddDerivedToBaseCastStep(
2845 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002846 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002847 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002848 else if (NewObjCConversion)
2849 Sequence.AddObjCObjectConversionStep(
2850 S.Context.getQualifiedType(T1,
2851 T2.getNonReferenceType().getQualifiers()));
2852
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002853 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002854 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002856 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2857 return OR_Success;
2858}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002859
2860/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2861static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002862 const InitializedEntity &Entity,
2863 const InitializationKind &Kind,
2864 Expr *Initializer,
2865 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002866 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002867 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002868 Qualifiers T1Quals;
2869 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002870 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002871 Qualifiers T2Quals;
2872 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002873 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002874
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002875 // If the initializer is the address of an overloaded function, try
2876 // to resolve the overloaded function. If all goes well, T2 is the
2877 // type of the resulting function.
2878 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002879 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002880 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002881 T1,
2882 false,
2883 Found)) {
2884 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2885 cv2T2 = Fn->getType();
2886 T2 = cv2T2.getUnqualifiedType();
2887 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002888 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2889 return;
2890 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002891 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002892
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002893 // Compute some basic properties of the types and the initializer.
2894 bool isLValueRef = DestType->isLValueReferenceType();
2895 bool isRValueRef = !isLValueRef;
2896 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002897 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002898 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002899 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002900 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002901 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002902 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002903
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002904 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002906 // "cv2 T2" as follows:
2907 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002909 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002910 // Note the analogous bullet points for rvlaue refs to functions. Because
2911 // there are no function rvalues in C++, rvalue refs to functions are treated
2912 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002913 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002914 bool T1Function = T1->isFunctionType();
2915 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002917 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002919 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002921 // reference-compatible with "cv2 T2," or
2922 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002924 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002925 // can occur. However, we do pay attention to whether it is a bit-field
2926 // to decide whether we're actually binding to a temporary created from
2927 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002928 if (DerivedToBase)
2929 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002931 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002932 else if (ObjCConversion)
2933 Sequence.AddObjCObjectConversionStep(
2934 S.Context.getQualifiedType(T1, T2Quals));
2935
Chandler Carruth04bdce62010-01-12 20:32:25 +00002936 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002937 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002938 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002939 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002940 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002941 return;
2942 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943
2944 // - has a class type (i.e., T2 is a class type), where T1 is not
2945 // reference-related to T2, and can be implicitly converted to an
2946 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2947 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002948 // applicable conversion functions (13.3.1.6) and choosing the best
2949 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002950 // If we have an rvalue ref to function type here, the rhs must be
2951 // an rvalue.
2952 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2953 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002954 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002955 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002956 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002957 Sequence);
2958 if (ConvOvlResult == OR_Success)
2959 return;
John McCall0d1da222010-01-12 00:44:57 +00002960 if (ConvOvlResult != OR_No_Viable_Function) {
2961 Sequence.SetOverloadFailure(
2962 InitializationSequence::FK_ReferenceInitOverloadFailed,
2963 ConvOvlResult);
2964 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002965 }
2966 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002967
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002968 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002969 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002970 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002971 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002972 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2973 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2974 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002975 Sequence.SetOverloadFailure(
2976 InitializationSequence::FK_ReferenceInitOverloadFailed,
2977 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002978 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002979 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002980 ? (RefRelationship == Sema::Ref_Related
2981 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2982 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2983 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002984
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002985 return;
2986 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002987
Douglas Gregor92e460e2011-01-20 16:44:54 +00002988 // - If the initializer expression
2989 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2990 // "cv1 T1" is reference-compatible with "cv2 T2"
2991 // Note: functions are handled below.
2992 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00002993 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002995 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00002996 (InitCategory.isXValue() ||
2997 (InitCategory.isPRValue() && T2->isRecordType()) ||
2998 (InitCategory.isPRValue() && T2->isArrayType()))) {
2999 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3000 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003001 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3002 // compiler the freedom to perform a copy here or bind to the
3003 // object, while C++0x requires that we bind directly to the
3004 // object. Hence, we always bind to the object without making an
3005 // extra copy. However, in C++03 requires that we check for the
3006 // presence of a suitable copy constructor:
3007 //
3008 // The constructor that would be used to make the copy shall
3009 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003010 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003011 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003013
Douglas Gregor92e460e2011-01-20 16:44:54 +00003014 if (DerivedToBase)
3015 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3016 ValueKind);
3017 else if (ObjCConversion)
3018 Sequence.AddObjCObjectConversionStep(
3019 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003020
Douglas Gregor92e460e2011-01-20 16:44:54 +00003021 if (T1Quals != T2Quals)
3022 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00003024 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003027
3028 // - has a class type (i.e., T2 is a class type), where T1 is not
3029 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003030 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3031 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003032 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003033 if (RefRelationship == Sema::Ref_Incompatible) {
3034 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3035 Kind, Initializer,
3036 /*AllowRValues=*/true,
3037 Sequence);
3038 if (ConvOvlResult)
3039 Sequence.SetOverloadFailure(
3040 InitializationSequence::FK_ReferenceInitOverloadFailed,
3041 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003042
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003043 return;
3044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003045
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003046 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3047 return;
3048 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003049
3050 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003051 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003053 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003054
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003055 // Determine whether we are allowed to call explicit constructors or
3056 // explicit conversion operators.
3057 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003058
3059 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3060
John McCall31168b02011-06-15 23:02:42 +00003061 ImplicitConversionSequence ICS
3062 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003063 /*SuppressUserConversions*/ false,
3064 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003065 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003066 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3067 /*AllowObjCWritebackConversion=*/false);
3068
3069 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003070 // FIXME: Use the conversion function set stored in ICS to turn
3071 // this into an overloading ambiguity diagnostic. However, we need
3072 // to keep that set as an OverloadCandidateSet rather than as some
3073 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003074 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3075 Sequence.SetOverloadFailure(
3076 InitializationSequence::FK_ReferenceInitOverloadFailed,
3077 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003078 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3079 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003080 else
3081 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003082 return;
John McCall31168b02011-06-15 23:02:42 +00003083 } else {
3084 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003085 }
3086
3087 // [...] If T1 is reference-related to T2, cv1 must be the
3088 // same cv-qualification as, or greater cv-qualification
3089 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003090 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3091 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003093 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003094 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3095 return;
3096 }
3097
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003099 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003101 InitCategory.isLValue()) {
3102 Sequence.SetFailed(
3103 InitializationSequence::FK_RValueReferenceBindingToLValue);
3104 return;
3105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003107 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3108 return;
3109}
3110
3111/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112/// (C++ [dcl.init.string], C99 6.7.8).
3113static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003114 const InitializedEntity &Entity,
3115 const InitializationKind &Kind,
3116 Expr *Initializer,
3117 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003118 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119}
3120
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003121/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3122/// enumerates the constructors of the initialized entity and performs overload
3123/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003125 const InitializedEntity &Entity,
3126 const InitializationKind &Kind,
3127 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003128 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003129 InitializationSequence &Sequence) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00003130 // Check constructor arguments for self reference.
3131 if (DeclaratorDecl *DD = Entity.getDecl())
3132 // Parameters arguments are occassionially constructed with itself,
3133 // for instance, in recursive functions. Skip them.
3134 if (!isa<ParmVarDecl>(DD))
3135 for (unsigned i = 0; i < NumArgs; ++i)
3136 S.CheckSelfReference(DD, Args[i]);
3137
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003138 // Build the candidate set directly in the initialization sequence
3139 // structure, so that it will persist if we fail.
3140 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3141 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003142
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003143 // Determine whether we are allowed to call explicit constructors or
3144 // explicit conversion operators.
3145 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3146 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003147 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003148
3149 // The type we're constructing needs to be complete.
3150 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003151 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003152 return;
3153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003155 // The type we're converting to is a class type. Enumerate its constructors
3156 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003157 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003159 CXXRecordDecl *DestRecordDecl
3160 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003162 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003163 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003164 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003165 NamedDecl *D = *Con;
3166 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003167 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003168
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003169 // Find the constructor (which may be a template).
3170 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003171 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003172 if (ConstructorTmpl)
3173 Constructor = cast<CXXConstructorDecl>(
3174 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003175 else {
John McCalla0296f72010-03-19 07:35:19 +00003176 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003177
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003179 // suppress user-defined conversions on the arguments.
3180 // FIXME: Move constructors?
3181 if (Kind.getKind() == InitializationKind::IK_Copy &&
3182 Constructor->isCopyConstructor())
3183 SuppressUserConversions = true;
3184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003186 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003187 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003188 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003189 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003190 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003191 Args, NumArgs, CandidateSet,
3192 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003193 else
John McCalla0296f72010-03-19 07:35:19 +00003194 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003195 Args, NumArgs, CandidateSet,
3196 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198 }
3199
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003200 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003201
3202 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003203 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003205 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003206 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003208 Result);
3209 return;
3210 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003211
3212 // C++0x [dcl.init]p6:
3213 // If a program calls for the default initialization of an object
3214 // of a const-qualified type T, T shall be a class type with a
3215 // user-provided default constructor.
3216 if (Kind.getKind() == InitializationKind::IK_Default &&
3217 Entity.getType().isConstQualified() &&
3218 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3219 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3220 return;
3221 }
3222
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003223 // Add the constructor initialization step. Any cv-qualification conversion is
3224 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003225 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003227 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003228 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003229}
3230
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003231/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003233 const InitializedEntity &Entity,
3234 const InitializationKind &Kind,
3235 InitializationSequence &Sequence) {
3236 // C++ [dcl.init]p5:
3237 //
3238 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003239 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003241 // -- if T is an array type, then each element is value-initialized;
3242 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3243 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003245 if (const RecordType *RT = T->getAs<RecordType>()) {
3246 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3247 // -- if T is a class type (clause 9) with a user-declared
3248 // constructor (12.1), then the default constructor for T is
3249 // called (and the initialization is ill-formed if T has no
3250 // accessible default constructor);
3251 //
3252 // FIXME: we really want to refer to a single subobject of the array,
3253 // but Entity doesn't have a way to capture that (yet).
3254 if (ClassDecl->hasUserDeclaredConstructor())
3255 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003257 // -- if T is a (possibly cv-qualified) non-union class type
3258 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003259 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003260 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003261 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003262 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003263 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003265 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003266 }
3267 }
3268
Douglas Gregor1b303932009-12-22 15:35:07 +00003269 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003270}
3271
Douglas Gregor85dabae2009-12-16 01:38:02 +00003272/// \brief Attempt default initialization (C++ [dcl.init]p6).
3273static void TryDefaultInitialization(Sema &S,
3274 const InitializedEntity &Entity,
3275 const InitializationKind &Kind,
3276 InitializationSequence &Sequence) {
3277 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003278
Douglas Gregor85dabae2009-12-16 01:38:02 +00003279 // C++ [dcl.init]p6:
3280 // To default-initialize an object of type T means:
3281 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003282 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3283
Douglas Gregor85dabae2009-12-16 01:38:02 +00003284 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3285 // constructor for T is called (and the initialization is ill-formed if
3286 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003287 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003288 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3289 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291
Douglas Gregor85dabae2009-12-16 01:38:02 +00003292 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293
Douglas Gregor85dabae2009-12-16 01:38:02 +00003294 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003295 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003296 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003297 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003298 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003299 return;
3300 }
3301
3302 // If the destination type has a lifetime property, zero-initialize it.
3303 if (DestType.getQualifiers().hasObjCLifetime()) {
3304 Sequence.AddZeroInitializationStep(Entity.getType());
3305 return;
3306 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003307}
3308
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003309/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3310/// which enumerates all conversion functions and performs overload resolution
3311/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003313 const InitializedEntity &Entity,
3314 const InitializationKind &Kind,
3315 Expr *Initializer,
3316 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003317 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003318 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3319 QualType SourceType = Initializer->getType();
3320 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3321 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322
Douglas Gregor540c3b02009-12-14 17:27:33 +00003323 // Build the candidate set directly in the initialization sequence
3324 // structure, so that it will persist if we fail.
3325 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3326 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003327
Douglas Gregor540c3b02009-12-14 17:27:33 +00003328 // Determine whether we are allowed to call explicit constructors or
3329 // explicit conversion operators.
3330 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331
Douglas Gregor540c3b02009-12-14 17:27:33 +00003332 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3333 // The type we're converting to is a class type. Enumerate its constructors
3334 // to see if there is a suitable conversion.
3335 CXXRecordDecl *DestRecordDecl
3336 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003337
Douglas Gregord9848152010-04-26 14:36:57 +00003338 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003340 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003341 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003342 Con != ConEnd; ++Con) {
3343 NamedDecl *D = *Con;
3344 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
Douglas Gregord9848152010-04-26 14:36:57 +00003346 // Find the constructor (which may be a template).
3347 CXXConstructorDecl *Constructor = 0;
3348 FunctionTemplateDecl *ConstructorTmpl
3349 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003350 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003351 Constructor = cast<CXXConstructorDecl>(
3352 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003353 else
Douglas Gregord9848152010-04-26 14:36:57 +00003354 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
Douglas Gregord9848152010-04-26 14:36:57 +00003356 if (!Constructor->isInvalidDecl() &&
3357 Constructor->isConvertingConstructor(AllowExplicit)) {
3358 if (ConstructorTmpl)
3359 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3360 /*ExplicitArgs*/ 0,
3361 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003362 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003363 else
3364 S.AddOverloadCandidate(Constructor, FoundDecl,
3365 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003366 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 }
Douglas Gregord9848152010-04-26 14:36:57 +00003369 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003370 }
Eli Friedman78275202009-12-19 08:11:05 +00003371
3372 SourceLocation DeclLoc = Initializer->getLocStart();
3373
Douglas Gregor540c3b02009-12-14 17:27:33 +00003374 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3375 // The type we're converting from is a class type, enumerate its conversion
3376 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003377
Eli Friedman4afe9a32009-12-20 22:12:03 +00003378 // We can only enumerate the conversion functions for a complete type; if
3379 // the type isn't complete, simply skip this step.
3380 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3381 CXXRecordDecl *SourceRecordDecl
3382 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383
John McCallad371252010-01-20 00:46:10 +00003384 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003385 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003386 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003388 I != E; ++I) {
3389 NamedDecl *D = *I;
3390 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3391 if (isa<UsingShadowDecl>(D))
3392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393
Eli Friedman4afe9a32009-12-20 22:12:03 +00003394 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3395 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003396 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003398 else
John McCallda4458e2010-03-31 01:36:47 +00003399 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
Eli Friedman4afe9a32009-12-20 22:12:03 +00003401 if (AllowExplicit || !Conv->isExplicit()) {
3402 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003404 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003405 CandidateSet);
3406 else
John McCalla0296f72010-03-19 07:35:19 +00003407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003408 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003409 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003410 }
3411 }
3412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
3414 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003415 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003416 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003417 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003418 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003420 Result);
3421 return;
3422 }
John McCall0d1da222010-01-12 00:44:57 +00003423
Douglas Gregor540c3b02009-12-14 17:27:33 +00003424 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003425 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Douglas Gregor540c3b02009-12-14 17:27:33 +00003427 if (isa<CXXConstructorDecl>(Function)) {
3428 // Add the user-defined conversion step. Any cv-qualification conversion is
3429 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003430 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003431 return;
3432 }
3433
3434 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003435 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003436 if (ConvType->getAs<RecordType>()) {
3437 // If we're converting to a class type, there may be an copy if
3438 // the resulting temporary object (possible to create an object of
3439 // a base class type). That copy is not a separate conversion, so
3440 // we just make a note of the actual destination type (possibly a
3441 // base class of the type returned by the conversion function) and
3442 // let the user-defined conversion step handle the conversion.
3443 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3444 return;
3445 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003446
Douglas Gregor5ab11652010-04-17 22:01:05 +00003447 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448
Douglas Gregor5ab11652010-04-17 22:01:05 +00003449 // If the conversion following the call to the conversion function
3450 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003451 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3452 Best->FinalConversion.Third) {
3453 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003454 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003455 ICS.Standard = Best->FinalConversion;
3456 Sequence.AddConversionSequenceStep(ICS, DestType);
3457 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003458}
3459
John McCall31168b02011-06-15 23:02:42 +00003460/// The non-zero enum values here are indexes into diagnostic alternatives.
3461enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3462
3463/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003464static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3465 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003466 // Skip parens.
3467 e = e->IgnoreParens();
3468
3469 // Skip address-of nodes.
3470 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3471 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003472 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003473
3474 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003475 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3476 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003477 case CK_Dependent:
3478 case CK_BitCast:
3479 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003480 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003481 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003482
3483 case CK_ArrayToPointerDecay:
3484 return IIK_nonscalar;
3485
3486 case CK_NullToPointer:
3487 return IIK_okay;
3488
3489 default:
3490 break;
3491 }
3492
3493 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003494 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3495 if (!isAddressOf) return IIK_nonlocal;
3496
3497 VarDecl *var;
3498 if (isa<DeclRefExpr>(e)) {
3499 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3500 if (!var) return IIK_nonlocal;
3501 } else {
3502 var = cast<BlockDeclRefExpr>(e)->getDecl();
3503 }
3504
3505 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003506
3507 // If we have a conditional operator, check both sides.
3508 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003509 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003510 return iik;
3511
John McCall63f84442011-06-27 23:59:58 +00003512 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003513
3514 // These are never scalar.
3515 } else if (isa<ArraySubscriptExpr>(e)) {
3516 return IIK_nonscalar;
3517
3518 // Otherwise, it needs to be a null pointer constant.
3519 } else {
3520 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3521 ? IIK_okay : IIK_nonlocal);
3522 }
3523
3524 return IIK_nonlocal;
3525}
3526
3527/// Check whether the given expression is a valid operand for an
3528/// indirect copy/restore.
3529static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3530 assert(src->isRValue());
3531
John McCall63f84442011-06-27 23:59:58 +00003532 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003533 if (iik == IIK_okay) return;
3534
3535 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3536 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3537 << src->getSourceRange();
3538}
3539
Douglas Gregore2f943b2011-02-22 18:29:51 +00003540/// \brief Determine whether we have compatible array types for the
3541/// purposes of GNU by-copy array initialization.
3542static bool hasCompatibleArrayTypes(ASTContext &Context,
3543 const ArrayType *Dest,
3544 const ArrayType *Source) {
3545 // If the source and destination array types are equivalent, we're
3546 // done.
3547 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3548 return true;
3549
3550 // Make sure that the element types are the same.
3551 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3552 return false;
3553
3554 // The only mismatch we allow is when the destination is an
3555 // incomplete array type and the source is a constant array type.
3556 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3557}
3558
John McCall31168b02011-06-15 23:02:42 +00003559static bool tryObjCWritebackConversion(Sema &S,
3560 InitializationSequence &Sequence,
3561 const InitializedEntity &Entity,
3562 Expr *Initializer) {
3563 bool ArrayDecay = false;
3564 QualType ArgType = Initializer->getType();
3565 QualType ArgPointee;
3566 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3567 ArrayDecay = true;
3568 ArgPointee = ArgArrayType->getElementType();
3569 ArgType = S.Context.getPointerType(ArgPointee);
3570 }
3571
3572 // Handle write-back conversion.
3573 QualType ConvertedArgType;
3574 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3575 ConvertedArgType))
3576 return false;
3577
3578 // We should copy unless we're passing to an argument explicitly
3579 // marked 'out'.
3580 bool ShouldCopy = true;
3581 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3582 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3583
3584 // Do we need an lvalue conversion?
3585 if (ArrayDecay || Initializer->isGLValue()) {
3586 ImplicitConversionSequence ICS;
3587 ICS.setStandard();
3588 ICS.Standard.setAsIdentityConversion();
3589
3590 QualType ResultType;
3591 if (ArrayDecay) {
3592 ICS.Standard.First = ICK_Array_To_Pointer;
3593 ResultType = S.Context.getPointerType(ArgPointee);
3594 } else {
3595 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3596 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3597 }
3598
3599 Sequence.AddConversionSequenceStep(ICS, ResultType);
3600 }
3601
3602 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3603 return true;
3604}
3605
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003606InitializationSequence::InitializationSequence(Sema &S,
3607 const InitializedEntity &Entity,
3608 const InitializationKind &Kind,
3609 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003610 unsigned NumArgs)
3611 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003612 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615 // The semantics of initializers are as follows. The destination type is
3616 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003619 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003620 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003622 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3624 SequenceKind = DependentSequence;
3625 return;
3626 }
3627
Sebastian Redld201edf2011-06-05 13:59:11 +00003628 // Almost everything is a normal sequence.
3629 setSequenceKind(NormalSequence);
3630
John McCalled75c092010-12-07 22:54:16 +00003631 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003632 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3633 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3634 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003635 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003636 return;
3637 }
3638 Args[I] = Result.take();
3639 }
John McCalled75c092010-12-07 22:54:16 +00003640
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003641 QualType SourceType;
3642 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003643 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003644 Initializer = Args[0];
3645 if (!isa<InitListExpr>(Initializer))
3646 SourceType = Initializer->getType();
3647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003648
3649 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650 // list-initialized (8.5.4).
3651 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003652 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003653 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003655
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003656 // - If the destination type is a reference type, see 8.5.3.
3657 if (DestType->isReferenceType()) {
3658 // C++0x [dcl.init.ref]p1:
3659 // A variable declared to be a T& or T&&, that is, "reference to type T"
3660 // (8.3.2), shall be initialized by an object, or function, of type T or
3661 // by an object that can be converted into a T.
3662 // (Therefore, multiple arguments are not permitted.)
3663 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003664 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003665 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003666 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003667 return;
3668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003669
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003670 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003671 if (Kind.getKind() == InitializationKind::IK_Value ||
3672 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003673 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003674 return;
3675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676
Douglas Gregor85dabae2009-12-16 01:38:02 +00003677 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003678 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003679 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003680 return;
3681 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003682
John McCall66884dd2011-02-21 07:22:22 +00003683 // - If the destination type is an array of characters, an array of
3684 // char16_t, an array of char32_t, or an array of wchar_t, and the
3685 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003687 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003688 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3689 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003690 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003691 return;
3692 }
3693
Douglas Gregore2f943b2011-02-22 18:29:51 +00003694 // Note: as an GNU C extension, we allow initialization of an
3695 // array from a compound literal that creates an array of the same
3696 // type, so long as the initializer has no side effects.
3697 if (!S.getLangOptions().CPlusPlus && Initializer &&
3698 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3699 Initializer->getType()->isArrayType()) {
3700 const ArrayType *SourceAT
3701 = Context.getAsArrayType(Initializer->getType());
3702 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003703 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003704 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003705 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003706 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003707 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003708 }
3709 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003710 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003711 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003712 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003714 return;
3715 }
Eli Friedman78275202009-12-19 08:11:05 +00003716
John McCall31168b02011-06-15 23:02:42 +00003717 // Determine whether we should consider writeback conversions for
3718 // Objective-C ARC.
3719 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3720 Entity.getKind() == InitializedEntity::EK_Parameter;
3721
3722 // We're at the end of the line for C: it's either a write-back conversion
3723 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003724 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003725 // If allowed, check whether this is an Objective-C writeback conversion.
3726 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003727 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003728 return;
3729 }
3730
3731 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003732 AddCAssignmentStep(DestType);
3733 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003734 return;
3735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
John McCall31168b02011-06-15 23:02:42 +00003737 assert(S.getLangOptions().CPlusPlus);
3738
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003739 // - If the destination type is a (possibly cv-qualified) class type:
3740 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741 // - If the initialization is direct-initialization, or if it is
3742 // copy-initialization where the cv-unqualified version of the
3743 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003744 // class of the destination, constructors are considered. [...]
3745 if (Kind.getKind() == InitializationKind::IK_Direct ||
3746 (Kind.getKind() == InitializationKind::IK_Copy &&
3747 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3748 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003750 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003752 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003753 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003754 // used) to a derived class thereof are enumerated as described in
3755 // 13.3.1.4, and the best one is chosen through overload resolution
3756 // (13.3).
3757 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003758 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 return;
3760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761
Douglas Gregor85dabae2009-12-16 01:38:02 +00003762 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003763 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003764 return;
3765 }
3766 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
3768 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003769 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003770 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003771 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3772 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003773 return;
3774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003775
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003776 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003777 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003780 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003781
3782 ImplicitConversionSequence ICS
3783 = S.TryImplicitConversion(Initializer, Entity.getType(),
3784 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003785 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003786 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003787 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3788 allowObjCWritebackConversion);
3789
3790 if (ICS.isStandard() &&
3791 ICS.Standard.Second == ICK_Writeback_Conversion) {
3792 // Objective-C ARC writeback conversion.
3793
3794 // We should copy unless we're passing to an argument explicitly
3795 // marked 'out'.
3796 bool ShouldCopy = true;
3797 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3798 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3799
3800 // If there was an lvalue adjustment, add it as a separate conversion.
3801 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3802 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3803 ImplicitConversionSequence LvalueICS;
3804 LvalueICS.setStandard();
3805 LvalueICS.Standard.setAsIdentityConversion();
3806 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3807 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003808 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003809 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003810
3811 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003812 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003813 DeclAccessPair dap;
3814 if (Initializer->getType() == Context.OverloadTy &&
3815 !S.ResolveAddressOfOverloadedFunction(Initializer
3816 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003817 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003818 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003819 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003820 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003821 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003822
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003823 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003824 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003825}
3826
3827InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003828 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003829 StepEnd = Steps.end();
3830 Step != StepEnd; ++Step)
3831 Step->Destroy();
3832}
3833
3834//===----------------------------------------------------------------------===//
3835// Perform initialization
3836//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003838getAssignmentAction(const InitializedEntity &Entity) {
3839 switch(Entity.getKind()) {
3840 case InitializedEntity::EK_Variable:
3841 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003842 case InitializedEntity::EK_Exception:
3843 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003844 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003845 return Sema::AA_Initializing;
3846
3847 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003848 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003849 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3850 return Sema::AA_Sending;
3851
Douglas Gregore1314a62009-12-18 05:02:21 +00003852 return Sema::AA_Passing;
3853
3854 case InitializedEntity::EK_Result:
3855 return Sema::AA_Returning;
3856
Douglas Gregore1314a62009-12-18 05:02:21 +00003857 case InitializedEntity::EK_Temporary:
3858 // FIXME: Can we tell apart casting vs. converting?
3859 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003860
Douglas Gregore1314a62009-12-18 05:02:21 +00003861 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003862 case InitializedEntity::EK_ArrayElement:
3863 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003864 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003865 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003866 return Sema::AA_Initializing;
3867 }
3868
3869 return Sema::AA_Converting;
3870}
3871
Douglas Gregor95562572010-04-24 23:45:46 +00003872/// \brief Whether we should binding a created object as a temporary when
3873/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003874static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003875 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003876 case InitializedEntity::EK_ArrayElement:
3877 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003878 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003879 case InitializedEntity::EK_New:
3880 case InitializedEntity::EK_Variable:
3881 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003882 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003883 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003884 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003885 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003886 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003887 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003888
Douglas Gregore1314a62009-12-18 05:02:21 +00003889 case InitializedEntity::EK_Parameter:
3890 case InitializedEntity::EK_Temporary:
3891 return true;
3892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Douglas Gregore1314a62009-12-18 05:02:21 +00003894 llvm_unreachable("missed an InitializedEntity kind?");
3895}
3896
Douglas Gregor95562572010-04-24 23:45:46 +00003897/// \brief Whether the given entity, when initialized with an object
3898/// created for that initialization, requires destruction.
3899static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3900 switch (Entity.getKind()) {
3901 case InitializedEntity::EK_Member:
3902 case InitializedEntity::EK_Result:
3903 case InitializedEntity::EK_New:
3904 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003905 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003906 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003907 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003908 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003909 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
Douglas Gregor95562572010-04-24 23:45:46 +00003911 case InitializedEntity::EK_Variable:
3912 case InitializedEntity::EK_Parameter:
3913 case InitializedEntity::EK_Temporary:
3914 case InitializedEntity::EK_ArrayElement:
3915 case InitializedEntity::EK_Exception:
3916 return true;
3917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
3919 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003920}
3921
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003922/// \brief Make a (potentially elidable) temporary copy of the object
3923/// provided by the given initializer by calling the appropriate copy
3924/// constructor.
3925///
3926/// \param S The Sema object used for type-checking.
3927///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003928/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003929/// the type of the initializer expression or a superclass thereof.
3930///
3931/// \param Enter The entity being initialized.
3932///
3933/// \param CurInit The initializer expression.
3934///
3935/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3936/// is permitted in C++03 (but not C++0x) when binding a reference to
3937/// an rvalue.
3938///
3939/// \returns An expression that copies the initializer expression into
3940/// a temporary object, or an error expression if a copy could not be
3941/// created.
John McCalldadc5752010-08-24 06:29:42 +00003942static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003943 QualType T,
3944 const InitializedEntity &Entity,
3945 ExprResult CurInit,
3946 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003947 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003948 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003950 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003951 Class = cast<CXXRecordDecl>(Record->getDecl());
3952 if (!Class)
3953 return move(CurInit);
3954
Douglas Gregor5d369002011-01-21 18:05:27 +00003955 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003956 // When certain criteria are met, an implementation is allowed to
3957 // omit the copy/move construction of a class object, even if the
3958 // copy/move constructor and/or destructor for the object have
3959 // side effects. [...]
3960 // - when a temporary class object that has not been bound to a
3961 // reference (12.2) would be copied/moved to a class object
3962 // with the same cv-unqualified type, the copy/move operation
3963 // can be omitted by constructing the temporary object
3964 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003966 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003967 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003969 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003970 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003971 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003972 switch (Entity.getKind()) {
3973 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003974 Loc = Entity.getReturnLoc();
3975 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976
Douglas Gregore1314a62009-12-18 05:02:21 +00003977 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003978 Loc = Entity.getThrowLoc();
3979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003980
Douglas Gregore1314a62009-12-18 05:02:21 +00003981 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003982 Loc = Entity.getDecl()->getLocation();
3983 break;
3984
Anders Carlsson0bd52402010-01-24 00:19:41 +00003985 case InitializedEntity::EK_ArrayElement:
3986 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003987 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003988 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003989 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003990 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003991 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003992 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003993 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003994 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003995 Loc = CurInitExpr->getLocStart();
3996 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00003997 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00003998
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003999 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004000 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4001 return move(CurInit);
4002
Douglas Gregorf282a762011-01-21 19:38:21 +00004003 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00004004 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00004005 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00004006 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004007 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004008 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00004009 // C++0x [dcl.init]p16, second bullet to class types, this
4010 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004011 CXXConstructorDecl *Constructor = 0;
4012
4013 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004014 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004015 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00004016 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00004017 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004018 continue;
4019
4020 DeclAccessPair FoundDecl
4021 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4022 S.AddOverloadCandidate(Constructor, FoundDecl,
4023 &CurInitExpr, 1, CandidateSet);
4024 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004026
4027 // Handle constructor templates.
4028 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4029 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00004030 continue;
John McCalla0296f72010-03-19 07:35:19 +00004031
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004032 Constructor = cast<CXXConstructorDecl>(
4033 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00004034 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004035 continue;
4036
4037 // FIXME: Do we need to limit this to copy-constructor-like
4038 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00004039 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004040 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4041 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4042 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004044
Douglas Gregore1314a62009-12-18 05:02:21 +00004045 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004046 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004047 case OR_Success:
4048 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049
Douglas Gregore1314a62009-12-18 05:02:21 +00004050 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004051 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4052 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4053 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004054 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004055 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004056 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004057 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004058 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004059 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060
Douglas Gregore1314a62009-12-18 05:02:21 +00004061 case OR_Ambiguous:
4062 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004063 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004064 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004065 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004066 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Douglas Gregore1314a62009-12-18 05:02:21 +00004068 case OR_Deleted:
4069 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004070 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004071 << CurInitExpr->getSourceRange();
4072 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004073 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004074 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004075 }
4076
Douglas Gregor5ab11652010-04-17 22:01:05 +00004077 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004078 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004079 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004080
Anders Carlssona01874b2010-04-21 18:47:17 +00004081 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004082 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004083
4084 if (IsExtraneousCopy) {
4085 // If this is a totally extraneous copy for C++03 reference
4086 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004087 // expression. We don't generate an (elided) copy operation here
4088 // because doing so would require us to pass down a flag to avoid
4089 // infinite recursion, where each step adds another extraneous,
4090 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004091
Douglas Gregor30b52772010-04-18 07:57:34 +00004092 // Instantiate the default arguments of any extra parameters in
4093 // the selected copy constructor, as if we were going to create a
4094 // proper call to the copy constructor.
4095 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4096 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4097 if (S.RequireCompleteType(Loc, Parm->getType(),
4098 S.PDiag(diag::err_call_incomplete_argument)))
4099 break;
4100
4101 // Build the default argument expression; we don't actually care
4102 // if this succeeds or not, because this routine will complain
4103 // if there was a problem.
4104 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4105 }
4106
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004107 return S.Owned(CurInitExpr);
4108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109
Chandler Carruth30141632011-02-25 19:41:05 +00004110 S.MarkDeclarationReferenced(Loc, Constructor);
4111
Douglas Gregor5ab11652010-04-17 22:01:05 +00004112 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004113 // constructor call (we might have derived-to-base conversions, or
4114 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004115 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004116 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004117 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004118
Douglas Gregord0ace022010-04-25 00:55:24 +00004119 // Actually perform the constructor call.
4120 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004121 move_arg(ConstructorArgs),
4122 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004123 CXXConstructExpr::CK_Complete,
4124 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004125
Douglas Gregord0ace022010-04-25 00:55:24 +00004126 // If we're supposed to bind temporaries, do so.
4127 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4128 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4129 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004130}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004131
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004132void InitializationSequence::PrintInitLocationNote(Sema &S,
4133 const InitializedEntity &Entity) {
4134 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4135 if (Entity.getDecl()->getLocation().isInvalid())
4136 return;
4137
4138 if (Entity.getDecl()->getDeclName())
4139 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4140 << Entity.getDecl()->getDeclName();
4141 else
4142 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4143 }
4144}
4145
Sebastian Redl112aa822011-07-14 19:07:55 +00004146static bool isReferenceBinding(const InitializationSequence::Step &s) {
4147 return s.Kind == InitializationSequence::SK_BindReference ||
4148 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4149}
4150
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152InitializationSequence::Perform(Sema &S,
4153 const InitializedEntity &Entity,
4154 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004155 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004156 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004157 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004158 unsigned NumArgs = Args.size();
4159 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004160 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162
Sebastian Redld201edf2011-06-05 13:59:11 +00004163 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004164 // If the declaration is a non-dependent, incomplete array type
4165 // that has an initializer, then its type will be completed once
4166 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004167 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004168 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004169 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004170 if (const IncompleteArrayType *ArrayT
4171 = S.Context.getAsIncompleteArrayType(DeclType)) {
4172 // FIXME: We don't currently have the ability to accurately
4173 // compute the length of an initializer list without
4174 // performing full type-checking of the initializer list
4175 // (since we have to determine where braces are implicitly
4176 // introduced and such). So, we fall back to making the array
4177 // type a dependently-sized array type with no specified
4178 // bound.
4179 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4180 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004181
Douglas Gregor51e77d52009-12-10 17:56:55 +00004182 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004183 if (DeclaratorDecl *DD = Entity.getDecl()) {
4184 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4185 TypeLoc TL = TInfo->getTypeLoc();
4186 if (IncompleteArrayTypeLoc *ArrayLoc
4187 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4188 Brackets = ArrayLoc->getBracketsRange();
4189 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004190 }
4191
4192 *ResultType
4193 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4194 /*NumElts=*/0,
4195 ArrayT->getSizeModifier(),
4196 ArrayT->getIndexTypeCVRQualifiers(),
4197 Brackets);
4198 }
4199
4200 }
4201 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004202 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4203 Kind.isExplicitCast());
4204 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004205 }
4206
Sebastian Redld201edf2011-06-05 13:59:11 +00004207 // No steps means no initialization.
4208 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004209 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Douglas Gregor1b303932009-12-22 15:35:07 +00004211 QualType DestType = Entity.getType().getNonReferenceType();
4212 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004213 // the same as Entity.getDecl()->getType() in cases involving type merging,
4214 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004215 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004216 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004217 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004218
John McCalldadc5752010-08-24 06:29:42 +00004219 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004222 // grab the only argument out the Args and place it into the "current"
4223 // initializer.
4224 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004225 case SK_ResolveAddressOfOverloadedFunction:
4226 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004227 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004228 case SK_CastDerivedToBaseLValue:
4229 case SK_BindReference:
4230 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004231 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004232 case SK_UserConversion:
4233 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004234 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004235 case SK_QualificationConversionRValue:
4236 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004237 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004238 case SK_ListInitialization:
4239 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004240 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004241 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004242 case SK_ArrayInit:
4243 case SK_PassByIndirectCopyRestore:
4244 case SK_PassByIndirectRestore:
4245 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004246 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004247 CurInit = Args.get()[0];
4248 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004249
4250 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004251 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4252 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4253 if (CurInit.isInvalid())
4254 return ExprError();
4255 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004256 break;
John McCall34376a62010-12-04 03:47:34 +00004257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004258
Douglas Gregore1314a62009-12-18 05:02:21 +00004259 case SK_ConstructorInitialization:
4260 case SK_ZeroInitialization:
4261 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
4264 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004265 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004266 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004267 for (step_iterator Step = step_begin(), StepEnd = step_end();
4268 Step != StepEnd; ++Step) {
4269 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004270 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
John Wiegley01296292011-04-08 18:41:53 +00004272 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004274 switch (Step->Kind) {
4275 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004277 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004278 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004279 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004280 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004281 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004282 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004283 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004286 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004287 case SK_CastDerivedToBaseLValue: {
4288 // We have a derived-to-base cast that produces either an rvalue or an
4289 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
John McCallcf142162010-08-07 06:22:56 +00004291 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004292
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 // Casts to inaccessible base classes are allowed with C-style casts.
4294 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4295 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004296 CurInit.get()->getLocStart(),
4297 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004298 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004299 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300
Douglas Gregor88d292c2010-05-13 16:44:06 +00004301 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4302 QualType T = SourceType;
4303 if (const PointerType *Pointer = T->getAs<PointerType>())
4304 T = Pointer->getPointeeType();
4305 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004306 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004307 cast<CXXRecordDecl>(RecordTy->getDecl()));
4308 }
4309
John McCall2536c6d2010-08-25 10:28:54 +00004310 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004311 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004312 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004313 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004314 VK_XValue :
4315 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004316 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4317 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004318 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004319 CurInit.get(),
4320 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004321 break;
4322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004324 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004325 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004326 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4327 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004328 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004329 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004330 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004331 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004332 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004333 }
Anders Carlssona91be642010-01-29 02:47:33 +00004334
John Wiegley01296292011-04-08 18:41:53 +00004335 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004336 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004337 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4338 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004339 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004340 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004341 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004342 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004344 // Reference binding does not have any corresponding ASTs.
4345
4346 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004347 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004348 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004349
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004350 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004351
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004352 case SK_BindReferenceToTemporary:
4353 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004354 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004355 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004356
Douglas Gregorfe314812011-06-21 17:03:29 +00004357 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004358 CurInit = new (S.Context) MaterializeTemporaryExpr(
4359 Entity.getType().getNonReferenceType(),
4360 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004361 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004362
4363 // If we're binding to an Objective-C object that has lifetime, we
4364 // need cleanups.
4365 if (S.getLangOptions().ObjCAutoRefCount &&
4366 CurInit.get()->getType()->isObjCLifetimeType())
4367 S.ExprNeedsCleanups = true;
4368
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004369 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004371 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004373 /*IsExtraneousCopy=*/true);
4374 break;
4375
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004376 case SK_UserConversion: {
4377 // We have a user-defined conversion that invokes either a constructor
4378 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004379 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004380 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004381 FunctionDecl *Fn = Step->Function.Function;
4382 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004383 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004384 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004385 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004386 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004387 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004388 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004389 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004390
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391 // Determine the arguments required to actually perform the constructor
4392 // call.
John Wiegley01296292011-04-08 18:41:53 +00004393 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004394 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004395 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004396 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004397 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004399 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004401 move_arg(ConstructorArgs),
4402 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004403 CXXConstructExpr::CK_Complete,
4404 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004405 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004406 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004407
Anders Carlssona01874b2010-04-21 18:47:17 +00004408 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004409 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004410 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
John McCalle3027922010-08-25 11:45:40 +00004412 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004413 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4414 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4415 S.IsDerivedFrom(SourceType, Class))
4416 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregor95562572010-04-24 23:45:46 +00004418 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004419 } else {
4420 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004421 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004422 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004423 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004424 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004425 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
4427 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004428 // derived-to-base conversion? I believe the answer is "no", because
4429 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004430 ExprResult CurInitExprRes =
4431 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4432 FoundFn, Conversion);
4433 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004434 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004435 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004437 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004438 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004439 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004440 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441
John McCalle3027922010-08-25 11:45:40 +00004442 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Douglas Gregor95562572010-04-24 23:45:46 +00004444 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Sebastian Redl112aa822011-07-14 19:07:55 +00004447 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004448 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004449 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004450 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004451 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004452 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004454 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004455 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004456 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004457 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4458 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004459 }
4460 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004462 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004463 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004464 CurInit.get()->getType(),
4465 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004466 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004468 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004469 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4470 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004471
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004472 break;
4473 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004474
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004475 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004476 case SK_QualificationConversionXValue:
4477 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004478 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004479 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004480 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004481 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004482 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004483 VK_XValue :
4484 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004485 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004486 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004487 }
4488
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004489 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004490 Sema::CheckedConversionKind CCK
4491 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4492 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4493 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4494 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004495 ExprResult CurInitExprRes =
4496 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004497 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004498 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004499 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004500 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004501 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor51e77d52009-12-10 17:56:55 +00004504 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004505 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004506 QualType Ty = Step->Type;
Sebastian Redla846cac2011-09-24 17:47:46 +00004507 InitListChecker CheckInitList(S, Entity, InitList,
4508 ResultType ? *ResultType : Ty);
4509 if (CheckInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004510 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004511
4512 CurInit.release();
Sebastian Redla846cac2011-09-24 17:47:46 +00004513 CurInit = S.Owned(CheckInitList.getFullyStructuredList());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004514 break;
4515 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004516
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004517 case SK_ListConstructorCall:
4518 assert(false && "List constructor calls not yet supported.");
4519
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004520 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004521 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004522 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004523 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004525 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004526 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004527 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4528 ? Kind.getEqualLoc()
4529 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004530
4531 if (Kind.getKind() == InitializationKind::IK_Default) {
4532 // Force even a trivial, implicit default constructor to be
4533 // semantically checked. We do this explicitly because we don't build
4534 // the definition for completely trivial constructors.
4535 CXXRecordDecl *ClassDecl = Constructor->getParent();
4536 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004537 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004538 ClassDecl->hasTrivialDefaultConstructor() &&
4539 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004540 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4541 }
4542
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004543 // Determine the arguments required to actually perform the constructor
4544 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004546 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004547 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548
4549
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004550 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004551 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004552 (Kind.getKind() == InitializationKind::IK_Direct ||
4553 Kind.getKind() == InitializationKind::IK_Value)) {
4554 // An explicitly-constructed temporary, e.g., X(1, 2).
4555 unsigned NumExprs = ConstructorArgs.size();
4556 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004557 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004558 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Douglas Gregor2b88c112010-09-08 00:15:04 +00004560 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4561 if (!TSInfo)
4562 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004564 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4565 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004566 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004568 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004569 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004570 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004571 } else {
4572 CXXConstructExpr::ConstructionKind ConstructKind =
4573 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004575 if (Entity.getKind() == InitializedEntity::EK_Base) {
4576 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004578 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004579 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004580 ConstructKind = CXXConstructExpr::CK_Delegating;
4581 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004582
Chandler Carruth01718152010-10-25 08:47:36 +00004583 // Only get the parenthesis range if it is a direct construction.
4584 SourceRange parenRange =
4585 Kind.getKind() == InitializationKind::IK_Direct ?
4586 Kind.getParenRange() : SourceRange();
4587
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004588 // If the entity allows NRVO, mark the construction as elidable
4589 // unconditionally.
4590 if (Entity.allowsNRVO())
4591 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4592 Constructor, /*Elidable=*/true,
4593 move_arg(ConstructorArgs),
4594 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004595 ConstructKind,
4596 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004597 else
4598 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004600 move_arg(ConstructorArgs),
4601 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004602 ConstructKind,
4603 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004604 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004605 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004606 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004607
4608 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004609 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004610 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004611 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004613 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004614 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004616 break;
4617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004619 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004620 step_iterator NextStep = Step;
4621 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004623 NextStep->Kind == SK_ConstructorInitialization) {
4624 // The need for zero-initialization is recorded directly into
4625 // the call to the object's constructor within the next step.
4626 ConstructorInitRequiresZeroInit = true;
4627 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4628 S.getLangOptions().CPlusPlus &&
4629 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004630 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4631 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004633 Kind.getRange().getBegin());
4634
4635 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4636 TSInfo->getType().getNonLValueExprType(S.Context),
4637 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004638 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004639 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004640 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004641 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004642 break;
4643 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004644
4645 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004646 QualType SourceType = CurInit.get()->getType();
4647 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004648 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004649 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4650 if (Result.isInvalid())
4651 return ExprError();
4652 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004653
4654 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004655 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004656 if (ConvTy != Sema::Compatible &&
4657 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004658 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004659 == Sema::Compatible)
4660 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004661 if (CurInitExprRes.isInvalid())
4662 return ExprError();
4663 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004664
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004665 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004666 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4667 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004668 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004669 getAssignmentAction(Entity),
4670 &Complained)) {
4671 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004672 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004673 } else if (Complained)
4674 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004675 break;
4676 }
Eli Friedman78275202009-12-19 08:11:05 +00004677
4678 case SK_StringInit: {
4679 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004680 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004681 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004682 break;
4683 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004684
4685 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004686 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004687 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004688 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004689 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004690
4691 case SK_ArrayInit:
4692 // Okay: we checked everything before creating this step. Note that
4693 // this is a GNU extension.
4694 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004695 << Step->Type << CurInit.get()->getType()
4696 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004697
4698 // If the destination type is an incomplete array type, update the
4699 // type accordingly.
4700 if (ResultType) {
4701 if (const IncompleteArrayType *IncompleteDest
4702 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4703 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004704 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004705 *ResultType = S.Context.getConstantArrayType(
4706 IncompleteDest->getElementType(),
4707 ConstantSource->getSize(),
4708 ArrayType::Normal, 0);
4709 }
4710 }
4711 }
John McCall31168b02011-06-15 23:02:42 +00004712 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004713
John McCall31168b02011-06-15 23:02:42 +00004714 case SK_PassByIndirectCopyRestore:
4715 case SK_PassByIndirectRestore:
4716 checkIndirectCopyRestoreSource(S, CurInit.get());
4717 CurInit = S.Owned(new (S.Context)
4718 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4719 Step->Kind == SK_PassByIndirectCopyRestore));
4720 break;
4721
4722 case SK_ProduceObjCObject:
4723 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00004724 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00004725 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004726 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004727 }
4728 }
John McCall1f425642010-11-11 03:21:53 +00004729
4730 // Diagnose non-fatal problems with the completed initialization.
4731 if (Entity.getKind() == InitializedEntity::EK_Member &&
4732 cast<FieldDecl>(Entity.getDecl())->isBitField())
4733 S.CheckBitFieldInitialization(Kind.getLocation(),
4734 cast<FieldDecl>(Entity.getDecl()),
4735 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004736
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004737 return move(CurInit);
4738}
4739
4740//===----------------------------------------------------------------------===//
4741// Diagnose initialization failures
4742//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004744 const InitializedEntity &Entity,
4745 const InitializationKind &Kind,
4746 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004747 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004748 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749
Douglas Gregor1b303932009-12-22 15:35:07 +00004750 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004751 switch (Failure) {
4752 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004753 // FIXME: Customize for the initialized entity?
4754 if (NumArgs == 0)
4755 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4756 << DestType.getNonReferenceType();
4757 else // FIXME: diagnostic below could be better!
4758 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4759 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004762 case FK_ArrayNeedsInitList:
4763 case FK_ArrayNeedsInitListOrStringLiteral:
4764 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4765 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Douglas Gregore2f943b2011-02-22 18:29:51 +00004768 case FK_ArrayTypeMismatch:
4769 case FK_NonConstantArrayInit:
4770 S.Diag(Kind.getLocation(),
4771 (Failure == FK_ArrayTypeMismatch
4772 ? diag::err_array_init_different_type
4773 : diag::err_array_init_non_constant_array))
4774 << DestType.getNonReferenceType()
4775 << Args[0]->getType()
4776 << Args[0]->getSourceRange();
4777 break;
4778
John McCall16df1e52010-03-30 21:47:33 +00004779 case FK_AddressOfOverloadFailed: {
4780 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004782 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004783 true,
4784 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004785 break;
John McCall16df1e52010-03-30 21:47:33 +00004786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004788 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004789 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004790 switch (FailedOverloadResult) {
4791 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004792 if (Failure == FK_UserConversionOverloadFailed)
4793 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4794 << Args[0]->getType() << DestType
4795 << Args[0]->getSourceRange();
4796 else
4797 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4798 << DestType << Args[0]->getType()
4799 << Args[0]->getSourceRange();
4800
John McCall5c32be02010-08-24 20:38:10 +00004801 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004802 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004804 case OR_No_Viable_Function:
4805 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4806 << Args[0]->getType() << DestType.getNonReferenceType()
4807 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004808 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004809 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004811 case OR_Deleted: {
4812 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4813 << Args[0]->getType() << DestType.getNonReferenceType()
4814 << Args[0]->getSourceRange();
4815 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004816 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004817 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4818 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004819 if (Ovl == OR_Deleted) {
4820 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004821 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004822 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004823 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004824 }
4825 break;
4826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004828 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004829 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004830 break;
4831 }
4832 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004834 case FK_NonConstLValueReferenceBindingToTemporary:
4835 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004837 Failure == FK_NonConstLValueReferenceBindingToTemporary
4838 ? diag::err_lvalue_reference_bind_to_temporary
4839 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004840 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004841 << DestType.getNonReferenceType()
4842 << Args[0]->getType()
4843 << Args[0]->getSourceRange();
4844 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004846 case FK_RValueReferenceBindingToLValue:
4847 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004848 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004849 << Args[0]->getSourceRange();
4850 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004851
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004852 case FK_ReferenceInitDropsQualifiers:
4853 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4854 << DestType.getNonReferenceType()
4855 << Args[0]->getType()
4856 << Args[0]->getSourceRange();
4857 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004858
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004859 case FK_ReferenceInitFailed:
4860 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4861 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004862 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004863 << Args[0]->getType()
4864 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004865 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4866 Args[0]->getType()->isObjCObjectPointerType())
4867 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004868 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869
Douglas Gregorb491ed32011-02-19 21:32:49 +00004870 case FK_ConversionFailed: {
4871 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004872 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4873 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004874 << DestType
John McCall086a4642010-11-24 05:12:34 +00004875 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004876 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004877 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004878 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4879 Args[0]->getType()->isObjCObjectPointerType())
4880 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004881 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004882 }
John Wiegley01296292011-04-08 18:41:53 +00004883
4884 case FK_ConversionFromPropertyFailed:
4885 // No-op. This error has already been reported.
4886 break;
4887
Douglas Gregor51e77d52009-12-10 17:56:55 +00004888 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004889 SourceRange R;
4890
4891 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004892 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004893 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004895 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004896
Douglas Gregor8ec51732010-09-08 21:40:08 +00004897 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4898 if (Kind.isCStyleOrFunctionalCast())
4899 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4900 << R;
4901 else
4902 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4903 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004904 break;
4905 }
4906
4907 case FK_ReferenceBindingToInitList:
4908 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4909 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4910 break;
4911
4912 case FK_InitListBadDestinationType:
4913 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4914 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4915 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004917 case FK_ConstructorOverloadFailed: {
4918 SourceRange ArgsRange;
4919 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004921 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004923 // FIXME: Using "DestType" for the entity we're printing is probably
4924 // bad.
4925 switch (FailedOverloadResult) {
4926 case OR_Ambiguous:
4927 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4928 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004929 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4930 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004931 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004933 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004934 if (Kind.getKind() == InitializationKind::IK_Default &&
4935 (Entity.getKind() == InitializedEntity::EK_Base ||
4936 Entity.getKind() == InitializedEntity::EK_Member) &&
4937 isa<CXXConstructorDecl>(S.CurContext)) {
4938 // This is implicit default initialization of a member or
4939 // base within a constructor. If no viable function was
4940 // found, notify the user that she needs to explicitly
4941 // initialize this base/member.
4942 CXXConstructorDecl *Constructor
4943 = cast<CXXConstructorDecl>(S.CurContext);
4944 if (Entity.getKind() == InitializedEntity::EK_Base) {
4945 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4946 << Constructor->isImplicit()
4947 << S.Context.getTypeDeclType(Constructor->getParent())
4948 << /*base=*/0
4949 << Entity.getType();
4950
4951 RecordDecl *BaseDecl
4952 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4953 ->getDecl();
4954 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4955 << S.Context.getTagDeclType(BaseDecl);
4956 } else {
4957 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4958 << Constructor->isImplicit()
4959 << S.Context.getTypeDeclType(Constructor->getParent())
4960 << /*member=*/1
4961 << Entity.getName();
4962 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4963
4964 if (const RecordType *Record
4965 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004967 diag::note_previous_decl)
4968 << S.Context.getTagDeclType(Record->getDecl());
4969 }
4970 break;
4971 }
4972
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004973 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4974 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004975 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004976 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004978 case OR_Deleted: {
4979 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4980 << true << DestType << ArgsRange;
4981 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004982 OverloadingResult Ovl
4983 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004984 if (Ovl == OR_Deleted) {
4985 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004986 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004987 } else {
4988 llvm_unreachable("Inconsistent overload resolution?");
4989 }
4990 break;
4991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004993 case OR_Success:
4994 llvm_unreachable("Conversion did not fail!");
4995 break;
4996 }
4997 break;
4998 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
Douglas Gregor85dabae2009-12-16 01:38:02 +00005000 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005001 if (Entity.getKind() == InitializedEntity::EK_Member &&
5002 isa<CXXConstructorDecl>(S.CurContext)) {
5003 // This is implicit default-initialization of a const member in
5004 // a constructor. Complain that it needs to be explicitly
5005 // initialized.
5006 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5007 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5008 << Constructor->isImplicit()
5009 << S.Context.getTypeDeclType(Constructor->getParent())
5010 << /*const=*/1
5011 << Entity.getName();
5012 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5013 << Entity.getName();
5014 } else {
5015 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5016 << DestType << (bool)DestType->getAs<RecordType>();
5017 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005018 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005020 case FK_Incomplete:
5021 S.RequireCompleteType(Kind.getLocation(), DestType,
5022 diag::err_init_incomplete_type);
5023 break;
5024
5025 case FK_ListInitializationFailed:
5026 assert(false && "Failed list initialization not yet handled.");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005029 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005030 return true;
5031}
Douglas Gregore1314a62009-12-18 05:02:21 +00005032
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005033void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005034 switch (SequenceKind) {
5035 case FailedSequence: {
5036 OS << "Failed sequence: ";
5037 switch (Failure) {
5038 case FK_TooManyInitsForReference:
5039 OS << "too many initializers for reference";
5040 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005042 case FK_ArrayNeedsInitList:
5043 OS << "array requires initializer list";
5044 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005046 case FK_ArrayNeedsInitListOrStringLiteral:
5047 OS << "array requires initializer list or string literal";
5048 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005049
Douglas Gregore2f943b2011-02-22 18:29:51 +00005050 case FK_ArrayTypeMismatch:
5051 OS << "array type mismatch";
5052 break;
5053
5054 case FK_NonConstantArrayInit:
5055 OS << "non-constant array initializer";
5056 break;
5057
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005058 case FK_AddressOfOverloadFailed:
5059 OS << "address of overloaded function failed";
5060 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005062 case FK_ReferenceInitOverloadFailed:
5063 OS << "overload resolution for reference initialization failed";
5064 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005066 case FK_NonConstLValueReferenceBindingToTemporary:
5067 OS << "non-const lvalue reference bound to temporary";
5068 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005070 case FK_NonConstLValueReferenceBindingToUnrelated:
5071 OS << "non-const lvalue reference bound to unrelated type";
5072 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005074 case FK_RValueReferenceBindingToLValue:
5075 OS << "rvalue reference bound to an lvalue";
5076 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005078 case FK_ReferenceInitDropsQualifiers:
5079 OS << "reference initialization drops qualifiers";
5080 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005082 case FK_ReferenceInitFailed:
5083 OS << "reference initialization failed";
5084 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005086 case FK_ConversionFailed:
5087 OS << "conversion failed";
5088 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089
John Wiegley01296292011-04-08 18:41:53 +00005090 case FK_ConversionFromPropertyFailed:
5091 OS << "conversion from property failed";
5092 break;
5093
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005094 case FK_TooManyInitsForScalar:
5095 OS << "too many initializers for scalar";
5096 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005098 case FK_ReferenceBindingToInitList:
5099 OS << "referencing binding to initializer list";
5100 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005102 case FK_InitListBadDestinationType:
5103 OS << "initializer list for non-aggregate, non-scalar type";
5104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005106 case FK_UserConversionOverloadFailed:
5107 OS << "overloading failed for user-defined conversion";
5108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005110 case FK_ConstructorOverloadFailed:
5111 OS << "constructor overloading failed";
5112 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005114 case FK_DefaultInitOfConst:
5115 OS << "default initialization of a const variable";
5116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005118 case FK_Incomplete:
5119 OS << "initialization of incomplete type";
5120 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005121
5122 case FK_ListInitializationFailed:
5123 OS << "list initialization failed";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005125 OS << '\n';
5126 return;
5127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005128
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005129 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005130 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005131 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132
Sebastian Redld201edf2011-06-05 13:59:11 +00005133 case NormalSequence:
5134 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005135 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005138 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5139 if (S != step_begin()) {
5140 OS << " -> ";
5141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005142
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005143 switch (S->Kind) {
5144 case SK_ResolveAddressOfOverloadedFunction:
5145 OS << "resolve address of overloaded function";
5146 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005148 case SK_CastDerivedToBaseRValue:
5149 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5150 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005152 case SK_CastDerivedToBaseXValue:
5153 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5154 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005156 case SK_CastDerivedToBaseLValue:
5157 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5158 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005160 case SK_BindReference:
5161 OS << "bind reference to lvalue";
5162 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005164 case SK_BindReferenceToTemporary:
5165 OS << "bind reference to a temporary";
5166 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005168 case SK_ExtraneousCopyToTemporary:
5169 OS << "extraneous C++03 copy to temporary";
5170 break;
5171
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005172 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005173 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005174 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005175
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005176 case SK_QualificationConversionRValue:
5177 OS << "qualification conversion (rvalue)";
5178
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005179 case SK_QualificationConversionXValue:
5180 OS << "qualification conversion (xvalue)";
5181
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005182 case SK_QualificationConversionLValue:
5183 OS << "qualification conversion (lvalue)";
5184 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005186 case SK_ConversionSequence:
5187 OS << "implicit conversion sequence (";
5188 S->ICS->DebugPrint(); // FIXME: use OS
5189 OS << ")";
5190 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005191
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005192 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005193 OS << "list aggregate initialization";
5194 break;
5195
5196 case SK_ListConstructorCall:
5197 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005198 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005200 case SK_ConstructorInitialization:
5201 OS << "constructor initialization";
5202 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005204 case SK_ZeroInitialization:
5205 OS << "zero initialization";
5206 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005208 case SK_CAssignment:
5209 OS << "C assignment";
5210 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005211
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005212 case SK_StringInit:
5213 OS << "string initialization";
5214 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005215
5216 case SK_ObjCObjectConversion:
5217 OS << "Objective-C object conversion";
5218 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005219
5220 case SK_ArrayInit:
5221 OS << "array initialization";
5222 break;
John McCall31168b02011-06-15 23:02:42 +00005223
5224 case SK_PassByIndirectCopyRestore:
5225 OS << "pass by indirect copy and restore";
5226 break;
5227
5228 case SK_PassByIndirectRestore:
5229 OS << "pass by indirect restore";
5230 break;
5231
5232 case SK_ProduceObjCObject:
5233 OS << "Objective-C object retension";
5234 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005235 }
5236 }
5237}
5238
5239void InitializationSequence::dump() const {
5240 dump(llvm::errs());
5241}
5242
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005243static void DiagnoseNarrowingInInitList(
5244 Sema& S, QualType EntityType, const Expr *InitE,
5245 bool Constant, const APValue &ConstantValue) {
5246 if (Constant) {
5247 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005248 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005249 ? diag::err_init_list_constant_narrowing
5250 : diag::warn_init_list_constant_narrowing)
5251 << InitE->getSourceRange()
5252 << ConstantValue
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005253 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005254 } else
5255 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005256 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005257 ? diag::err_init_list_variable_narrowing
5258 : diag::warn_init_list_variable_narrowing)
5259 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005260 << InitE->getType().getLocalUnqualifiedType()
5261 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005262
5263 llvm::SmallString<128> StaticCast;
5264 llvm::raw_svector_ostream OS(StaticCast);
5265 OS << "static_cast<";
5266 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5267 // It's important to use the typedef's name if there is one so that the
5268 // fixit doesn't break code using types like int64_t.
5269 //
5270 // FIXME: This will break if the typedef requires qualification. But
5271 // getQualifiedNameAsString() includes non-machine-parsable components.
5272 OS << TT->getDecl();
5273 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5274 OS << BT->getName(S.getLangOptions());
5275 else {
5276 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5277 // with a broken cast.
5278 return;
5279 }
5280 OS << ">(";
5281 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5282 << InitE->getSourceRange()
5283 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5284 << FixItHint::CreateInsertion(
5285 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5286}
5287
Douglas Gregore1314a62009-12-18 05:02:21 +00005288//===----------------------------------------------------------------------===//
5289// Initialization helper functions
5290//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005291bool
5292Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5293 ExprResult Init) {
5294 if (Init.isInvalid())
5295 return false;
5296
5297 Expr *InitE = Init.get();
5298 assert(InitE && "No initialization expression");
5299
5300 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5301 SourceLocation());
5302 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005303 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005304}
5305
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005307Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5308 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005309 ExprResult Init,
5310 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005311 if (Init.isInvalid())
5312 return ExprError();
5313
John McCall1f425642010-11-11 03:21:53 +00005314 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005315 assert(InitE && "No initialization expression?");
5316
5317 if (EqualLoc.isInvalid())
5318 EqualLoc = InitE->getLocStart();
5319
5320 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5321 EqualLoc);
5322 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5323 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005324
5325 bool Constant = false;
5326 APValue Result;
5327 if (TopLevelOfInitList &&
5328 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5329 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5330 Constant, Result);
5331 }
John McCallfaf5fb42010-08-26 23:41:50 +00005332 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005333}