blob: f449c7d70d5c7c1f867c1ae658259ec9e23e9ac4 [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;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000173 bool AllowBraceElision;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000198 void CheckComplexType(const InitializedEntity &Entity,
199 InitListExpr *IList, QualType DeclType,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000203 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000204 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000208 void CheckReferenceType(const InitializedEntity &Entity,
209 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000210 unsigned &Index,
211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000213 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000214 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000217 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000218 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000219 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000222 unsigned &StructuredIndex,
223 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000224 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000225 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000226 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000230 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000231 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000232 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000233 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 RecordDecl::field_iterator *NextField,
235 llvm::APSInt *NextElementIndex,
236 unsigned &Index,
237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000239 bool FinishSubobjectInit,
240 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
242 QualType CurrentObjectType,
243 InitListExpr *StructuredList,
244 unsigned StructuredIndex,
245 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000246 void UpdateStructuredListElement(InitListExpr *StructuredList,
247 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248 Expr *expr);
249 int numArrayElements(QualType DeclType);
250 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000251
Douglas Gregor2bb07652009-12-22 00:05:34 +0000252 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000255 void FillInValueInitializations(const InitializedEntity &Entity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000257 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
258 Expr *InitExpr, FieldDecl *Field,
259 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000260 void CheckValueInitializable(const InitializedEntity &Entity);
261
Douglas Gregor85df8d82009-01-29 00:45:39 +0000262public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000263 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000264 InitListExpr *IL, QualType &T, bool VerifyOnly,
265 bool AllowBraceElision);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000266 bool HadError() { return hadError; }
267
268 // @brief Retrieves the fully-structured initializer list used for
269 // semantic analysis and code generation.
270 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
271};
Chris Lattner9ececce2009-02-24 22:48:58 +0000272} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000273
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000274void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
275 assert(VerifyOnly &&
276 "CheckValueInitializable is only inteded for verification mode.");
277
278 SourceLocation Loc;
279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
282 if (InitSeq.Failed())
283 hadError = true;
284}
285
Douglas Gregor2bb07652009-12-22 00:05:34 +0000286void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
287 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000288 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000289 bool &RequiresSecondPass) {
290 SourceLocation Loc = ILE->getSourceRange().getBegin();
291 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000292 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000293 = InitializedEntity::InitializeMember(Field, &ParentEntity);
294 if (Init >= NumInits || !ILE->getInit(Init)) {
295 // FIXME: We probably don't need to handle references
296 // specially here, since value-initialization of references is
297 // handled in InitializationSequence.
298 if (Field->getType()->isReferenceType()) {
299 // C++ [dcl.init.aggr]p9:
300 // If an incomplete or empty initializer-list leaves a
301 // member of reference type uninitialized, the program is
302 // ill-formed.
303 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
304 << Field->getType()
305 << ILE->getSyntacticForm()->getSourceRange();
306 SemaRef.Diag(Field->getLocation(),
307 diag::note_uninit_reference_member);
308 hadError = true;
309 return;
310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311
Douglas Gregor2bb07652009-12-22 00:05:34 +0000312 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
313 true);
314 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
315 if (!InitSeq) {
316 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
317 hadError = true;
318 return;
319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000320
John McCalldadc5752010-08-24 06:29:42 +0000321 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000322 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323 if (MemberInit.isInvalid()) {
324 hadError = true;
325 return;
326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327
Douglas Gregor2bb07652009-12-22 00:05:34 +0000328 if (hadError) {
329 // Do nothing
330 } else if (Init < NumInits) {
331 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000332 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000333 // Value-initialization requires a constructor call, so
334 // extend the initializer list to include the constructor
335 // call and make a note that we'll need to take another pass
336 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000337 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000338 RequiresSecondPass = true;
339 }
340 } else if (InitListExpr *InnerILE
341 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000342 FillInValueInitializations(MemberEntity, InnerILE,
343 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000344}
345
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000346/// Recursively replaces NULL values within the given initializer list
347/// with expressions that perform value-initialization of the
348/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349void
Douglas Gregor723796a2009-12-16 06:35:08 +0000350InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
351 InitListExpr *ILE,
352 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000353 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000354 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000355 SourceLocation Loc = ILE->getSourceRange().getBegin();
356 if (ILE->getSyntacticForm())
357 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000358
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000359 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000360 if (RType->getDecl()->isUnion() &&
361 ILE->getInitializedFieldInUnion())
362 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
363 Entity, ILE, RequiresSecondPass);
364 else {
365 unsigned Init = 0;
366 for (RecordDecl::field_iterator
367 Field = RType->getDecl()->field_begin(),
368 FieldEnd = RType->getDecl()->field_end();
369 Field != FieldEnd; ++Field) {
370 if (Field->isUnnamedBitfield())
371 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000372
Douglas Gregor2bb07652009-12-22 00:05:34 +0000373 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000374 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000375
376 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
377 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000378 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379
Douglas Gregor2bb07652009-12-22 00:05:34 +0000380 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000381
Douglas Gregor2bb07652009-12-22 00:05:34 +0000382 // Only look at the first initialization of a union.
383 if (RType->getDecl()->isUnion())
384 break;
385 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000386 }
387
388 return;
Mike Stump11289f42009-09-09 15:08:12 +0000389 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000390
391 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregor723796a2009-12-16 06:35:08 +0000393 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000394 unsigned NumInits = ILE->getNumInits();
395 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000396 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000397 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000398 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
399 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000401 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000402 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000403 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000404 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000406 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000407 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000408 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000409
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000411 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000412 if (hadError)
413 return;
414
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
416 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000417 ElementEntity.setElementIndex(Init);
418
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000419 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
421 true);
422 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
423 if (!InitSeq) {
424 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000425 hadError = true;
426 return;
427 }
428
John McCalldadc5752010-08-24 06:29:42 +0000429 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000430 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000431 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000432 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000433 return;
434 }
435
436 if (hadError) {
437 // Do nothing
438 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000439 // For arrays, just set the expression used for value-initialization
440 // of the "holes" in the array.
441 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
442 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
443 else
444 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000445 } else {
446 // For arrays, just set the expression used for value-initialization
447 // of the rest of elements and exit.
448 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
449 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
450 return;
451 }
452
Sebastian Redld201edf2011-06-05 13:59:11 +0000453 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000454 // Value-initialization requires a constructor call, so
455 // extend the initializer list to include the constructor
456 // call and make a note that we'll need to take another pass
457 // through the initializer list.
458 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
459 RequiresSecondPass = true;
460 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000461 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000462 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000463 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
464 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000465 }
466}
467
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000468
Douglas Gregor723796a2009-12-16 06:35:08 +0000469InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000470 InitListExpr *IL, QualType &T,
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000471 bool VerifyOnly, bool AllowBraceElision)
472 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000473 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000474
Eli Friedman23a9e312008-05-19 19:16:24 +0000475 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000476 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000477 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000478 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000479 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000480 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000481 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000482
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000483 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000484 bool RequiresSecondPass = false;
485 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000486 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000487 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000488 RequiresSecondPass);
489 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000490}
491
492int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000493 // FIXME: use a proper constant
494 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000495 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000496 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000497 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
498 }
499 return maxElements;
500}
501
502int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000503 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000505 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000506 Field = structDecl->field_begin(),
507 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000508 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000509 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000510 ++InitializableMembers;
511 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000512 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000513 return std::min(InitializableMembers, 1);
514 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000515}
516
Anders Carlsson6cabf312010-01-23 23:23:01 +0000517void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000518 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000519 QualType T, unsigned &Index,
520 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000521 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000522 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Steve Narofff8ecff22008-05-01 22:18:59 +0000524 if (T->isArrayType())
525 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000526 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000527 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000528 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000529 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000530 else
David Blaikie83d382b2011-09-23 05:06:16 +0000531 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000532
Eli Friedmane0f832b2008-05-25 13:49:22 +0000533 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000534 if (!VerifyOnly)
535 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
536 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000537 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000538 hadError = true;
539 return;
540 }
541
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000542 // Build a structured initializer list corresponding to this subobject.
543 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000544 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
545 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000546 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
547 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000548 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000549
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000550 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000551 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000553 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000554 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000555 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000556
557 if (VerifyOnly) {
558 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
559 hadError = true;
560 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000561 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000562
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000563 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000564 // Update the structured sub-object initializer so that it's ending
565 // range corresponds with the end of the last initializer it used.
566 if (EndIndex < ParentIList->getNumInits()) {
567 SourceLocation EndLoc
568 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
569 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000572 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000573 if (T->isArrayType() || T->isRecordType()) {
574 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000575 AllowBraceElision ? diag::warn_missing_braces :
576 diag::err_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000577 << StructuredSubobjectInitList->getSourceRange()
578 << FixItHint::CreateInsertion(
579 StructuredSubobjectInitList->getLocStart(), "{")
580 << FixItHint::CreateInsertion(
581 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000582 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000583 "}");
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000584 if (!AllowBraceElision)
585 hadError = true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000586 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000587 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000588}
589
Anders Carlsson6cabf312010-01-23 23:23:01 +0000590void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000591 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 unsigned &Index,
593 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000594 unsigned &StructuredIndex,
595 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000596 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000597 if (!VerifyOnly) {
598 SyntacticToSemantic[IList] = StructuredList;
599 StructuredList->setSyntacticForm(IList);
600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000602 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000603 if (!VerifyOnly) {
604 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
605 IList->setType(ExprTy);
606 StructuredList->setType(ExprTy);
607 }
Eli Friedman85f54972008-05-25 13:22:35 +0000608 if (hadError)
609 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000610
Eli Friedman85f54972008-05-25 13:22:35 +0000611 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000612 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000613 if (VerifyOnly) {
614 if (SemaRef.getLangOptions().CPlusPlus ||
615 (SemaRef.getLangOptions().OpenCL &&
616 IList->getType()->isVectorType())) {
617 hadError = true;
618 }
619 return;
620 }
621
Eli Friedmanbd327452009-05-29 20:20:05 +0000622 if (StructuredIndex == 1 &&
623 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000624 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000625 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000626 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000627 hadError = true;
628 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000629 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000630 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000631 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000632 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000633 // Don't complain for incomplete types, since we'll get an error
634 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000635 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000636 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000637 CurrentObjectType->isArrayType()? 0 :
638 CurrentObjectType->isVectorType()? 1 :
639 CurrentObjectType->isScalarType()? 2 :
640 CurrentObjectType->isUnionType()? 3 :
641 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000642
643 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000644 if (SemaRef.getLangOptions().CPlusPlus) {
645 DK = diag::err_excess_initializers;
646 hadError = true;
647 }
Nate Begeman425038c2009-07-07 21:53:06 +0000648 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
649 DK = diag::err_excess_initializers;
650 hadError = true;
651 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000652
Chris Lattnerb0912a52009-02-24 22:50:46 +0000653 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000654 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000655 }
656 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000657
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000658 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
659 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000660 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000661 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000662 << FixItHint::CreateRemoval(IList->getLocStart())
663 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000664}
665
Anders Carlsson6cabf312010-01-23 23:23:01 +0000666void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000667 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000668 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000669 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000670 unsigned &Index,
671 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000672 unsigned &StructuredIndex,
673 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000674 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
675 // Explicitly braced initializer for complex type can be real+imaginary
676 // parts.
677 CheckComplexType(Entity, IList, DeclType, Index,
678 StructuredList, StructuredIndex);
679 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000680 CheckScalarType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000682 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000683 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000684 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000685 } else if (DeclType->isAggregateType()) {
686 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000687 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000688 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000689 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000690 StructuredList, StructuredIndex,
691 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000692 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000693 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000694 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000695 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000696 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000697 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000698 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000699 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000700 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000701 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
702 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000703 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000704 if (!VerifyOnly)
705 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
706 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000707 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000708 } else if (DeclType->isRecordType()) {
709 // C++ [dcl.init]p14:
710 // [...] If the class is an aggregate (8.5.1), and the initializer
711 // is a brace-enclosed list, see 8.5.1.
712 //
713 // Note: 8.5.1 is handled below; here, we diagnose the case where
714 // we have an initializer list and a destination type that is not
715 // an aggregate.
716 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000717 if (!VerifyOnly)
718 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
719 << DeclType << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000720 hadError = true;
721 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000722 CheckReferenceType(Entity, IList, DeclType, Index,
723 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000724 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000725 if (!VerifyOnly)
726 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
727 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000728 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000729 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000730 if (!VerifyOnly)
731 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
732 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000733 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000734 }
735}
736
Anders Carlsson6cabf312010-01-23 23:23:01 +0000737void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000738 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000739 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000740 unsigned &Index,
741 InitListExpr *StructuredList,
742 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000743 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000744 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
745 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000747 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000748 = getStructuredSubobjectInit(IList, Index, ElemType,
749 StructuredList, StructuredIndex,
750 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000751 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000752 newStructuredList, newStructuredIndex);
753 ++StructuredIndex;
754 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000755 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000756 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000757 return CheckScalarType(Entity, IList, ElemType, Index,
758 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000759 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000760 return CheckReferenceType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
762 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000763
John McCall5decec92011-02-21 07:57:55 +0000764 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
765 // arrayType can be incomplete if we're initializing a flexible
766 // array member. There's nothing we can do with the completed
767 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768
John McCall5decec92011-02-21 07:57:55 +0000769 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000770 if (!VerifyOnly) {
771 CheckStringInit(Str, ElemType, arrayType, SemaRef);
772 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
773 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000774 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000775 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000776 }
John McCall5decec92011-02-21 07:57:55 +0000777
778 // Fall through for subaggregate initialization.
779
780 } else if (SemaRef.getLangOptions().CPlusPlus) {
781 // C++ [dcl.init.aggr]p12:
782 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000783 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000784 // an initializer-list. If the initializer can initialize a
785 // member, the member is initialized. [...]
786
787 // FIXME: Better EqualLoc?
788 InitializationKind Kind =
789 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
790 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
791
792 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000793 if (!VerifyOnly) {
794 ExprResult Result =
795 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
796 if (Result.isInvalid())
797 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000798
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000799 UpdateStructuredListElement(StructuredList, StructuredIndex,
800 Result.takeAs<Expr>());
801 }
John McCall5decec92011-02-21 07:57:55 +0000802 ++Index;
803 return;
804 }
805
806 // Fall through for subaggregate initialization
807 } else {
808 // C99 6.7.8p13:
809 //
810 // The initializer for a structure or union object that has
811 // automatic storage duration shall be either an initializer
812 // list as described below, or a single expression that has
813 // compatible structure or union type. In the latter case, the
814 // initial value of the object, including unnamed members, is
815 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000816 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000817 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000818 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
819 !VerifyOnly)
John McCall5decec92011-02-21 07:57:55 +0000820 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000821 if (ExprRes.isInvalid())
822 hadError = true;
823 else {
824 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
825 if (ExprRes.isInvalid())
826 hadError = true;
827 }
828 UpdateStructuredListElement(StructuredList, StructuredIndex,
829 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000830 ++Index;
831 return;
832 }
John Wiegley01296292011-04-08 18:41:53 +0000833 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000834 // Fall through for subaggregate initialization
835 }
836
837 // C++ [dcl.init.aggr]p12:
838 //
839 // [...] Otherwise, if the member is itself a non-empty
840 // subaggregate, brace elision is assumed and the initializer is
841 // considered for the initialization of the first member of
842 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000843 if (!SemaRef.getLangOptions().OpenCL &&
844 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000845 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
846 StructuredIndex);
847 ++StructuredIndex;
848 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000849 if (!VerifyOnly) {
850 // We cannot initialize this element, so let
851 // PerformCopyInitialization produce the appropriate diagnostic.
852 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
853 SemaRef.Owned(expr),
854 /*TopLevelOfInitList=*/true);
855 }
John McCall5decec92011-02-21 07:57:55 +0000856 hadError = true;
857 ++Index;
858 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000859 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000860}
861
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000862void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
863 InitListExpr *IList, QualType DeclType,
864 unsigned &Index,
865 InitListExpr *StructuredList,
866 unsigned &StructuredIndex) {
867 assert(Index == 0 && "Index in explicit init list must be zero");
868
869 // As an extension, clang supports complex initializers, which initialize
870 // a complex number component-wise. When an explicit initializer list for
871 // a complex number contains two two initializers, this extension kicks in:
872 // it exepcts the initializer list to contain two elements convertible to
873 // the element type of the complex type. The first element initializes
874 // the real part, and the second element intitializes the imaginary part.
875
876 if (IList->getNumInits() != 2)
877 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
878 StructuredIndex);
879
880 // This is an extension in C. (The builtin _Complex type does not exist
881 // in the C++ standard.)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000882 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000883 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
884 << IList->getSourceRange();
885
886 // Initialize the complex number.
887 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
888 InitializedEntity ElementEntity =
889 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
890
891 for (unsigned i = 0; i < 2; ++i) {
892 ElementEntity.setElementIndex(Index);
893 CheckSubElementType(ElementEntity, IList, elementType, Index,
894 StructuredList, StructuredIndex);
895 }
896}
897
898
Anders Carlsson6cabf312010-01-23 23:23:01 +0000899void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000900 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000901 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000902 InitListExpr *StructuredList,
903 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000904 if (Index >= IList->getNumInits()) {
Sebastian Redl12757ab2011-09-24 17:48:14 +0000905 if (!SemaRef.getLangOptions().CPlusPlus0x) {
906 if (!VerifyOnly)
907 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
908 << IList->getSourceRange();
909 hadError = true;
910 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000911 ++Index;
912 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000913 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000914 }
John McCall643169b2010-11-11 00:46:36 +0000915
916 Expr *expr = IList->getInit(Index);
917 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000918 if (!VerifyOnly)
919 SemaRef.Diag(SubIList->getLocStart(),
920 diag::warn_many_braces_around_scalar_init)
921 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000922
923 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
924 StructuredIndex);
925 return;
926 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000927 if (!VerifyOnly)
928 SemaRef.Diag(expr->getSourceRange().getBegin(),
929 diag::err_designator_for_scalar_init)
930 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +0000931 hadError = true;
932 ++Index;
933 ++StructuredIndex;
934 return;
935 }
936
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000937 if (VerifyOnly) {
938 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
939 hadError = true;
940 ++Index;
941 return;
942 }
943
John McCall643169b2010-11-11 00:46:36 +0000944 ExprResult Result =
945 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000946 SemaRef.Owned(expr),
947 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000948
949 Expr *ResultExpr = 0;
950
951 if (Result.isInvalid())
952 hadError = true; // types weren't compatible.
953 else {
954 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000955
John McCall643169b2010-11-11 00:46:36 +0000956 if (ResultExpr != expr) {
957 // The type was promoted, update initializer list.
958 IList->setInit(Index, ResultExpr);
959 }
960 }
961 if (hadError)
962 ++StructuredIndex;
963 else
964 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
965 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000966}
967
Anders Carlsson6cabf312010-01-23 23:23:01 +0000968void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
969 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000970 unsigned &Index,
971 InitListExpr *StructuredList,
972 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000973 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +0000974 // FIXME: It would be wonderful if we could point at the actual member. In
975 // general, it would be useful to pass location information down the stack,
976 // so that we know the location (or decl) of the "current object" being
977 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000978 if (!VerifyOnly)
979 SemaRef.Diag(IList->getLocStart(),
980 diag::err_init_reference_member_uninitialized)
981 << DeclType
982 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +0000983 hadError = true;
984 ++Index;
985 ++StructuredIndex;
986 return;
987 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000988
989 Expr *expr = IList->getInit(Index);
990 if (isa<InitListExpr>(expr)) {
991 // FIXME: Allowed in C++11.
992 if (!VerifyOnly)
993 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
994 << DeclType << IList->getSourceRange();
995 hadError = true;
996 ++Index;
997 ++StructuredIndex;
998 return;
999 }
1000
1001 if (VerifyOnly) {
1002 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1003 hadError = true;
1004 ++Index;
1005 return;
1006 }
1007
1008 ExprResult Result =
1009 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1010 SemaRef.Owned(expr),
1011 /*TopLevelOfInitList=*/true);
1012
1013 if (Result.isInvalid())
1014 hadError = true;
1015
1016 expr = Result.takeAs<Expr>();
1017 IList->setInit(Index, expr);
1018
1019 if (hadError)
1020 ++StructuredIndex;
1021 else
1022 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1023 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001024}
1025
Anders Carlsson6cabf312010-01-23 23:23:01 +00001026void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001027 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001028 unsigned &Index,
1029 InitListExpr *StructuredList,
1030 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001031 const VectorType *VT = DeclType->getAs<VectorType>();
1032 unsigned maxElements = VT->getNumElements();
1033 unsigned numEltsInit = 0;
1034 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001035
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001036 if (Index >= IList->getNumInits()) {
1037 // Make sure the element type can be value-initialized.
1038 if (VerifyOnly)
1039 CheckValueInitializable(
1040 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1041 return;
1042 }
1043
John McCall6a16b2f2010-10-30 00:11:39 +00001044 if (!SemaRef.getLangOptions().OpenCL) {
1045 // If the initializing element is a vector, try to copy-initialize
1046 // instead of breaking it apart (which is doomed to failure anyway).
1047 Expr *Init = IList->getInit(Index);
1048 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001049 if (VerifyOnly) {
1050 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1051 hadError = true;
1052 ++Index;
1053 return;
1054 }
1055
John McCall6a16b2f2010-10-30 00:11:39 +00001056 ExprResult Result =
1057 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001058 SemaRef.Owned(Init),
1059 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001060
1061 Expr *ResultExpr = 0;
1062 if (Result.isInvalid())
1063 hadError = true; // types weren't compatible.
1064 else {
1065 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
John McCall6a16b2f2010-10-30 00:11:39 +00001067 if (ResultExpr != Init) {
1068 // The type was promoted, update initializer list.
1069 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001070 }
1071 }
John McCall6a16b2f2010-10-30 00:11:39 +00001072 if (hadError)
1073 ++StructuredIndex;
1074 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001075 UpdateStructuredListElement(StructuredList, StructuredIndex,
1076 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001077 ++Index;
1078 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001079 }
Mike Stump11289f42009-09-09 15:08:12 +00001080
John McCall6a16b2f2010-10-30 00:11:39 +00001081 InitializedEntity ElementEntity =
1082 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083
John McCall6a16b2f2010-10-30 00:11:39 +00001084 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1085 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001086 if (Index >= IList->getNumInits()) {
1087 if (VerifyOnly)
1088 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001089 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091
John McCall6a16b2f2010-10-30 00:11:39 +00001092 ElementEntity.setElementIndex(Index);
1093 CheckSubElementType(ElementEntity, IList, elementType, Index,
1094 StructuredList, StructuredIndex);
1095 }
1096 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001097 }
John McCall6a16b2f2010-10-30 00:11:39 +00001098
1099 InitializedEntity ElementEntity =
1100 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101
John McCall6a16b2f2010-10-30 00:11:39 +00001102 // OpenCL initializers allows vectors to be constructed from vectors.
1103 for (unsigned i = 0; i < maxElements; ++i) {
1104 // Don't attempt to go past the end of the init list
1105 if (Index >= IList->getNumInits())
1106 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
John McCall6a16b2f2010-10-30 00:11:39 +00001108 ElementEntity.setElementIndex(Index);
1109
1110 QualType IType = IList->getInit(Index)->getType();
1111 if (!IType->isVectorType()) {
1112 CheckSubElementType(ElementEntity, IList, elementType, Index,
1113 StructuredList, StructuredIndex);
1114 ++numEltsInit;
1115 } else {
1116 QualType VecType;
1117 const VectorType *IVT = IType->getAs<VectorType>();
1118 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001119
John McCall6a16b2f2010-10-30 00:11:39 +00001120 if (IType->isExtVectorType())
1121 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1122 else
1123 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001124 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001125 CheckSubElementType(ElementEntity, IList, VecType, Index,
1126 StructuredList, StructuredIndex);
1127 numEltsInit += numIElts;
1128 }
1129 }
1130
1131 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001132 if (numEltsInit != maxElements) {
1133 if (!VerifyOnly)
1134 SemaRef.Diag(IList->getSourceRange().getBegin(),
1135 diag::err_vector_incorrect_num_initializers)
1136 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1137 hadError = true;
1138 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001139}
1140
Anders Carlsson6cabf312010-01-23 23:23:01 +00001141void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001142 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001143 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001144 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001145 unsigned &Index,
1146 InitListExpr *StructuredList,
1147 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001148 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1149
Steve Narofff8ecff22008-05-01 22:18:59 +00001150 // Check for the special-case of initializing an array with a string.
1151 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001152 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001153 SemaRef.Context)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001154 // We place the string literal directly into the resulting
1155 // initializer list. This is the only place where the structure
1156 // of the structured initializer list doesn't match exactly,
1157 // because doing so would involve allocating one character
1158 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001159 if (!VerifyOnly) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001160 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001161 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1162 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1163 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001164 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001165 return;
1166 }
1167 }
John McCall66884dd2011-02-21 07:22:22 +00001168 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001169 // Check for VLAs; in standard C it would be possible to check this
1170 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1171 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001172 if (!VerifyOnly)
1173 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1174 diag::err_variable_object_no_init)
1175 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001176 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001177 ++Index;
1178 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001179 return;
1180 }
1181
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001182 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001183 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1184 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001185 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001186 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001187 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001188 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001189 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001190 maxElementsKnown = true;
1191 }
1192
John McCall66884dd2011-02-21 07:22:22 +00001193 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001194 while (Index < IList->getNumInits()) {
1195 Expr *Init = IList->getInit(Index);
1196 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001197 // If we're not the subobject that matches up with the '{' for
1198 // the designator, we shouldn't be handling the
1199 // designator. Return immediately.
1200 if (!SubobjectIsDesignatorContext)
1201 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001202
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001203 // Handle this designated initializer. elementIndex will be
1204 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001205 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001206 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001207 StructuredList, StructuredIndex, true,
1208 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001209 hadError = true;
1210 continue;
1211 }
1212
Douglas Gregor033d1252009-01-23 16:54:12 +00001213 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001214 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001215 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001216 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001217 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001218
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001219 // If the array is of incomplete type, keep track of the number of
1220 // elements in the initializer.
1221 if (!maxElementsKnown && elementIndex > maxElements)
1222 maxElements = elementIndex;
1223
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001224 continue;
1225 }
1226
1227 // If we know the maximum number of elements, and we've already
1228 // hit it, stop consuming elements in the initializer list.
1229 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001230 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001231
Anders Carlsson6cabf312010-01-23 23:23:01 +00001232 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001234 Entity);
1235 // Check this element.
1236 CheckSubElementType(ElementEntity, IList, elementType, Index,
1237 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001238 ++elementIndex;
1239
1240 // If the array is of incomplete type, keep track of the number of
1241 // elements in the initializer.
1242 if (!maxElementsKnown && elementIndex > maxElements)
1243 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001244 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001245 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001246 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001247 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001248 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001249 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001250 // Sizing an array implicitly to zero is not allowed by ISO C,
1251 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001252 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001253 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001254 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001255
Mike Stump11289f42009-09-09 15:08:12 +00001256 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001257 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001258 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001259 if (!hadError && VerifyOnly) {
1260 // Check if there are any members of the array that get value-initialized.
1261 // If so, check if doing that is possible.
1262 // FIXME: This needs to detect holes left by designated initializers too.
1263 if (maxElementsKnown && elementIndex < maxElements)
1264 CheckValueInitializable(InitializedEntity::InitializeElement(
1265 SemaRef.Context, 0, Entity));
1266 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001267}
1268
Eli Friedman3fa64df2011-08-23 22:24:57 +00001269bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1270 Expr *InitExpr,
1271 FieldDecl *Field,
1272 bool TopLevelObject) {
1273 // Handle GNU flexible array initializers.
1274 unsigned FlexArrayDiag;
1275 if (isa<InitListExpr>(InitExpr) &&
1276 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1277 // Empty flexible array init always allowed as an extension
1278 FlexArrayDiag = diag::ext_flexible_array_init;
1279 } else if (SemaRef.getLangOptions().CPlusPlus) {
1280 // Disallow flexible array init in C++; it is not required for gcc
1281 // compatibility, and it needs work to IRGen correctly in general.
1282 FlexArrayDiag = diag::err_flexible_array_init;
1283 } else if (!TopLevelObject) {
1284 // Disallow flexible array init on non-top-level object
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1287 // Disallow flexible array init on anything which is not a variable.
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1290 // Disallow flexible array init on local variables.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else {
1293 // Allow other cases.
1294 FlexArrayDiag = diag::ext_flexible_array_init;
1295 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001296
1297 if (!VerifyOnly) {
1298 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1299 FlexArrayDiag)
1300 << InitExpr->getSourceRange().getBegin();
1301 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1302 << Field;
1303 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001304
1305 return FlexArrayDiag != diag::ext_flexible_array_init;
1306}
1307
Anders Carlsson6cabf312010-01-23 23:23:01 +00001308void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001309 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001310 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001311 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001312 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001313 unsigned &Index,
1314 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001315 unsigned &StructuredIndex,
1316 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001317 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001318
Eli Friedman23a9e312008-05-19 19:16:24 +00001319 // If the record is invalid, some of it's members are invalid. To avoid
1320 // confusion, we forgo checking the intializer for the entire record.
1321 if (structDecl->isInvalidDecl()) {
1322 hadError = true;
1323 return;
Mike Stump11289f42009-09-09 15:08:12 +00001324 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001325
1326 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001327 // Value-initialize the first named member of the union.
1328 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1329 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1330 Field != FieldEnd; ++Field) {
1331 if (Field->getDeclName()) {
1332 if (VerifyOnly)
1333 CheckValueInitializable(
1334 InitializedEntity::InitializeMember(*Field, &Entity));
1335 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001336 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001337 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001338 }
1339 }
1340 return;
1341 }
1342
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001343 // If structDecl is a forward declaration, this loop won't do
1344 // anything except look at designated initializers; That's okay,
1345 // because an error should get printed out elsewhere. It might be
1346 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001347 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001348 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001349 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001350 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001351 while (Index < IList->getNumInits()) {
1352 Expr *Init = IList->getInit(Index);
1353
1354 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001355 // If we're not the subobject that matches up with the '{' for
1356 // the designator, we shouldn't be handling the
1357 // designator. Return immediately.
1358 if (!SubobjectIsDesignatorContext)
1359 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001360
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001361 // Handle this designated initializer. Field will be updated to
1362 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001363 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001364 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001365 StructuredList, StructuredIndex,
1366 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001367 hadError = true;
1368
Douglas Gregora9add4e2009-02-12 19:00:39 +00001369 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001370
1371 // Disable check for missing fields when designators are used.
1372 // This matches gcc behaviour.
1373 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001374 continue;
1375 }
1376
1377 if (Field == FieldEnd) {
1378 // We've run out of fields. We're done.
1379 break;
1380 }
1381
Douglas Gregora9add4e2009-02-12 19:00:39 +00001382 // We've already initialized a member of a union. We're done.
1383 if (InitializedSomething && DeclType->isUnionType())
1384 break;
1385
Douglas Gregor91f84212008-12-11 16:49:14 +00001386 // If we've hit the flexible array member at the end, we're done.
1387 if (Field->getType()->isIncompleteArrayType())
1388 break;
1389
Douglas Gregor51695702009-01-29 16:53:55 +00001390 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001391 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001392 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001393 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001394 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001395
Douglas Gregora82064c2011-06-29 21:51:31 +00001396 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001397 bool InvalidUse;
1398 if (VerifyOnly)
1399 InvalidUse = !SemaRef.CanUseDecl(*Field);
1400 else
1401 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1402 IList->getInit(Index)->getLocStart());
1403 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001404 ++Index;
1405 ++Field;
1406 hadError = true;
1407 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001408 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001409
Anders Carlsson6cabf312010-01-23 23:23:01 +00001410 InitializedEntity MemberEntity =
1411 InitializedEntity::InitializeMember(*Field, &Entity);
1412 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1413 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001414 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001415
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001416 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001417 // Initialize the first field within the union.
1418 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001419 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001420
1421 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001422 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001423
John McCalle40b58e2010-03-11 19:32:38 +00001424 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001425 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1426 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1427 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001428 // It is possible we have one or more unnamed bitfields remaining.
1429 // Find first (if any) named field and emit warning.
1430 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1431 it != end; ++it) {
1432 if (!it->isUnnamedBitfield()) {
1433 SemaRef.Diag(IList->getSourceRange().getEnd(),
1434 diag::warn_missing_field_initializers) << it->getName();
1435 break;
1436 }
1437 }
1438 }
1439
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001440 // Check that any remaining fields can be value-initialized.
1441 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1442 !Field->getType()->isIncompleteArrayType()) {
1443 // FIXME: Should check for holes left by designated initializers too.
1444 for (; Field != FieldEnd && !hadError; ++Field) {
1445 if (!Field->isUnnamedBitfield())
1446 CheckValueInitializable(
1447 InitializedEntity::InitializeMember(*Field, &Entity));
1448 }
1449 }
1450
Mike Stump11289f42009-09-09 15:08:12 +00001451 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001452 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001453 return;
1454
Eli Friedman3fa64df2011-08-23 22:24:57 +00001455 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1456 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001457 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001458 ++Index;
1459 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 }
1461
Anders Carlsson6cabf312010-01-23 23:23:01 +00001462 InitializedEntity MemberEntity =
1463 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464
Anders Carlsson6cabf312010-01-23 23:23:01 +00001465 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001467 StructuredList, StructuredIndex);
1468 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001469 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001470 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001471}
Steve Narofff8ecff22008-05-01 22:18:59 +00001472
Douglas Gregord5846a12009-04-15 06:41:24 +00001473/// \brief Expand a field designator that refers to a member of an
1474/// anonymous struct or union into a series of field designators that
1475/// refers to the field within the appropriate subobject.
1476///
Douglas Gregord5846a12009-04-15 06:41:24 +00001477static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001478 DesignatedInitExpr *DIE,
1479 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001480 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001481 typedef DesignatedInitExpr::Designator Designator;
1482
Douglas Gregord5846a12009-04-15 06:41:24 +00001483 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001484 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001485 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1486 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1487 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001488 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001489 DIE->getDesignator(DesigIdx)->getDotLoc(),
1490 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1491 else
1492 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1493 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001494 assert(isa<FieldDecl>(*PI));
1495 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001496 }
1497
1498 // Expand the current designator into the set of replacement
1499 // designators, so we have a full subobject path down to where the
1500 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001501 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001502 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001503}
Mike Stump11289f42009-09-09 15:08:12 +00001504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001506/// corresponds to FieldName.
1507static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1508 IdentifierInfo *FieldName) {
1509 assert(AnonField->isAnonymousStructOrUnion());
1510 Decl *NextDecl = AnonField->getNextDeclInContext();
1511 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1512 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1513 return IF;
1514 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001515 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001516 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001517}
1518
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001519static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1520 DesignatedInitExpr *DIE) {
1521 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1522 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1523 for (unsigned I = 0; I < NumIndexExprs; ++I)
1524 IndexExprs[I] = DIE->getSubExpr(I + 1);
1525 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1526 DIE->size(), IndexExprs.data(),
1527 NumIndexExprs, DIE->getEqualOrColonLoc(),
1528 DIE->usesGNUSyntax(), DIE->getInit());
1529}
1530
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001531/// @brief Check the well-formedness of a C99 designated initializer.
1532///
1533/// Determines whether the designated initializer @p DIE, which
1534/// resides at the given @p Index within the initializer list @p
1535/// IList, is well-formed for a current object of type @p DeclType
1536/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001537/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001538/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001539///
1540/// @param IList The initializer list in which this designated
1541/// initializer occurs.
1542///
Douglas Gregora5324162009-04-15 04:56:10 +00001543/// @param DIE The designated initializer expression.
1544///
1545/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001546///
1547/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1548/// into which the designation in @p DIE should refer.
1549///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001550/// @param NextField If non-NULL and the first designator in @p DIE is
1551/// a field, this will be set to the field declaration corresponding
1552/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001553///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001554/// @param NextElementIndex If non-NULL and the first designator in @p
1555/// DIE is an array designator or GNU array-range designator, this
1556/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001557///
1558/// @param Index Index into @p IList where the designated initializer
1559/// @p DIE occurs.
1560///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001561/// @param StructuredList The initializer list expression that
1562/// describes all of the subobject initializers in the order they'll
1563/// actually be initialized.
1564///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001565/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001566bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001567InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001568 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001569 DesignatedInitExpr *DIE,
1570 unsigned DesigIdx,
1571 QualType &CurrentObjectType,
1572 RecordDecl::field_iterator *NextField,
1573 llvm::APSInt *NextElementIndex,
1574 unsigned &Index,
1575 InitListExpr *StructuredList,
1576 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001577 bool FinishSubobjectInit,
1578 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001579 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001580 // Check the actual initialization for the designated object type.
1581 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001582
1583 // Temporarily remove the designator expression from the
1584 // initializer list that the child calls see, so that we don't try
1585 // to re-process the designator.
1586 unsigned OldIndex = Index;
1587 IList->setInit(OldIndex, DIE->getInit());
1588
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001589 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001590 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001591
1592 // Restore the designated initializer expression in the syntactic
1593 // form of the initializer list.
1594 if (IList->getInit(OldIndex) != DIE->getInit())
1595 DIE->setInit(IList->getInit(OldIndex));
1596 IList->setInit(OldIndex, DIE);
1597
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001598 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001599 }
1600
Douglas Gregora5324162009-04-15 04:56:10 +00001601 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001602 bool IsFirstDesignator = (DesigIdx == 0);
1603 if (!VerifyOnly) {
1604 assert((IsFirstDesignator || StructuredList) &&
1605 "Need a non-designated initializer list to start from");
1606
1607 // Determine the structural initializer list that corresponds to the
1608 // current subobject.
1609 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1610 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1611 StructuredList, StructuredIndex,
1612 SourceRange(D->getStartLocation(),
1613 DIE->getSourceRange().getEnd()));
1614 assert(StructuredList && "Expected a structured initializer list");
1615 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001616
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617 if (D->isFieldDesignator()) {
1618 // C99 6.7.8p7:
1619 //
1620 // If a designator has the form
1621 //
1622 // . identifier
1623 //
1624 // then the current object (defined below) shall have
1625 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001626 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001627 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001628 if (!RT) {
1629 SourceLocation Loc = D->getDotLoc();
1630 if (Loc.isInvalid())
1631 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001632 if (!VerifyOnly)
1633 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1634 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001635 ++Index;
1636 return true;
1637 }
1638
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001639 // Note: we perform a linear search of the fields here, despite
1640 // the fact that we have a faster lookup method, because we always
1641 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001642 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001643 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001644 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001645 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001646 Field = RT->getDecl()->field_begin(),
1647 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001648 for (; Field != FieldEnd; ++Field) {
1649 if (Field->isUnnamedBitfield())
1650 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001652 // If we find a field representing an anonymous field, look in the
1653 // IndirectFieldDecl that follow for the designated initializer.
1654 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1655 if (IndirectFieldDecl *IF =
1656 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001657 // In verify mode, don't modify the original.
1658 if (VerifyOnly)
1659 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001660 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1661 D = DIE->getDesignator(DesigIdx);
1662 break;
1663 }
1664 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001665 if (KnownField && KnownField == *Field)
1666 break;
1667 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668 break;
1669
1670 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001671 }
1672
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001673 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001674 if (VerifyOnly) {
1675 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001676 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001677 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001678
Douglas Gregord5846a12009-04-15 06:41:24 +00001679 // There was no normal field in the struct with the designated
1680 // name. Perform another lookup for this name, which may find
1681 // something that we can't designate (e.g., a member function),
1682 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001683 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001684 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001685 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001686 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001687 // Name lookup didn't find anything. Determine whether this
1688 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001689 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001690 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001691 TypoCorrection Corrected = SemaRef.CorrectTypo(
1692 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1693 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1694 RT->getDecl(), false, Sema::CTC_NoKeywords);
1695 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001696 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001697 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001698 std::string CorrectedStr(
1699 Corrected.getAsString(SemaRef.getLangOptions()));
1700 std::string CorrectedQuotedStr(
1701 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001703 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001704 << FieldName << CurrentObjectType << CorrectedQuotedStr
1705 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001706 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001707 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001708 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001709 } else {
1710 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1711 << FieldName << CurrentObjectType;
1712 ++Index;
1713 return true;
1714 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001716
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001717 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001718 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001719 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001720 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001721 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001722 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001723 ++Index;
1724 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001725 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001726
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001727 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001728 // The replacement field comes from typo correction; find it
1729 // in the list of fields.
1730 FieldIndex = 0;
1731 Field = RT->getDecl()->field_begin();
1732 for (; Field != FieldEnd; ++Field) {
1733 if (Field->isUnnamedBitfield())
1734 continue;
1735
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001737 Field->getIdentifier() == ReplacementField->getIdentifier())
1738 break;
1739
1740 ++FieldIndex;
1741 }
1742 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001743 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001744
1745 // All of the fields of a union are located at the same place in
1746 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001747 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001748 FieldIndex = 0;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001749 if (!VerifyOnly)
1750 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001751 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001752
Douglas Gregora82064c2011-06-29 21:51:31 +00001753 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001754 bool InvalidUse;
1755 if (VerifyOnly)
1756 InvalidUse = !SemaRef.CanUseDecl(*Field);
1757 else
1758 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1759 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001760 ++Index;
1761 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001762 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001763
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001764 if (!VerifyOnly) {
1765 // Update the designator with the field declaration.
1766 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001768 // Make sure that our non-designated initializer list has space
1769 // for a subobject corresponding to this field.
1770 if (FieldIndex >= StructuredList->getNumInits())
1771 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1772 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001774 // This designator names a flexible array member.
1775 if (Field->getType()->isIncompleteArrayType()) {
1776 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001777 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001778 // We can't designate an object within the flexible array
1779 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001780 if (!VerifyOnly) {
1781 DesignatedInitExpr::Designator *NextD
1782 = DIE->getDesignator(DesigIdx + 1);
1783 SemaRef.Diag(NextD->getStartLocation(),
1784 diag::err_designator_into_flexible_array_member)
1785 << SourceRange(NextD->getStartLocation(),
1786 DIE->getSourceRange().getEnd());
1787 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1788 << *Field;
1789 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001790 Invalid = true;
1791 }
1792
Chris Lattner001b29c2010-10-10 17:49:49 +00001793 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1794 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001795 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001796 if (!VerifyOnly) {
1797 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1798 diag::err_flexible_array_init_needs_braces)
1799 << DIE->getInit()->getSourceRange();
1800 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1801 << *Field;
1802 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001803 Invalid = true;
1804 }
1805
Eli Friedman3fa64df2011-08-23 22:24:57 +00001806 // Check GNU flexible array initializer.
1807 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1808 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001809 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001810
1811 if (Invalid) {
1812 ++Index;
1813 return true;
1814 }
1815
1816 // Initialize the array.
1817 bool prevHadError = hadError;
1818 unsigned newStructuredIndex = FieldIndex;
1819 unsigned OldIndex = Index;
1820 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001821
1822 InitializedEntity MemberEntity =
1823 InitializedEntity::InitializeMember(*Field, &Entity);
1824 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001825 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001826
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001827 IList->setInit(OldIndex, DIE);
1828 if (hadError && !prevHadError) {
1829 ++Field;
1830 ++FieldIndex;
1831 if (NextField)
1832 *NextField = Field;
1833 StructuredIndex = FieldIndex;
1834 return true;
1835 }
1836 } else {
1837 // Recurse to check later designated subobjects.
1838 QualType FieldType = (*Field)->getType();
1839 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001841 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001842 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001843 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1844 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001845 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001846 true, false))
1847 return true;
1848 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001849
1850 // Find the position of the next field to be initialized in this
1851 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001852 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001853 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001854
1855 // If this the first designator, our caller will continue checking
1856 // the rest of this struct/class/union subobject.
1857 if (IsFirstDesignator) {
1858 if (NextField)
1859 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001860 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001861 return false;
1862 }
1863
Douglas Gregor17bd0942009-01-28 23:36:17 +00001864 if (!FinishSubobjectInit)
1865 return false;
1866
Douglas Gregord5846a12009-04-15 06:41:24 +00001867 // We've already initialized something in the union; we're done.
1868 if (RT->getDecl()->isUnion())
1869 return hadError;
1870
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001871 // Check the remaining fields within this class/struct/union subobject.
1872 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873
Anders Carlsson6cabf312010-01-23 23:23:01 +00001874 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001875 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001876 return hadError && !prevHadError;
1877 }
1878
1879 // C99 6.7.8p6:
1880 //
1881 // If a designator has the form
1882 //
1883 // [ constant-expression ]
1884 //
1885 // then the current object (defined below) shall have array
1886 // type and the expression shall be an integer constant
1887 // expression. If the array is of unknown size, any
1888 // nonnegative value is valid.
1889 //
1890 // Additionally, cope with the GNU extension that permits
1891 // designators of the form
1892 //
1893 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001894 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001895 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001896 if (!VerifyOnly)
1897 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1898 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001899 ++Index;
1900 return true;
1901 }
1902
1903 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001904 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1905 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001906 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00001907 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001908 DesignatedEndIndex = DesignatedStartIndex;
1909 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001910 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001911
Mike Stump11289f42009-09-09 15:08:12 +00001912 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001913 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001914 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00001915 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001916 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001917
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001918 // Codegen can't handle evaluating array range designators that have side
1919 // effects, because we replicate the AST value for each initialized element.
1920 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1921 // elements with something that has a side effect, so codegen can emit an
1922 // "error unsupported" error instead of miscompiling the app.
1923 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001924 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001925 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001926 }
1927
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001928 if (isa<ConstantArrayType>(AT)) {
1929 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001930 DesignatedStartIndex
1931 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001932 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001933 DesignatedEndIndex
1934 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001935 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1936 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00001937 if (!VerifyOnly)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001938 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1939 diag::err_array_designator_too_large)
1940 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1941 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001942 ++Index;
1943 return true;
1944 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001945 } else {
1946 // Make sure the bit-widths and signedness match.
1947 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001948 DesignatedEndIndex
1949 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001950 else if (DesignatedStartIndex.getBitWidth() <
1951 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001952 DesignatedStartIndex
1953 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001954 DesignatedStartIndex.setIsUnsigned(true);
1955 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001956 }
Mike Stump11289f42009-09-09 15:08:12 +00001957
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001958 // Make sure that our non-designated initializer list has space
1959 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001960 if (!VerifyOnly &&
1961 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001962 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001963 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001964
Douglas Gregor17bd0942009-01-28 23:36:17 +00001965 // Repeatedly perform subobject initializations in the range
1966 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001967
Douglas Gregor17bd0942009-01-28 23:36:17 +00001968 // Move to the next designator
1969 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1970 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001972 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001973 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001974
Douglas Gregor17bd0942009-01-28 23:36:17 +00001975 while (DesignatedStartIndex <= DesignatedEndIndex) {
1976 // Recurse to check later designated subobjects.
1977 QualType ElementType = AT->getElementType();
1978 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001980 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1982 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001983 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001984 (DesignatedStartIndex == DesignatedEndIndex),
1985 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001986 return true;
1987
1988 // Move to the next index in the array that we'll be initializing.
1989 ++DesignatedStartIndex;
1990 ElementIndex = DesignatedStartIndex.getZExtValue();
1991 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001992
1993 // If this the first designator, our caller will continue checking
1994 // the rest of this array subobject.
1995 if (IsFirstDesignator) {
1996 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001997 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001998 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001999 return false;
2000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregor17bd0942009-01-28 23:36:17 +00002002 if (!FinishSubobjectInit)
2003 return false;
2004
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002005 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002006 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002008 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002009 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002010 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002011}
2012
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002013// Get the structured initializer list for a subobject of type
2014// @p CurrentObjectType.
2015InitListExpr *
2016InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2017 QualType CurrentObjectType,
2018 InitListExpr *StructuredList,
2019 unsigned StructuredIndex,
2020 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002021 if (VerifyOnly)
2022 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002023 Expr *ExistingInit = 0;
2024 if (!StructuredList)
2025 ExistingInit = SyntacticToSemantic[IList];
2026 else if (StructuredIndex < StructuredList->getNumInits())
2027 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002028
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002029 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2030 return Result;
2031
2032 if (ExistingInit) {
2033 // We are creating an initializer list that initializes the
2034 // subobjects of the current object, but there was already an
2035 // initialization that completely initialized the current
2036 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002037 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002038 // struct X { int a, b; };
2039 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002040 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002041 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2042 // designated initializer re-initializes the whole
2043 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002044 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002045 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002046 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00002047 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002048 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002049 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002050 << ExistingInit->getSourceRange();
2051 }
2052
Mike Stump11289f42009-09-09 15:08:12 +00002053 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002054 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2055 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00002056 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002057
Douglas Gregora8a089b2010-07-13 18:40:04 +00002058 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002059
Douglas Gregor6d00c992009-03-20 23:58:33 +00002060 // Pre-allocate storage for the structured initializer list.
2061 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002062 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002063 bool GotNumInits = false;
2064 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002065 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002066 GotNumInits = true;
2067 } else if (Index < IList->getNumInits()) {
2068 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002069 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002070 GotNumInits = true;
2071 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002072 }
2073
Mike Stump11289f42009-09-09 15:08:12 +00002074 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002075 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2076 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2077 NumElements = CAType->getSize().getZExtValue();
2078 // Simple heuristic so that we don't allocate a very large
2079 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002080 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002081 NumElements = 0;
2082 }
John McCall9dd450b2009-09-21 23:43:11 +00002083 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002084 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002085 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002086 RecordDecl *RDecl = RType->getDecl();
2087 if (RDecl->isUnion())
2088 NumElements = 1;
2089 else
Mike Stump11289f42009-09-09 15:08:12 +00002090 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002091 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002092 }
2093
Ted Kremenekac034612010-04-13 23:39:13 +00002094 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002095
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002096 // Link this new initializer list into the structured initializer
2097 // lists.
2098 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002099 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002100 else {
2101 Result->setSyntacticForm(IList);
2102 SyntacticToSemantic[IList] = Result;
2103 }
2104
2105 return Result;
2106}
2107
2108/// Update the initializer at index @p StructuredIndex within the
2109/// structured initializer list to the value @p expr.
2110void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2111 unsigned &StructuredIndex,
2112 Expr *expr) {
2113 // No structured initializer list to update
2114 if (!StructuredList)
2115 return;
2116
Ted Kremenekac034612010-04-13 23:39:13 +00002117 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2118 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002119 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00002120 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 diag::warn_initializer_overrides)
2122 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002123 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002124 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002125 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002126 << PrevInit->getSourceRange();
2127 }
Mike Stump11289f42009-09-09 15:08:12 +00002128
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002129 ++StructuredIndex;
2130}
2131
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002132/// Check that the given Index expression is a valid array designator
2133/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002134/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002135/// and produces a reasonable diagnostic if there is a
2136/// failure. Returns true if there was an error, false otherwise. If
2137/// everything went okay, Value will receive the value of the constant
2138/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002139static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002140CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002141 SourceLocation Loc = Index->getSourceRange().getBegin();
2142
2143 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002144 if (S.VerifyIntegerConstantExpression(Index, &Value))
2145 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002146
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002147 if (Value.isSigned() && Value.isNegative())
2148 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002149 << Value.toString(10) << Index->getSourceRange();
2150
Douglas Gregor51650d32009-01-23 21:04:18 +00002151 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002152 return false;
2153}
2154
John McCalldadc5752010-08-24 06:29:42 +00002155ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002156 SourceLocation Loc,
2157 bool GNUSyntax,
2158 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002159 typedef DesignatedInitExpr::Designator ASTDesignator;
2160
2161 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002162 SmallVector<ASTDesignator, 32> Designators;
2163 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002164
2165 // Build designators and check array designator expressions.
2166 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2167 const Designator &D = Desig.getDesignator(Idx);
2168 switch (D.getKind()) {
2169 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002170 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002171 D.getFieldLoc()));
2172 break;
2173
2174 case Designator::ArrayDesignator: {
2175 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2176 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002177 if (!Index->isTypeDependent() &&
2178 !Index->isValueDependent() &&
2179 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002180 Invalid = true;
2181 else {
2182 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002183 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002184 D.getRBracketLoc()));
2185 InitExpressions.push_back(Index);
2186 }
2187 break;
2188 }
2189
2190 case Designator::ArrayRangeDesignator: {
2191 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2192 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2193 llvm::APSInt StartValue;
2194 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002195 bool StartDependent = StartIndex->isTypeDependent() ||
2196 StartIndex->isValueDependent();
2197 bool EndDependent = EndIndex->isTypeDependent() ||
2198 EndIndex->isValueDependent();
2199 if ((!StartDependent &&
2200 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2201 (!EndDependent &&
2202 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002203 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002204 else {
2205 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002206 if (StartDependent || EndDependent) {
2207 // Nothing to compute.
2208 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002209 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002210 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002211 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002212
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002213 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002214 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002215 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002216 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2217 Invalid = true;
2218 } else {
2219 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002220 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002221 D.getEllipsisLoc(),
2222 D.getRBracketLoc()));
2223 InitExpressions.push_back(StartIndex);
2224 InitExpressions.push_back(EndIndex);
2225 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002226 }
2227 break;
2228 }
2229 }
2230 }
2231
2232 if (Invalid || Init.isInvalid())
2233 return ExprError();
2234
2235 // Clear out the expressions within the designation.
2236 Desig.ClearExprs(*this);
2237
2238 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002239 = DesignatedInitExpr::Create(Context,
2240 Designators.data(), Designators.size(),
2241 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002242 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243
Douglas Gregorc124e592011-01-16 16:13:16 +00002244 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002245 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2246 << DIE->getSourceRange();
2247 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002248 Diag(DIE->getLocStart(), diag::ext_designated_init)
2249 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002250
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002251 return Owned(DIE);
2252}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002253
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002254//===----------------------------------------------------------------------===//
2255// Initialization entity
2256//===----------------------------------------------------------------------===//
2257
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002258InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002259 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002261{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002262 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2263 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002264 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002265 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002266 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002267 Type = VT->getElementType();
2268 } else {
2269 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2270 assert(CT && "Unexpected type");
2271 Kind = EK_ComplexElement;
2272 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002273 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002274}
2275
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002276InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002277 CXXBaseSpecifier *Base,
2278 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002279{
2280 InitializedEntity Result;
2281 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002282 Result.Base = reinterpret_cast<uintptr_t>(Base);
2283 if (IsInheritedVirtualBase)
2284 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002285
Douglas Gregor1b303932009-12-22 15:35:07 +00002286 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002287 return Result;
2288}
2289
Douglas Gregor85dabae2009-12-16 01:38:02 +00002290DeclarationName InitializedEntity::getName() const {
2291 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002292 case EK_Parameter: {
2293 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2294 return (D ? D->getDeclName() : DeclarationName());
2295 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002296
2297 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002298 case EK_Member:
2299 return VariableOrMember->getDeclName();
2300
2301 case EK_Result:
2302 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002303 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002304 case EK_Temporary:
2305 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002306 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002307 case EK_ArrayElement:
2308 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002309 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002310 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002311 return DeclarationName();
2312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002313
Douglas Gregor85dabae2009-12-16 01:38:02 +00002314 // Silence GCC warning
2315 return DeclarationName();
2316}
2317
Douglas Gregora4b592a2009-12-19 03:01:41 +00002318DeclaratorDecl *InitializedEntity::getDecl() const {
2319 switch (getKind()) {
2320 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002321 case EK_Member:
2322 return VariableOrMember;
2323
John McCall31168b02011-06-15 23:02:42 +00002324 case EK_Parameter:
2325 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2326
Douglas Gregora4b592a2009-12-19 03:01:41 +00002327 case EK_Result:
2328 case EK_Exception:
2329 case EK_New:
2330 case EK_Temporary:
2331 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002332 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002333 case EK_ArrayElement:
2334 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002335 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002336 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002337 return 0;
2338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002339
Douglas Gregora4b592a2009-12-19 03:01:41 +00002340 // Silence GCC warning
2341 return 0;
2342}
2343
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002344bool InitializedEntity::allowsNRVO() const {
2345 switch (getKind()) {
2346 case EK_Result:
2347 case EK_Exception:
2348 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002349
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002350 case EK_Variable:
2351 case EK_Parameter:
2352 case EK_Member:
2353 case EK_New:
2354 case EK_Temporary:
2355 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002356 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002357 case EK_ArrayElement:
2358 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002359 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002360 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002361 break;
2362 }
2363
2364 return false;
2365}
2366
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002367//===----------------------------------------------------------------------===//
2368// Initialization sequence
2369//===----------------------------------------------------------------------===//
2370
2371void InitializationSequence::Step::Destroy() {
2372 switch (Kind) {
2373 case SK_ResolveAddressOfOverloadedFunction:
2374 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002375 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002376 case SK_CastDerivedToBaseLValue:
2377 case SK_BindReference:
2378 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002379 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002380 case SK_UserConversion:
2381 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002382 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002384 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002385 case SK_ListConstructorCall:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002386 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002387 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002388 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002389 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002390 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002391 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002392 case SK_PassByIndirectCopyRestore:
2393 case SK_PassByIndirectRestore:
2394 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002395 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002396
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002397 case SK_ConversionSequence:
2398 delete ICS;
2399 }
2400}
2401
Douglas Gregor838fcc32010-03-26 20:14:36 +00002402bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002403 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002404}
2405
2406bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002407 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002408 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002409
Douglas Gregor838fcc32010-03-26 20:14:36 +00002410 switch (getFailureKind()) {
2411 case FK_TooManyInitsForReference:
2412 case FK_ArrayNeedsInitList:
2413 case FK_ArrayNeedsInitListOrStringLiteral:
2414 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2415 case FK_NonConstLValueReferenceBindingToTemporary:
2416 case FK_NonConstLValueReferenceBindingToUnrelated:
2417 case FK_RValueReferenceBindingToLValue:
2418 case FK_ReferenceInitDropsQualifiers:
2419 case FK_ReferenceInitFailed:
2420 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002421 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002422 case FK_TooManyInitsForScalar:
2423 case FK_ReferenceBindingToInitList:
2424 case FK_InitListBadDestinationType:
2425 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002426 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002427 case FK_ArrayTypeMismatch:
2428 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002429 case FK_ListInitializationFailed:
John McCall4124c492011-10-17 18:40:02 +00002430 case FK_PlaceholderType:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002431 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432
Douglas Gregor838fcc32010-03-26 20:14:36 +00002433 case FK_ReferenceInitOverloadFailed:
2434 case FK_UserConversionOverloadFailed:
2435 case FK_ConstructorOverloadFailed:
2436 return FailedOverloadResult == OR_Ambiguous;
2437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438
Douglas Gregor838fcc32010-03-26 20:14:36 +00002439 return false;
2440}
2441
Douglas Gregorb33eed02010-04-16 22:09:46 +00002442bool InitializationSequence::isConstructorInitialization() const {
2443 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2444}
2445
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002446bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2447 const Expr *Initializer,
2448 bool *isInitializerConstant,
2449 APValue *ConstantValue) const {
2450 if (Steps.empty() || Initializer->isValueDependent())
2451 return false;
2452
2453 const Step &LastStep = Steps.back();
2454 if (LastStep.Kind != SK_ConversionSequence)
2455 return false;
2456
2457 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2458 const StandardConversionSequence *SCS = NULL;
2459 switch (ICS.getKind()) {
2460 case ImplicitConversionSequence::StandardConversion:
2461 SCS = &ICS.Standard;
2462 break;
2463 case ImplicitConversionSequence::UserDefinedConversion:
2464 SCS = &ICS.UserDefined.After;
2465 break;
2466 case ImplicitConversionSequence::AmbiguousConversion:
2467 case ImplicitConversionSequence::EllipsisConversion:
2468 case ImplicitConversionSequence::BadConversion:
2469 return false;
2470 }
2471
2472 // Check if SCS represents a narrowing conversion, according to C++0x
2473 // [dcl.init.list]p7:
2474 //
2475 // A narrowing conversion is an implicit conversion ...
2476 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2477 QualType FromType = SCS->getToType(0);
2478 QualType ToType = SCS->getToType(1);
2479 switch (PossibleNarrowing) {
2480 // * from a floating-point type to an integer type, or
2481 //
2482 // * from an integer type or unscoped enumeration type to a floating-point
2483 // type, except where the source is a constant expression and the actual
2484 // value after conversion will fit into the target type and will produce
2485 // the original value when converted back to the original type, or
2486 case ICK_Floating_Integral:
2487 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2488 *isInitializerConstant = false;
2489 return true;
2490 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2491 llvm::APSInt IntConstantValue;
2492 if (Initializer &&
2493 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2494 // Convert the integer to the floating type.
2495 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2496 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2497 llvm::APFloat::rmNearestTiesToEven);
2498 // And back.
2499 llvm::APSInt ConvertedValue = IntConstantValue;
2500 bool ignored;
2501 Result.convertToInteger(ConvertedValue,
2502 llvm::APFloat::rmTowardZero, &ignored);
2503 // If the resulting value is different, this was a narrowing conversion.
2504 if (IntConstantValue != ConvertedValue) {
2505 *isInitializerConstant = true;
2506 *ConstantValue = APValue(IntConstantValue);
2507 return true;
2508 }
2509 } else {
2510 // Variables are always narrowings.
2511 *isInitializerConstant = false;
2512 return true;
2513 }
2514 }
2515 return false;
2516
2517 // * from long double to double or float, or from double to float, except
2518 // where the source is a constant expression and the actual value after
2519 // conversion is within the range of values that can be represented (even
2520 // if it cannot be represented exactly), or
2521 case ICK_Floating_Conversion:
2522 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2523 // FromType is larger than ToType.
2524 Expr::EvalResult InitializerValue;
2525 // FIXME: Check whether Initializer is a constant expression according
2526 // to C++0x [expr.const], rather than just whether it can be folded.
2527 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2528 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2529 // Constant! (Except for FIXME above.)
2530 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2531 // Convert the source value into the target type.
2532 bool ignored;
2533 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2534 Ctx.getFloatTypeSemantics(ToType),
2535 llvm::APFloat::rmNearestTiesToEven, &ignored);
2536 // If there was no overflow, the source value is within the range of
2537 // values that can be represented.
2538 if (ConvertStatus & llvm::APFloat::opOverflow) {
2539 *isInitializerConstant = true;
2540 *ConstantValue = InitializerValue.Val;
2541 return true;
2542 }
2543 } else {
2544 *isInitializerConstant = false;
2545 return true;
2546 }
2547 }
2548 return false;
2549
2550 // * from an integer type or unscoped enumeration type to an integer type
2551 // that cannot represent all the values of the original type, except where
2552 // the source is a constant expression and the actual value after
2553 // conversion will fit into the target type and will produce the original
2554 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002555 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002556 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2557 // Boolean conversions can be from pointers and pointers to members
2558 // [conv.bool], and those aren't considered narrowing conversions.
2559 return false;
2560 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002561 case ICK_Integral_Conversion: {
2562 assert(FromType->isIntegralOrUnscopedEnumerationType());
2563 assert(ToType->isIntegralOrUnscopedEnumerationType());
2564 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2565 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2566 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2567 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2568
2569 if (FromWidth > ToWidth ||
2570 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2571 // Not all values of FromType can be represented in ToType.
2572 llvm::APSInt InitializerValue;
2573 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2574 *isInitializerConstant = true;
2575 *ConstantValue = APValue(InitializerValue);
2576
2577 // Add a bit to the InitializerValue so we don't have to worry about
2578 // signed vs. unsigned comparisons.
2579 InitializerValue = InitializerValue.extend(
2580 InitializerValue.getBitWidth() + 1);
2581 // Convert the initializer to and from the target width and signed-ness.
2582 llvm::APSInt ConvertedValue = InitializerValue;
2583 ConvertedValue = ConvertedValue.trunc(ToWidth);
2584 ConvertedValue.setIsSigned(ToSigned);
2585 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2586 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2587 // If the result is different, this was a narrowing conversion.
2588 return ConvertedValue != InitializerValue;
2589 } else {
2590 // Variables are always narrowings.
2591 *isInitializerConstant = false;
2592 return true;
2593 }
2594 }
2595 return false;
2596 }
2597
2598 default:
2599 // Other kinds of conversions are not narrowings.
2600 return false;
2601 }
2602}
2603
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002604void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002605 FunctionDecl *Function,
2606 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002607 Step S;
2608 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2609 S.Type = Function->getType();
Benjamin Kramerec440992011-10-09 17:58:25 +00002610 S.Function.HadMultipleCandidates = false;
John McCalla0296f72010-03-19 07:35:19 +00002611 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002612 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002613 Steps.push_back(S);
2614}
2615
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002617 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002618 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002619 switch (VK) {
2620 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2621 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2622 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002623 default: llvm_unreachable("No such category");
2624 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002625 S.Type = BaseType;
2626 Steps.push_back(S);
2627}
2628
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002629void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002630 bool BindingTemporary) {
2631 Step S;
2632 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002637void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2638 Step S;
2639 S.Kind = SK_ExtraneousCopyToTemporary;
2640 S.Type = T;
2641 Steps.push_back(S);
2642}
2643
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002644void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002645 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002646 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002647 Step S;
2648 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002649 S.Type = T;
Benjamin Kramerec440992011-10-09 17:58:25 +00002650 S.Function.HadMultipleCandidates = false;
John McCalla0296f72010-03-19 07:35:19 +00002651 S.Function.Function = Function;
2652 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002653 Steps.push_back(S);
2654}
2655
2656void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002657 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002658 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002659 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002660 switch (VK) {
2661 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002662 S.Kind = SK_QualificationConversionRValue;
2663 break;
John McCall2536c6d2010-08-25 10:28:54 +00002664 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002665 S.Kind = SK_QualificationConversionXValue;
2666 break;
John McCall2536c6d2010-08-25 10:28:54 +00002667 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002668 S.Kind = SK_QualificationConversionLValue;
2669 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002670 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002671 S.Type = Ty;
2672 Steps.push_back(S);
2673}
2674
2675void InitializationSequence::AddConversionSequenceStep(
2676 const ImplicitConversionSequence &ICS,
2677 QualType T) {
2678 Step S;
2679 S.Kind = SK_ConversionSequence;
2680 S.Type = T;
2681 S.ICS = new ImplicitConversionSequence(ICS);
2682 Steps.push_back(S);
2683}
2684
Douglas Gregor51e77d52009-12-10 17:56:55 +00002685void InitializationSequence::AddListInitializationStep(QualType T) {
2686 Step S;
2687 S.Kind = SK_ListInitialization;
2688 S.Type = T;
2689 Steps.push_back(S);
2690}
2691
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002692void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002693InitializationSequence::AddConstructorInitializationStep(
2694 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002695 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002696 QualType T) {
2697 Step S;
2698 S.Kind = SK_ConstructorInitialization;
2699 S.Type = T;
Benjamin Kramerec440992011-10-09 17:58:25 +00002700 S.Function.HadMultipleCandidates = false;
John McCalla0296f72010-03-19 07:35:19 +00002701 S.Function.Function = Constructor;
2702 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002703 Steps.push_back(S);
2704}
2705
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002706void InitializationSequence::AddZeroInitializationStep(QualType T) {
2707 Step S;
2708 S.Kind = SK_ZeroInitialization;
2709 S.Type = T;
2710 Steps.push_back(S);
2711}
2712
Douglas Gregore1314a62009-12-18 05:02:21 +00002713void InitializationSequence::AddCAssignmentStep(QualType T) {
2714 Step S;
2715 S.Kind = SK_CAssignment;
2716 S.Type = T;
2717 Steps.push_back(S);
2718}
2719
Eli Friedman78275202009-12-19 08:11:05 +00002720void InitializationSequence::AddStringInitStep(QualType T) {
2721 Step S;
2722 S.Kind = SK_StringInit;
2723 S.Type = T;
2724 Steps.push_back(S);
2725}
2726
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002727void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2728 Step S;
2729 S.Kind = SK_ObjCObjectConversion;
2730 S.Type = T;
2731 Steps.push_back(S);
2732}
2733
Douglas Gregore2f943b2011-02-22 18:29:51 +00002734void InitializationSequence::AddArrayInitStep(QualType T) {
2735 Step S;
2736 S.Kind = SK_ArrayInit;
2737 S.Type = T;
2738 Steps.push_back(S);
2739}
2740
John McCall31168b02011-06-15 23:02:42 +00002741void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2742 bool shouldCopy) {
2743 Step s;
2744 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2745 : SK_PassByIndirectRestore);
2746 s.Type = type;
2747 Steps.push_back(s);
2748}
2749
2750void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2751 Step S;
2752 S.Kind = SK_ProduceObjCObject;
2753 S.Type = T;
2754 Steps.push_back(S);
2755}
2756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002757void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002758 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002759 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002760 this->Failure = Failure;
2761 this->FailedOverloadResult = Result;
2762}
2763
2764//===----------------------------------------------------------------------===//
2765// Attempt initialization
2766//===----------------------------------------------------------------------===//
2767
John McCall31168b02011-06-15 23:02:42 +00002768static void MaybeProduceObjCObject(Sema &S,
2769 InitializationSequence &Sequence,
2770 const InitializedEntity &Entity) {
2771 if (!S.getLangOptions().ObjCAutoRefCount) return;
2772
2773 /// When initializing a parameter, produce the value if it's marked
2774 /// __attribute__((ns_consumed)).
2775 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2776 if (!Entity.isParameterConsumed())
2777 return;
2778
2779 assert(Entity.getType()->isObjCRetainableType() &&
2780 "consuming an object of unretainable type?");
2781 Sequence.AddProduceObjCObjectStep(Entity.getType());
2782
2783 /// When initializing a return value, if the return type is a
2784 /// retainable type, then returns need to immediately retain the
2785 /// object. If an autorelease is required, it will be done at the
2786 /// last instant.
2787 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2788 if (!Entity.getType()->isObjCRetainableType())
2789 return;
2790
2791 Sequence.AddProduceObjCObjectStep(Entity.getType());
2792 }
2793}
2794
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002795/// \brief Attempt list initialization (C++0x [dcl.init.list])
2796static void TryListInitialization(Sema &S,
2797 const InitializedEntity &Entity,
2798 const InitializationKind &Kind,
2799 InitListExpr *InitList,
2800 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002801 QualType DestType = Entity.getType();
2802
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002803 // C++ doesn't allow scalar initialization with more than one argument.
2804 // But C99 complex numbers are scalars and it makes sense there.
2805 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2806 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2807 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2808 return;
2809 }
2810 // FIXME: C++0x defines behavior for these two cases.
2811 if (DestType->isReferenceType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002812 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2813 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002814 }
2815 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002816 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002817 return;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002818 }
2819
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002820 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00002821 DestType, /*VerifyOnly=*/true,
2822 Kind.getKind() != InitializationKind::IK_Direct ||
2823 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002824 if (CheckInitList.HadError()) {
2825 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2826 return;
2827 }
2828
2829 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002830 Sequence.AddListInitializationStep(DestType);
2831}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002832
2833/// \brief Try a reference initialization that involves calling a conversion
2834/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002835static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2836 const InitializedEntity &Entity,
2837 const InitializationKind &Kind,
2838 Expr *Initializer,
2839 bool AllowRValues,
2840 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002841 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002842 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2843 QualType T1 = cv1T1.getUnqualifiedType();
2844 QualType cv2T2 = Initializer->getType();
2845 QualType T2 = cv2T2.getUnqualifiedType();
2846
2847 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002848 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002849 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002850 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002851 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002852 ObjCConversion,
2853 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002854 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002855 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002856 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002857 (void)ObjCLifetimeConversion;
2858
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002859 // Build the candidate set directly in the initialization sequence
2860 // structure, so that it will persist if we fail.
2861 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2862 CandidateSet.clear();
2863
2864 // Determine whether we are allowed to call explicit constructors or
2865 // explicit conversion operators.
2866 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002868 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002869 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2870 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002871 // The type we're converting to is a class type. Enumerate its constructors
2872 // to see if there is a suitable conversion.
2873 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002874
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002875 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002876 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002877 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002878 NamedDecl *D = *Con;
2879 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2880
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002881 // Find the constructor (which may be a template).
2882 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002883 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002884 if (ConstructorTmpl)
2885 Constructor = cast<CXXConstructorDecl>(
2886 ConstructorTmpl->getTemplatedDecl());
2887 else
John McCalla0296f72010-03-19 07:35:19 +00002888 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002890 if (!Constructor->isInvalidDecl() &&
2891 Constructor->isConvertingConstructor(AllowExplicit)) {
2892 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002893 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002894 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002895 &Initializer, 1, CandidateSet,
2896 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002897 else
John McCalla0296f72010-03-19 07:35:19 +00002898 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002899 &Initializer, 1, CandidateSet,
2900 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002901 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002903 }
John McCall3696dcb2010-08-17 07:23:57 +00002904 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2905 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002906
Douglas Gregor496e8b342010-05-07 19:42:26 +00002907 const RecordType *T2RecordType = 0;
2908 if ((T2RecordType = T2->getAs<RecordType>()) &&
2909 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002910 // The type we're converting from is a class type, enumerate its conversion
2911 // functions.
2912 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2913
John McCallad371252010-01-20 00:46:10 +00002914 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002915 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002916 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2917 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002918 NamedDecl *D = *I;
2919 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2920 if (isa<UsingShadowDecl>(D))
2921 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002923 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2924 CXXConversionDecl *Conv;
2925 if (ConvTemplate)
2926 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2927 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002928 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002930 // If the conversion function doesn't return a reference type,
2931 // it can't be considered for this conversion unless we're allowed to
2932 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933 // FIXME: Do we need to make sure that we only consider conversion
2934 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002935 // break recursion.
2936 if ((AllowExplicit || !Conv->isExplicit()) &&
2937 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2938 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002939 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002940 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002941 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002942 else
John McCalla0296f72010-03-19 07:35:19 +00002943 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002944 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002945 }
2946 }
2947 }
John McCall3696dcb2010-08-17 07:23:57 +00002948 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2949 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002951 SourceLocation DeclLoc = Initializer->getLocStart();
2952
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002954 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002956 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002957 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002958
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002959 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002960
Chandler Carruth30141632011-02-25 19:41:05 +00002961 // This is the overload that will actually be used for the initialization, so
2962 // mark it as used.
2963 S.MarkDeclarationReferenced(DeclLoc, Function);
2964
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002965 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002966 if (isa<CXXConversionDecl>(Function))
2967 T2 = Function->getResultType();
2968 else
2969 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002970
2971 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002972 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002973 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002974
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002976 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002977 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002978 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002979 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002980 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002981 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002982
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002983 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002984 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002985 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002986 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002988 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002989 NewDerivedToBase, NewObjCConversion,
2990 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002991 if (NewRefRelationship == Sema::Ref_Incompatible) {
2992 // If the type we've converted to is not reference-related to the
2993 // type we're looking for, then there is another conversion step
2994 // we need to perform to produce a temporary of the right type
2995 // that we'll be binding to.
2996 ImplicitConversionSequence ICS;
2997 ICS.setStandard();
2998 ICS.Standard = Best->FinalConversion;
2999 T2 = ICS.Standard.getToType(2);
3000 Sequence.AddConversionSequenceStep(ICS, T2);
3001 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003002 Sequence.AddDerivedToBaseCastStep(
3003 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003004 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003005 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003006 else if (NewObjCConversion)
3007 Sequence.AddObjCObjectConversionStep(
3008 S.Context.getQualifiedType(T1,
3009 T2.getNonReferenceType().getQualifiers()));
3010
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003011 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003012 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003013
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003014 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3015 return OR_Success;
3016}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017
3018/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3019static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003020 const InitializedEntity &Entity,
3021 const InitializationKind &Kind,
3022 Expr *Initializer,
3023 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003024 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003025 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003026 Qualifiers T1Quals;
3027 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003028 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003029 Qualifiers T2Quals;
3030 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003031 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00003032
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003033 // If the initializer is the address of an overloaded function, try
3034 // to resolve the overloaded function. If all goes well, T2 is the
3035 // type of the resulting function.
3036 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00003037 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003038 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00003039 T1,
3040 false,
3041 Found)) {
3042 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
3043 cv2T2 = Fn->getType();
3044 T2 = cv2T2.getUnqualifiedType();
3045 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003046 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3047 return;
3048 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003049 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003050
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003051 // Compute some basic properties of the types and the initializer.
3052 bool isLValueRef = DestType->isLValueReferenceType();
3053 bool isRValueRef = !isLValueRef;
3054 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003055 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003056 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003057 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003058 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003059 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003060 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003061
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003062 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003064 // "cv2 T2" as follows:
3065 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003066 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003067 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00003068 // Note the analogous bullet points for rvlaue refs to functions. Because
3069 // there are no function rvalues in C++, rvalue refs to functions are treated
3070 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003071 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003072 bool T1Function = T1->isFunctionType();
3073 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003075 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003076 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003077 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003078 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003079 // reference-compatible with "cv2 T2," or
3080 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003082 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003083 // can occur. However, we do pay attention to whether it is a bit-field
3084 // to decide whether we're actually binding to a temporary created from
3085 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003086 if (DerivedToBase)
3087 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003089 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003090 else if (ObjCConversion)
3091 Sequence.AddObjCObjectConversionStep(
3092 S.Context.getQualifiedType(T1, T2Quals));
3093
Chandler Carruth04bdce62010-01-12 20:32:25 +00003094 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00003095 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003096 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003097 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003098 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003099 return;
3100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
3102 // - has a class type (i.e., T2 is a class type), where T1 is not
3103 // reference-related to T2, and can be implicitly converted to an
3104 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3105 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003106 // applicable conversion functions (13.3.1.6) and choosing the best
3107 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003108 // If we have an rvalue ref to function type here, the rhs must be
3109 // an rvalue.
3110 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3111 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003113 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00003114 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003115 Sequence);
3116 if (ConvOvlResult == OR_Success)
3117 return;
John McCall0d1da222010-01-12 00:44:57 +00003118 if (ConvOvlResult != OR_No_Viable_Function) {
3119 Sequence.SetOverloadFailure(
3120 InitializationSequence::FK_ReferenceInitOverloadFailed,
3121 ConvOvlResult);
3122 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003123 }
3124 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003125
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003126 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003127 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003128 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003129 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003130 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3131 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3132 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133 Sequence.SetOverloadFailure(
3134 InitializationSequence::FK_ReferenceInitOverloadFailed,
3135 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003136 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003137 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138 ? (RefRelationship == Sema::Ref_Related
3139 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3140 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3141 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003142
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003143 return;
3144 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003145
Douglas Gregor92e460e2011-01-20 16:44:54 +00003146 // - If the initializer expression
3147 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3148 // "cv1 T1" is reference-compatible with "cv2 T2"
3149 // Note: functions are handled below.
3150 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003151 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003153 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003154 (InitCategory.isXValue() ||
3155 (InitCategory.isPRValue() && T2->isRecordType()) ||
3156 (InitCategory.isPRValue() && T2->isArrayType()))) {
3157 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3158 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003159 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3160 // compiler the freedom to perform a copy here or bind to the
3161 // object, while C++0x requires that we bind directly to the
3162 // object. Hence, we always bind to the object without making an
3163 // extra copy. However, in C++03 requires that we check for the
3164 // presence of a suitable copy constructor:
3165 //
3166 // The constructor that would be used to make the copy shall
3167 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003168 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003169 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor92e460e2011-01-20 16:44:54 +00003172 if (DerivedToBase)
3173 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3174 ValueKind);
3175 else if (ObjCConversion)
3176 Sequence.AddObjCObjectConversionStep(
3177 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
Douglas Gregor92e460e2011-01-20 16:44:54 +00003179 if (T1Quals != T2Quals)
3180 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00003182 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003183 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
3186 // - has a class type (i.e., T2 is a class type), where T1 is not
3187 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003188 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3189 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003190 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003191 if (RefRelationship == Sema::Ref_Incompatible) {
3192 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3193 Kind, Initializer,
3194 /*AllowRValues=*/true,
3195 Sequence);
3196 if (ConvOvlResult)
3197 Sequence.SetOverloadFailure(
3198 InitializationSequence::FK_ReferenceInitOverloadFailed,
3199 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003201 return;
3202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003204 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3205 return;
3206 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003207
3208 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003209 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003211 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003212
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003213 // Determine whether we are allowed to call explicit constructors or
3214 // explicit conversion operators.
3215 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003216
3217 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3218
John McCall31168b02011-06-15 23:02:42 +00003219 ImplicitConversionSequence ICS
3220 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003221 /*SuppressUserConversions*/ false,
3222 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003223 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003224 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3225 /*AllowObjCWritebackConversion=*/false);
3226
3227 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003228 // FIXME: Use the conversion function set stored in ICS to turn
3229 // this into an overloading ambiguity diagnostic. However, we need
3230 // to keep that set as an OverloadCandidateSet rather than as some
3231 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003232 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3233 Sequence.SetOverloadFailure(
3234 InitializationSequence::FK_ReferenceInitOverloadFailed,
3235 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003236 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3237 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003238 else
3239 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003240 return;
John McCall31168b02011-06-15 23:02:42 +00003241 } else {
3242 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 }
3244
3245 // [...] If T1 is reference-related to T2, cv1 must be the
3246 // same cv-qualification as, or greater cv-qualification
3247 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003248 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3249 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003251 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003252 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3253 return;
3254 }
3255
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003257 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003259 InitCategory.isLValue()) {
3260 Sequence.SetFailed(
3261 InitializationSequence::FK_RValueReferenceBindingToLValue);
3262 return;
3263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003264
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003265 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3266 return;
3267}
3268
3269/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003270/// (C++ [dcl.init.string], C99 6.7.8).
3271static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003272 const InitializedEntity &Entity,
3273 const InitializationKind &Kind,
3274 Expr *Initializer,
3275 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003276 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003277}
3278
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3280/// enumerates the constructors of the initialized entity and performs overload
3281/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003282static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003283 const InitializedEntity &Entity,
3284 const InitializationKind &Kind,
3285 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003286 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003287 InitializationSequence &Sequence) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00003288 // Check constructor arguments for self reference.
3289 if (DeclaratorDecl *DD = Entity.getDecl())
3290 // Parameters arguments are occassionially constructed with itself,
3291 // for instance, in recursive functions. Skip them.
3292 if (!isa<ParmVarDecl>(DD))
3293 for (unsigned i = 0; i < NumArgs; ++i)
3294 S.CheckSelfReference(DD, Args[i]);
3295
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003296 // Build the candidate set directly in the initialization sequence
3297 // structure, so that it will persist if we fail.
3298 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3299 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003301 // Determine whether we are allowed to call explicit constructors or
3302 // explicit conversion operators.
3303 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3304 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003305 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003306
3307 // The type we're constructing needs to be complete.
3308 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003309 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003310 return;
3311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003313 // The type we're converting to is a class type. Enumerate its constructors
3314 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003315 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003317 CXXRecordDecl *DestRecordDecl
3318 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003320 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003321 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003322 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003323 NamedDecl *D = *Con;
3324 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003325 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003326
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003327 // Find the constructor (which may be a template).
3328 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003329 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003330 if (ConstructorTmpl)
3331 Constructor = cast<CXXConstructorDecl>(
3332 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003333 else {
John McCalla0296f72010-03-19 07:35:19 +00003334 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003335
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003337 // suppress user-defined conversions on the arguments.
3338 // FIXME: Move constructors?
3339 if (Kind.getKind() == InitializationKind::IK_Copy &&
3340 Constructor->isCopyConstructor())
3341 SuppressUserConversions = true;
3342 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003344 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003345 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003346 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003347 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003348 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003349 Args, NumArgs, CandidateSet,
3350 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003351 else
John McCalla0296f72010-03-19 07:35:19 +00003352 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003353 Args, NumArgs, CandidateSet,
3354 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356 }
3357
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003358 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359
3360 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003361 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003363 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003364 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003366 Result);
3367 return;
3368 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003369
3370 // C++0x [dcl.init]p6:
3371 // If a program calls for the default initialization of an object
3372 // of a const-qualified type T, T shall be a class type with a
3373 // user-provided default constructor.
3374 if (Kind.getKind() == InitializationKind::IK_Default &&
3375 Entity.getType().isConstQualified() &&
3376 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3377 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3378 return;
3379 }
3380
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003381 // Add the constructor initialization step. Any cv-qualification conversion is
3382 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003383 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003385 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003386 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003387}
3388
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003389/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003391 const InitializedEntity &Entity,
3392 const InitializationKind &Kind,
3393 InitializationSequence &Sequence) {
3394 // C++ [dcl.init]p5:
3395 //
3396 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003397 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003399 // -- if T is an array type, then each element is value-initialized;
3400 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3401 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003403 if (const RecordType *RT = T->getAs<RecordType>()) {
3404 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3405 // -- if T is a class type (clause 9) with a user-declared
3406 // constructor (12.1), then the default constructor for T is
3407 // called (and the initialization is ill-formed if T has no
3408 // accessible default constructor);
3409 //
3410 // FIXME: we really want to refer to a single subobject of the array,
3411 // but Entity doesn't have a way to capture that (yet).
3412 if (ClassDecl->hasUserDeclaredConstructor())
3413 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003415 // -- if T is a (possibly cv-qualified) non-union class type
3416 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003417 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003418 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003419 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003420 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003421 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003423 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003424 }
3425 }
3426
Douglas Gregor1b303932009-12-22 15:35:07 +00003427 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003428}
3429
Douglas Gregor85dabae2009-12-16 01:38:02 +00003430/// \brief Attempt default initialization (C++ [dcl.init]p6).
3431static void TryDefaultInitialization(Sema &S,
3432 const InitializedEntity &Entity,
3433 const InitializationKind &Kind,
3434 InitializationSequence &Sequence) {
3435 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436
Douglas Gregor85dabae2009-12-16 01:38:02 +00003437 // C++ [dcl.init]p6:
3438 // To default-initialize an object of type T means:
3439 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003440 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3441
Douglas Gregor85dabae2009-12-16 01:38:02 +00003442 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3443 // constructor for T is called (and the initialization is ill-formed if
3444 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003445 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003446 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3447 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Douglas Gregor85dabae2009-12-16 01:38:02 +00003450 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Douglas Gregor85dabae2009-12-16 01:38:02 +00003452 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003454 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003455 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003456 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003457 return;
3458 }
3459
3460 // If the destination type has a lifetime property, zero-initialize it.
3461 if (DestType.getQualifiers().hasObjCLifetime()) {
3462 Sequence.AddZeroInitializationStep(Entity.getType());
3463 return;
3464 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003465}
3466
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3468/// which enumerates all conversion functions and performs overload resolution
3469/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003470static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003471 const InitializedEntity &Entity,
3472 const InitializationKind &Kind,
3473 Expr *Initializer,
3474 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003475 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003476 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3477 QualType SourceType = Initializer->getType();
3478 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3479 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
Douglas Gregor540c3b02009-12-14 17:27:33 +00003481 // Build the candidate set directly in the initialization sequence
3482 // structure, so that it will persist if we fail.
3483 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3484 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485
Douglas Gregor540c3b02009-12-14 17:27:33 +00003486 // Determine whether we are allowed to call explicit constructors or
3487 // explicit conversion operators.
3488 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregor540c3b02009-12-14 17:27:33 +00003490 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3491 // The type we're converting to is a class type. Enumerate its constructors
3492 // to see if there is a suitable conversion.
3493 CXXRecordDecl *DestRecordDecl
3494 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
Douglas Gregord9848152010-04-26 14:36:57 +00003496 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003498 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003499 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003500 Con != ConEnd; ++Con) {
3501 NamedDecl *D = *Con;
3502 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Douglas Gregord9848152010-04-26 14:36:57 +00003504 // Find the constructor (which may be a template).
3505 CXXConstructorDecl *Constructor = 0;
3506 FunctionTemplateDecl *ConstructorTmpl
3507 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003508 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003509 Constructor = cast<CXXConstructorDecl>(
3510 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003511 else
Douglas Gregord9848152010-04-26 14:36:57 +00003512 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregord9848152010-04-26 14:36:57 +00003514 if (!Constructor->isInvalidDecl() &&
3515 Constructor->isConvertingConstructor(AllowExplicit)) {
3516 if (ConstructorTmpl)
3517 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3518 /*ExplicitArgs*/ 0,
3519 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003520 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003521 else
3522 S.AddOverloadCandidate(Constructor, FoundDecl,
3523 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003524 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526 }
Douglas Gregord9848152010-04-26 14:36:57 +00003527 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003528 }
Eli Friedman78275202009-12-19 08:11:05 +00003529
3530 SourceLocation DeclLoc = Initializer->getLocStart();
3531
Douglas Gregor540c3b02009-12-14 17:27:33 +00003532 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3533 // The type we're converting from is a class type, enumerate its conversion
3534 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003535
Eli Friedman4afe9a32009-12-20 22:12:03 +00003536 // We can only enumerate the conversion functions for a complete type; if
3537 // the type isn't complete, simply skip this step.
3538 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3539 CXXRecordDecl *SourceRecordDecl
3540 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
John McCallad371252010-01-20 00:46:10 +00003542 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003543 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003544 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003545 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003546 I != E; ++I) {
3547 NamedDecl *D = *I;
3548 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3549 if (isa<UsingShadowDecl>(D))
3550 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Eli Friedman4afe9a32009-12-20 22:12:03 +00003552 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3553 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003554 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003555 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003556 else
John McCallda4458e2010-03-31 01:36:47 +00003557 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Eli Friedman4afe9a32009-12-20 22:12:03 +00003559 if (AllowExplicit || !Conv->isExplicit()) {
3560 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003561 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003562 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003563 CandidateSet);
3564 else
John McCalla0296f72010-03-19 07:35:19 +00003565 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003566 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003567 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003568 }
3569 }
3570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
3572 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003573 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003574 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003575 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003576 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003578 Result);
3579 return;
3580 }
John McCall0d1da222010-01-12 00:44:57 +00003581
Douglas Gregor540c3b02009-12-14 17:27:33 +00003582 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003583 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregor540c3b02009-12-14 17:27:33 +00003585 if (isa<CXXConstructorDecl>(Function)) {
3586 // Add the user-defined conversion step. Any cv-qualification conversion is
3587 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003588 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003589 return;
3590 }
3591
3592 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003593 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003594 if (ConvType->getAs<RecordType>()) {
3595 // If we're converting to a class type, there may be an copy if
3596 // the resulting temporary object (possible to create an object of
3597 // a base class type). That copy is not a separate conversion, so
3598 // we just make a note of the actual destination type (possibly a
3599 // base class of the type returned by the conversion function) and
3600 // let the user-defined conversion step handle the conversion.
3601 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3602 return;
3603 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003604
Douglas Gregor5ab11652010-04-17 22:01:05 +00003605 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Douglas Gregor5ab11652010-04-17 22:01:05 +00003607 // If the conversion following the call to the conversion function
3608 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003609 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3610 Best->FinalConversion.Third) {
3611 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003612 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003613 ICS.Standard = Best->FinalConversion;
3614 Sequence.AddConversionSequenceStep(ICS, DestType);
3615 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003616}
3617
John McCall31168b02011-06-15 23:02:42 +00003618/// The non-zero enum values here are indexes into diagnostic alternatives.
3619enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3620
3621/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003622static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3623 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003624 // Skip parens.
3625 e = e->IgnoreParens();
3626
3627 // Skip address-of nodes.
3628 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3629 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003630 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003631
3632 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003633 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3634 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003635 case CK_Dependent:
3636 case CK_BitCast:
3637 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003638 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003639 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003640
3641 case CK_ArrayToPointerDecay:
3642 return IIK_nonscalar;
3643
3644 case CK_NullToPointer:
3645 return IIK_okay;
3646
3647 default:
3648 break;
3649 }
3650
3651 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003652 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3653 if (!isAddressOf) return IIK_nonlocal;
3654
3655 VarDecl *var;
3656 if (isa<DeclRefExpr>(e)) {
3657 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3658 if (!var) return IIK_nonlocal;
3659 } else {
3660 var = cast<BlockDeclRefExpr>(e)->getDecl();
3661 }
3662
3663 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003664
3665 // If we have a conditional operator, check both sides.
3666 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003667 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003668 return iik;
3669
John McCall63f84442011-06-27 23:59:58 +00003670 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003671
3672 // These are never scalar.
3673 } else if (isa<ArraySubscriptExpr>(e)) {
3674 return IIK_nonscalar;
3675
3676 // Otherwise, it needs to be a null pointer constant.
3677 } else {
3678 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3679 ? IIK_okay : IIK_nonlocal);
3680 }
3681
3682 return IIK_nonlocal;
3683}
3684
3685/// Check whether the given expression is a valid operand for an
3686/// indirect copy/restore.
3687static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3688 assert(src->isRValue());
3689
John McCall63f84442011-06-27 23:59:58 +00003690 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003691 if (iik == IIK_okay) return;
3692
3693 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3694 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3695 << src->getSourceRange();
3696}
3697
Douglas Gregore2f943b2011-02-22 18:29:51 +00003698/// \brief Determine whether we have compatible array types for the
3699/// purposes of GNU by-copy array initialization.
3700static bool hasCompatibleArrayTypes(ASTContext &Context,
3701 const ArrayType *Dest,
3702 const ArrayType *Source) {
3703 // If the source and destination array types are equivalent, we're
3704 // done.
3705 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3706 return true;
3707
3708 // Make sure that the element types are the same.
3709 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3710 return false;
3711
3712 // The only mismatch we allow is when the destination is an
3713 // incomplete array type and the source is a constant array type.
3714 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3715}
3716
John McCall31168b02011-06-15 23:02:42 +00003717static bool tryObjCWritebackConversion(Sema &S,
3718 InitializationSequence &Sequence,
3719 const InitializedEntity &Entity,
3720 Expr *Initializer) {
3721 bool ArrayDecay = false;
3722 QualType ArgType = Initializer->getType();
3723 QualType ArgPointee;
3724 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3725 ArrayDecay = true;
3726 ArgPointee = ArgArrayType->getElementType();
3727 ArgType = S.Context.getPointerType(ArgPointee);
3728 }
3729
3730 // Handle write-back conversion.
3731 QualType ConvertedArgType;
3732 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3733 ConvertedArgType))
3734 return false;
3735
3736 // We should copy unless we're passing to an argument explicitly
3737 // marked 'out'.
3738 bool ShouldCopy = true;
3739 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3740 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3741
3742 // Do we need an lvalue conversion?
3743 if (ArrayDecay || Initializer->isGLValue()) {
3744 ImplicitConversionSequence ICS;
3745 ICS.setStandard();
3746 ICS.Standard.setAsIdentityConversion();
3747
3748 QualType ResultType;
3749 if (ArrayDecay) {
3750 ICS.Standard.First = ICK_Array_To_Pointer;
3751 ResultType = S.Context.getPointerType(ArgPointee);
3752 } else {
3753 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3754 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3755 }
3756
3757 Sequence.AddConversionSequenceStep(ICS, ResultType);
3758 }
3759
3760 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3761 return true;
3762}
3763
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003764InitializationSequence::InitializationSequence(Sema &S,
3765 const InitializedEntity &Entity,
3766 const InitializationKind &Kind,
3767 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003768 unsigned NumArgs)
3769 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003770 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003772 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773 // The semantics of initializers are as follows. The destination type is
3774 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003775 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003777 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003778 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003779
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003780 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003781 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3782 SequenceKind = DependentSequence;
3783 return;
3784 }
3785
Sebastian Redld201edf2011-06-05 13:59:11 +00003786 // Almost everything is a normal sequence.
3787 setSequenceKind(NormalSequence);
3788
John McCalled75c092010-12-07 22:54:16 +00003789 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003790 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3791 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3792 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003793 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003794 return;
3795 }
3796 Args[I] = Result.take();
John McCall4124c492011-10-17 18:40:02 +00003797 } else if (const BuiltinType *PlaceholderTy
3798 = Args[I]->getType()->getAsPlaceholderType()) {
3799 // FIXME: should we be doing this here?
3800 if (PlaceholderTy->getKind() != BuiltinType::Overload) {
3801 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3802 if (result.isInvalid()) {
3803 SetFailed(FK_PlaceholderType);
3804 return;
3805 }
3806 Args[I] = result.take();
3807 }
John Wiegley01296292011-04-08 18:41:53 +00003808 }
John McCalled75c092010-12-07 22:54:16 +00003809
John McCall4124c492011-10-17 18:40:02 +00003810
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003811 QualType SourceType;
3812 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003813 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003814 Initializer = Args[0];
3815 if (!isa<InitListExpr>(Initializer))
3816 SourceType = Initializer->getType();
3817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818
3819 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003820 // list-initialized (8.5.4).
3821 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003822 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003823 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003826 // - If the destination type is a reference type, see 8.5.3.
3827 if (DestType->isReferenceType()) {
3828 // C++0x [dcl.init.ref]p1:
3829 // A variable declared to be a T& or T&&, that is, "reference to type T"
3830 // (8.3.2), shall be initialized by an object, or function, of type T or
3831 // by an object that can be converted into a T.
3832 // (Therefore, multiple arguments are not permitted.)
3833 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003834 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003835 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003836 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003837 return;
3838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003841 if (Kind.getKind() == InitializationKind::IK_Value ||
3842 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003843 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003844 return;
3845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregor85dabae2009-12-16 01:38:02 +00003847 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003848 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003849 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003850 return;
3851 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003852
John McCall66884dd2011-02-21 07:22:22 +00003853 // - If the destination type is an array of characters, an array of
3854 // char16_t, an array of char32_t, or an array of wchar_t, and the
3855 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003857 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003858 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3859 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003860 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003861 return;
3862 }
3863
Douglas Gregore2f943b2011-02-22 18:29:51 +00003864 // Note: as an GNU C extension, we allow initialization of an
3865 // array from a compound literal that creates an array of the same
3866 // type, so long as the initializer has no side effects.
3867 if (!S.getLangOptions().CPlusPlus && Initializer &&
3868 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3869 Initializer->getType()->isArrayType()) {
3870 const ArrayType *SourceAT
3871 = Context.getAsArrayType(Initializer->getType());
3872 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003873 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003874 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003875 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003876 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003877 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003878 }
3879 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003880 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003881 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003882 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003884 return;
3885 }
Eli Friedman78275202009-12-19 08:11:05 +00003886
John McCall31168b02011-06-15 23:02:42 +00003887 // Determine whether we should consider writeback conversions for
3888 // Objective-C ARC.
3889 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3890 Entity.getKind() == InitializedEntity::EK_Parameter;
3891
3892 // We're at the end of the line for C: it's either a write-back conversion
3893 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003894 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003895 // If allowed, check whether this is an Objective-C writeback conversion.
3896 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003897 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003898 return;
3899 }
3900
3901 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003902 AddCAssignmentStep(DestType);
3903 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003904 return;
3905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906
John McCall31168b02011-06-15 23:02:42 +00003907 assert(S.getLangOptions().CPlusPlus);
3908
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003909 // - If the destination type is a (possibly cv-qualified) class type:
3910 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 // - If the initialization is direct-initialization, or if it is
3912 // copy-initialization where the cv-unqualified version of the
3913 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003914 // class of the destination, constructors are considered. [...]
3915 if (Kind.getKind() == InitializationKind::IK_Direct ||
3916 (Kind.getKind() == InitializationKind::IK_Copy &&
3917 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3918 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003920 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003922 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003924 // used) to a derived class thereof are enumerated as described in
3925 // 13.3.1.4, and the best one is chosen through overload resolution
3926 // (13.3).
3927 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003928 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003929 return;
3930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931
Douglas Gregor85dabae2009-12-16 01:38:02 +00003932 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003933 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003934 return;
3935 }
3936 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
3938 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003939 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003940 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003941 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3942 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003943 return;
3944 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003946 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003947 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003948 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003949 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003950 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003951
3952 ImplicitConversionSequence ICS
3953 = S.TryImplicitConversion(Initializer, Entity.getType(),
3954 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003955 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003956 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003957 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3958 allowObjCWritebackConversion);
3959
3960 if (ICS.isStandard() &&
3961 ICS.Standard.Second == ICK_Writeback_Conversion) {
3962 // Objective-C ARC writeback conversion.
3963
3964 // We should copy unless we're passing to an argument explicitly
3965 // marked 'out'.
3966 bool ShouldCopy = true;
3967 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3968 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3969
3970 // If there was an lvalue adjustment, add it as a separate conversion.
3971 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3972 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3973 ImplicitConversionSequence LvalueICS;
3974 LvalueICS.setStandard();
3975 LvalueICS.Standard.setAsIdentityConversion();
3976 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3977 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003978 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003979 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003980
3981 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003982 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003983 DeclAccessPair dap;
3984 if (Initializer->getType() == Context.OverloadTy &&
3985 !S.ResolveAddressOfOverloadedFunction(Initializer
3986 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003987 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003988 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003989 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003990 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003991 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003992
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003993 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003994 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003995}
3996
3997InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003998 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003999 StepEnd = Steps.end();
4000 Step != StepEnd; ++Step)
4001 Step->Destroy();
4002}
4003
4004//===----------------------------------------------------------------------===//
4005// Perform initialization
4006//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00004008getAssignmentAction(const InitializedEntity &Entity) {
4009 switch(Entity.getKind()) {
4010 case InitializedEntity::EK_Variable:
4011 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004012 case InitializedEntity::EK_Exception:
4013 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004014 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004015 return Sema::AA_Initializing;
4016
4017 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004019 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4020 return Sema::AA_Sending;
4021
Douglas Gregore1314a62009-12-18 05:02:21 +00004022 return Sema::AA_Passing;
4023
4024 case InitializedEntity::EK_Result:
4025 return Sema::AA_Returning;
4026
Douglas Gregore1314a62009-12-18 05:02:21 +00004027 case InitializedEntity::EK_Temporary:
4028 // FIXME: Can we tell apart casting vs. converting?
4029 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030
Douglas Gregore1314a62009-12-18 05:02:21 +00004031 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004032 case InitializedEntity::EK_ArrayElement:
4033 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004034 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004035 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004036 return Sema::AA_Initializing;
4037 }
4038
4039 return Sema::AA_Converting;
4040}
4041
Douglas Gregor95562572010-04-24 23:45:46 +00004042/// \brief Whether we should binding a created object as a temporary when
4043/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004044static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004045 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004046 case InitializedEntity::EK_ArrayElement:
4047 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004048 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004049 case InitializedEntity::EK_New:
4050 case InitializedEntity::EK_Variable:
4051 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004052 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004053 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004054 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004055 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004056 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00004057 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058
Douglas Gregore1314a62009-12-18 05:02:21 +00004059 case InitializedEntity::EK_Parameter:
4060 case InitializedEntity::EK_Temporary:
4061 return true;
4062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063
Douglas Gregore1314a62009-12-18 05:02:21 +00004064 llvm_unreachable("missed an InitializedEntity kind?");
4065}
4066
Douglas Gregor95562572010-04-24 23:45:46 +00004067/// \brief Whether the given entity, when initialized with an object
4068/// created for that initialization, requires destruction.
4069static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4070 switch (Entity.getKind()) {
4071 case InitializedEntity::EK_Member:
4072 case InitializedEntity::EK_Result:
4073 case InitializedEntity::EK_New:
4074 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004075 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004076 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004077 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004078 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00004079 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080
Douglas Gregor95562572010-04-24 23:45:46 +00004081 case InitializedEntity::EK_Variable:
4082 case InitializedEntity::EK_Parameter:
4083 case InitializedEntity::EK_Temporary:
4084 case InitializedEntity::EK_ArrayElement:
4085 case InitializedEntity::EK_Exception:
4086 return true;
4087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
4089 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004090}
4091
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004092/// \brief Make a (potentially elidable) temporary copy of the object
4093/// provided by the given initializer by calling the appropriate copy
4094/// constructor.
4095///
4096/// \param S The Sema object used for type-checking.
4097///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004098/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004099/// the type of the initializer expression or a superclass thereof.
4100///
4101/// \param Enter The entity being initialized.
4102///
4103/// \param CurInit The initializer expression.
4104///
4105/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4106/// is permitted in C++03 (but not C++0x) when binding a reference to
4107/// an rvalue.
4108///
4109/// \returns An expression that copies the initializer expression into
4110/// a temporary object, or an error expression if a copy could not be
4111/// created.
John McCalldadc5752010-08-24 06:29:42 +00004112static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004113 QualType T,
4114 const InitializedEntity &Entity,
4115 ExprResult CurInit,
4116 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004117 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004118 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004120 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004121 Class = cast<CXXRecordDecl>(Record->getDecl());
4122 if (!Class)
4123 return move(CurInit);
4124
Douglas Gregor5d369002011-01-21 18:05:27 +00004125 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004126 // When certain criteria are met, an implementation is allowed to
4127 // omit the copy/move construction of a class object, even if the
4128 // copy/move constructor and/or destructor for the object have
4129 // side effects. [...]
4130 // - when a temporary class object that has not been bound to a
4131 // reference (12.2) would be copied/moved to a class object
4132 // with the same cv-unqualified type, the copy/move operation
4133 // can be omitted by constructing the temporary object
4134 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004136 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004137 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004139 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004140 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004141 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00004142 switch (Entity.getKind()) {
4143 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004144 Loc = Entity.getReturnLoc();
4145 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146
Douglas Gregore1314a62009-12-18 05:02:21 +00004147 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00004148 Loc = Entity.getThrowLoc();
4149 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
Douglas Gregore1314a62009-12-18 05:02:21 +00004151 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00004152 Loc = Entity.getDecl()->getLocation();
4153 break;
4154
Anders Carlsson0bd52402010-01-24 00:19:41 +00004155 case InitializedEntity::EK_ArrayElement:
4156 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00004157 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00004158 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004159 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00004160 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004161 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004162 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004163 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004164 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004165 Loc = CurInitExpr->getLocStart();
4166 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00004167 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00004168
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004170 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4171 return move(CurInit);
4172
Douglas Gregorf282a762011-01-21 19:38:21 +00004173 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00004174 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00004175 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00004176 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004177 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004178 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00004179 // C++0x [dcl.init]p16, second bullet to class types, this
4180 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004181 CXXConstructorDecl *Constructor = 0;
4182
4183 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004184 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004185 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00004186 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00004187 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004188 continue;
4189
4190 DeclAccessPair FoundDecl
4191 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4192 S.AddOverloadCandidate(Constructor, FoundDecl,
4193 &CurInitExpr, 1, CandidateSet);
4194 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004196
4197 // Handle constructor templates.
4198 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4199 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00004200 continue;
John McCalla0296f72010-03-19 07:35:19 +00004201
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004202 Constructor = cast<CXXConstructorDecl>(
4203 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00004204 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004205 continue;
4206
4207 // FIXME: Do we need to limit this to copy-constructor-like
4208 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00004209 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004210 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4211 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4212 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004215 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4216
Douglas Gregore1314a62009-12-18 05:02:21 +00004217 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004218 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004219 case OR_Success:
4220 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221
Douglas Gregore1314a62009-12-18 05:02:21 +00004222 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004223 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4224 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4225 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004226 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004227 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004228 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004229 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004230 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004231 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232
Douglas Gregore1314a62009-12-18 05:02:21 +00004233 case OR_Ambiguous:
4234 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004235 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004236 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004237 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004238 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004239
Douglas Gregore1314a62009-12-18 05:02:21 +00004240 case OR_Deleted:
4241 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004242 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004243 << CurInitExpr->getSourceRange();
4244 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004245 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004246 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004247 }
4248
Douglas Gregor5ab11652010-04-17 22:01:05 +00004249 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004250 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004251 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004252
Anders Carlssona01874b2010-04-21 18:47:17 +00004253 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004254 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004255
4256 if (IsExtraneousCopy) {
4257 // If this is a totally extraneous copy for C++03 reference
4258 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004259 // expression. We don't generate an (elided) copy operation here
4260 // because doing so would require us to pass down a flag to avoid
4261 // infinite recursion, where each step adds another extraneous,
4262 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004263
Douglas Gregor30b52772010-04-18 07:57:34 +00004264 // Instantiate the default arguments of any extra parameters in
4265 // the selected copy constructor, as if we were going to create a
4266 // proper call to the copy constructor.
4267 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4268 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4269 if (S.RequireCompleteType(Loc, Parm->getType(),
4270 S.PDiag(diag::err_call_incomplete_argument)))
4271 break;
4272
4273 // Build the default argument expression; we don't actually care
4274 // if this succeeds or not, because this routine will complain
4275 // if there was a problem.
4276 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4277 }
4278
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004279 return S.Owned(CurInitExpr);
4280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Chandler Carruth30141632011-02-25 19:41:05 +00004282 S.MarkDeclarationReferenced(Loc, Constructor);
4283
Douglas Gregor5ab11652010-04-17 22:01:05 +00004284 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004285 // constructor call (we might have derived-to-base conversions, or
4286 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004287 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004288 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004289 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004290
Douglas Gregord0ace022010-04-25 00:55:24 +00004291 // Actually perform the constructor call.
4292 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004293 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004294 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004295 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004296 CXXConstructExpr::CK_Complete,
4297 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
Douglas Gregord0ace022010-04-25 00:55:24 +00004299 // If we're supposed to bind temporaries, do so.
4300 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4301 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4302 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004303}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004304
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004305void InitializationSequence::PrintInitLocationNote(Sema &S,
4306 const InitializedEntity &Entity) {
4307 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4308 if (Entity.getDecl()->getLocation().isInvalid())
4309 return;
4310
4311 if (Entity.getDecl()->getDeclName())
4312 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4313 << Entity.getDecl()->getDeclName();
4314 else
4315 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4316 }
4317}
4318
Sebastian Redl112aa822011-07-14 19:07:55 +00004319static bool isReferenceBinding(const InitializationSequence::Step &s) {
4320 return s.Kind == InitializationSequence::SK_BindReference ||
4321 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4322}
4323
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004325InitializationSequence::Perform(Sema &S,
4326 const InitializedEntity &Entity,
4327 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004328 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004329 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004330 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004331 unsigned NumArgs = Args.size();
4332 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004333 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Sebastian Redld201edf2011-06-05 13:59:11 +00004336 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004337 // If the declaration is a non-dependent, incomplete array type
4338 // that has an initializer, then its type will be completed once
4339 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004340 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004341 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004342 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004343 if (const IncompleteArrayType *ArrayT
4344 = S.Context.getAsIncompleteArrayType(DeclType)) {
4345 // FIXME: We don't currently have the ability to accurately
4346 // compute the length of an initializer list without
4347 // performing full type-checking of the initializer list
4348 // (since we have to determine where braces are implicitly
4349 // introduced and such). So, we fall back to making the array
4350 // type a dependently-sized array type with no specified
4351 // bound.
4352 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4353 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004354
Douglas Gregor51e77d52009-12-10 17:56:55 +00004355 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004356 if (DeclaratorDecl *DD = Entity.getDecl()) {
4357 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4358 TypeLoc TL = TInfo->getTypeLoc();
4359 if (IncompleteArrayTypeLoc *ArrayLoc
4360 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4361 Brackets = ArrayLoc->getBracketsRange();
4362 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004363 }
4364
4365 *ResultType
4366 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4367 /*NumElts=*/0,
4368 ArrayT->getSizeModifier(),
4369 ArrayT->getIndexTypeCVRQualifiers(),
4370 Brackets);
4371 }
4372
4373 }
4374 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004375 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4376 Kind.isExplicitCast());
4377 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004378 }
4379
Sebastian Redld201edf2011-06-05 13:59:11 +00004380 // No steps means no initialization.
4381 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004382 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor1b303932009-12-22 15:35:07 +00004384 QualType DestType = Entity.getType().getNonReferenceType();
4385 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004386 // the same as Entity.getDecl()->getType() in cases involving type merging,
4387 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004388 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004389 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004390 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004391
John McCalldadc5752010-08-24 06:29:42 +00004392 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004395 // grab the only argument out the Args and place it into the "current"
4396 // initializer.
4397 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004398 case SK_ResolveAddressOfOverloadedFunction:
4399 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004400 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004401 case SK_CastDerivedToBaseLValue:
4402 case SK_BindReference:
4403 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004404 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004405 case SK_UserConversion:
4406 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004407 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004408 case SK_QualificationConversionRValue:
4409 case SK_ConversionSequence:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004410 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00004411 case SK_ListInitialization:
4412 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004413 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004414 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004415 case SK_ArrayInit:
4416 case SK_PassByIndirectCopyRestore:
4417 case SK_PassByIndirectRestore:
4418 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004419 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004420 CurInit = Args.get()[0];
4421 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004422
4423 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004424 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4425 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4426 if (CurInit.isInvalid())
4427 return ExprError();
4428 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004429 break;
John McCall34376a62010-12-04 03:47:34 +00004430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregore1314a62009-12-18 05:02:21 +00004432 case SK_ConstructorInitialization:
4433 case SK_ZeroInitialization:
4434 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
4437 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004438 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004439 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004440 for (step_iterator Step = step_begin(), StepEnd = step_end();
4441 Step != StepEnd; ++Step) {
4442 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004443 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
John Wiegley01296292011-04-08 18:41:53 +00004445 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004447 switch (Step->Kind) {
4448 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004450 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004451 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004452 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004453 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004454 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004455 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004456 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004458 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004459 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004460 case SK_CastDerivedToBaseLValue: {
4461 // We have a derived-to-base cast that produces either an rvalue or an
4462 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463
John McCallcf142162010-08-07 06:22:56 +00004464 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004465
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004466 // Casts to inaccessible base classes are allowed with C-style casts.
4467 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4468 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004469 CurInit.get()->getLocStart(),
4470 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004471 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004472 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Douglas Gregor88d292c2010-05-13 16:44:06 +00004474 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4475 QualType T = SourceType;
4476 if (const PointerType *Pointer = T->getAs<PointerType>())
4477 T = Pointer->getPointeeType();
4478 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004479 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004480 cast<CXXRecordDecl>(RecordTy->getDecl()));
4481 }
4482
John McCall2536c6d2010-08-25 10:28:54 +00004483 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004484 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004485 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004486 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004487 VK_XValue :
4488 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004489 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4490 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004491 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004492 CurInit.get(),
4493 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004494 break;
4495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004497 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004498 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004499 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4500 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004501 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004502 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004503 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004504 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004505 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004506 }
Anders Carlssona91be642010-01-29 02:47:33 +00004507
John Wiegley01296292011-04-08 18:41:53 +00004508 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004509 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004510 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4511 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004512 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004513 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004514 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004517 // Reference binding does not have any corresponding ASTs.
4518
4519 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004520 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004521 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004522
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004523 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004524
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004525 case SK_BindReferenceToTemporary:
4526 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004527 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004528 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004529
Douglas Gregorfe314812011-06-21 17:03:29 +00004530 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004531 CurInit = new (S.Context) MaterializeTemporaryExpr(
4532 Entity.getType().getNonReferenceType(),
4533 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004534 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004535
4536 // If we're binding to an Objective-C object that has lifetime, we
4537 // need cleanups.
4538 if (S.getLangOptions().ObjCAutoRefCount &&
4539 CurInit.get()->getType()->isObjCLifetimeType())
4540 S.ExprNeedsCleanups = true;
4541
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004542 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004544 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004546 /*IsExtraneousCopy=*/true);
4547 break;
4548
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004549 case SK_UserConversion: {
4550 // We have a user-defined conversion that invokes either a constructor
4551 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004552 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004553 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004554 FunctionDecl *Fn = Step->Function.Function;
4555 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004556 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00004557 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00004558 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004559 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004560 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004561 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004562 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004563
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004564 // Determine the arguments required to actually perform the constructor
4565 // call.
John Wiegley01296292011-04-08 18:41:53 +00004566 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004567 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004568 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004569 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004570 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004572 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004573 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004574 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004575 HadMultipleCandidates,
John McCallbfd822c2010-08-24 07:32:53 +00004576 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004577 CXXConstructExpr::CK_Complete,
4578 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004579 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004580 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004581
Anders Carlssona01874b2010-04-21 18:47:17 +00004582 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004583 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004584 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
John McCalle3027922010-08-25 11:45:40 +00004586 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004587 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4588 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4589 S.IsDerivedFrom(SourceType, Class))
4590 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
Douglas Gregor95562572010-04-24 23:45:46 +00004592 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004593 } else {
4594 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004595 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00004596 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004597 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004598 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599
4600 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004601 // derived-to-base conversion? I believe the answer is "no", because
4602 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004603 ExprResult CurInitExprRes =
4604 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4605 FoundFn, Conversion);
4606 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004607 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004608 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004611 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4612 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004613 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004614 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615
John McCalle3027922010-08-25 11:45:40 +00004616 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617
Douglas Gregor95562572010-04-24 23:45:46 +00004618 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620
Sebastian Redl112aa822011-07-14 19:07:55 +00004621 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004622 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004623 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004624 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004625 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004626 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004628 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004629 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004630 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004631 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4632 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004633 }
4634 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
John McCallcf142162010-08-07 06:22:56 +00004636 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004637 CurInit.get()->getType(),
4638 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00004639 CurInit.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004641 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004642 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4643 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004644
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004645 break;
4646 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004648 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004649 case SK_QualificationConversionXValue:
4650 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004651 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004652 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004653 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004654 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004655 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004656 VK_XValue :
4657 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004658 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004659 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004660 }
4661
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004662 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004663 Sema::CheckedConversionKind CCK
4664 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4665 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4666 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4667 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004668 ExprResult CurInitExprRes =
4669 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004670 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004671 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004672 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004673 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004674 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
Douglas Gregor51e77d52009-12-10 17:56:55 +00004677 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004678 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004679 QualType Ty = Step->Type;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004680 InitListChecker PerformInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00004681 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false,
4682 Kind.getKind() != InitializationKind::IK_Direct ||
4683 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004684 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00004685 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004686
4687 CurInit.release();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00004688 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004689 break;
4690 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004691
Sebastian Redl7de1fb42011-09-24 17:47:52 +00004692 case SK_ListConstructorCall:
4693 assert(false && "List constructor calls not yet supported.");
4694
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004695 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004696 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004697 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004698 = cast<CXXConstructorDecl>(Step->Function.Function);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004699 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004701 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004702 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004703 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4704 ? Kind.getEqualLoc()
4705 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004706
4707 if (Kind.getKind() == InitializationKind::IK_Default) {
4708 // Force even a trivial, implicit default constructor to be
4709 // semantically checked. We do this explicitly because we don't build
4710 // the definition for completely trivial constructors.
4711 CXXRecordDecl *ClassDecl = Constructor->getParent();
4712 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004713 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004714 ClassDecl->hasTrivialDefaultConstructor() &&
4715 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004716 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4717 }
4718
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004719 // Determine the arguments required to actually perform the constructor
4720 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004722 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004723 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
4725
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004726 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004727 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004728 (Kind.getKind() == InitializationKind::IK_Direct ||
4729 Kind.getKind() == InitializationKind::IK_Value)) {
4730 // An explicitly-constructed temporary, e.g., X(1, 2).
4731 unsigned NumExprs = ConstructorArgs.size();
4732 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004733 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004734 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Douglas Gregor2b88c112010-09-08 00:15:04 +00004736 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4737 if (!TSInfo)
4738 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004740 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4741 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004742 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004744 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004745 Kind.getParenRange(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004746 HadMultipleCandidates,
Douglas Gregor199db362010-04-27 20:36:09 +00004747 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004748 } else {
4749 CXXConstructExpr::ConstructionKind ConstructKind =
4750 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004752 if (Entity.getKind() == InitializedEntity::EK_Base) {
4753 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004755 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004756 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004757 ConstructKind = CXXConstructExpr::CK_Delegating;
4758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Chandler Carruth01718152010-10-25 08:47:36 +00004760 // Only get the parenthesis range if it is a direct construction.
4761 SourceRange parenRange =
4762 Kind.getKind() == InitializationKind::IK_Direct ?
4763 Kind.getParenRange() : SourceRange();
4764
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004765 // If the entity allows NRVO, mark the construction as elidable
4766 // unconditionally.
4767 if (Entity.allowsNRVO())
4768 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4769 Constructor, /*Elidable=*/true,
4770 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004771 HadMultipleCandidates,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004772 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004773 ConstructKind,
4774 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004775 else
4776 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004778 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004779 HadMultipleCandidates,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004780 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004781 ConstructKind,
4782 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004783 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004784 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004785 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004786
4787 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004788 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004789 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004790 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004792 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004793 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004795 break;
4796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004798 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004799 step_iterator NextStep = Step;
4800 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004802 NextStep->Kind == SK_ConstructorInitialization) {
4803 // The need for zero-initialization is recorded directly into
4804 // the call to the object's constructor within the next step.
4805 ConstructorInitRequiresZeroInit = true;
4806 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4807 S.getLangOptions().CPlusPlus &&
4808 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004809 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4810 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004812 Kind.getRange().getBegin());
4813
4814 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4815 TSInfo->getType().getNonLValueExprType(S.Context),
4816 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004817 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004818 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004819 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004820 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004821 break;
4822 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004823
4824 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004825 QualType SourceType = CurInit.get()->getType();
4826 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004827 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004828 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4829 if (Result.isInvalid())
4830 return ExprError();
4831 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004832
4833 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004834 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004835 if (ConvTy != Sema::Compatible &&
4836 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004837 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004838 == Sema::Compatible)
4839 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004840 if (CurInitExprRes.isInvalid())
4841 return ExprError();
4842 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004843
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004844 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004845 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4846 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004847 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004848 getAssignmentAction(Entity),
4849 &Complained)) {
4850 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004851 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004852 } else if (Complained)
4853 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004854 break;
4855 }
Eli Friedman78275202009-12-19 08:11:05 +00004856
4857 case SK_StringInit: {
4858 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004859 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004860 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004861 break;
4862 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004863
4864 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004865 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004866 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004867 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004868 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004869
4870 case SK_ArrayInit:
4871 // Okay: we checked everything before creating this step. Note that
4872 // this is a GNU extension.
4873 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004874 << Step->Type << CurInit.get()->getType()
4875 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004876
4877 // If the destination type is an incomplete array type, update the
4878 // type accordingly.
4879 if (ResultType) {
4880 if (const IncompleteArrayType *IncompleteDest
4881 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4882 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004883 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004884 *ResultType = S.Context.getConstantArrayType(
4885 IncompleteDest->getElementType(),
4886 ConstantSource->getSize(),
4887 ArrayType::Normal, 0);
4888 }
4889 }
4890 }
John McCall31168b02011-06-15 23:02:42 +00004891 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004892
John McCall31168b02011-06-15 23:02:42 +00004893 case SK_PassByIndirectCopyRestore:
4894 case SK_PassByIndirectRestore:
4895 checkIndirectCopyRestoreSource(S, CurInit.get());
4896 CurInit = S.Owned(new (S.Context)
4897 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4898 Step->Kind == SK_PassByIndirectCopyRestore));
4899 break;
4900
4901 case SK_ProduceObjCObject:
4902 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00004903 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00004904 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004905 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004906 }
4907 }
John McCall1f425642010-11-11 03:21:53 +00004908
4909 // Diagnose non-fatal problems with the completed initialization.
4910 if (Entity.getKind() == InitializedEntity::EK_Member &&
4911 cast<FieldDecl>(Entity.getDecl())->isBitField())
4912 S.CheckBitFieldInitialization(Kind.getLocation(),
4913 cast<FieldDecl>(Entity.getDecl()),
4914 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004916 return move(CurInit);
4917}
4918
4919//===----------------------------------------------------------------------===//
4920// Diagnose initialization failures
4921//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004922bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004923 const InitializedEntity &Entity,
4924 const InitializationKind &Kind,
4925 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004926 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004927 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregor1b303932009-12-22 15:35:07 +00004929 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004930 switch (Failure) {
4931 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004932 // FIXME: Customize for the initialized entity?
4933 if (NumArgs == 0)
4934 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4935 << DestType.getNonReferenceType();
4936 else // FIXME: diagnostic below could be better!
4937 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4938 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004939 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004941 case FK_ArrayNeedsInitList:
4942 case FK_ArrayNeedsInitListOrStringLiteral:
4943 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4944 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4945 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946
Douglas Gregore2f943b2011-02-22 18:29:51 +00004947 case FK_ArrayTypeMismatch:
4948 case FK_NonConstantArrayInit:
4949 S.Diag(Kind.getLocation(),
4950 (Failure == FK_ArrayTypeMismatch
4951 ? diag::err_array_init_different_type
4952 : diag::err_array_init_non_constant_array))
4953 << DestType.getNonReferenceType()
4954 << Args[0]->getType()
4955 << Args[0]->getSourceRange();
4956 break;
4957
John McCall16df1e52010-03-30 21:47:33 +00004958 case FK_AddressOfOverloadFailed: {
4959 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004961 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004962 true,
4963 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004964 break;
John McCall16df1e52010-03-30 21:47:33 +00004965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004967 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004968 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004969 switch (FailedOverloadResult) {
4970 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004971 if (Failure == FK_UserConversionOverloadFailed)
4972 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4973 << Args[0]->getType() << DestType
4974 << Args[0]->getSourceRange();
4975 else
4976 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4977 << DestType << Args[0]->getType()
4978 << Args[0]->getSourceRange();
4979
John McCall5c32be02010-08-24 20:38:10 +00004980 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004981 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004983 case OR_No_Viable_Function:
4984 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4985 << Args[0]->getType() << DestType.getNonReferenceType()
4986 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004987 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004988 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004989
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004990 case OR_Deleted: {
4991 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4992 << Args[0]->getType() << DestType.getNonReferenceType()
4993 << Args[0]->getSourceRange();
4994 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004995 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004996 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4997 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004998 if (Ovl == OR_Deleted) {
4999 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005000 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005001 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005002 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005003 }
5004 break;
5005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005007 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005008 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005009 break;
5010 }
5011 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005013 case FK_NonConstLValueReferenceBindingToTemporary:
5014 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005015 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005016 Failure == FK_NonConstLValueReferenceBindingToTemporary
5017 ? diag::err_lvalue_reference_bind_to_temporary
5018 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00005019 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005020 << DestType.getNonReferenceType()
5021 << Args[0]->getType()
5022 << Args[0]->getSourceRange();
5023 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005025 case FK_RValueReferenceBindingToLValue:
5026 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00005027 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005028 << Args[0]->getSourceRange();
5029 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005031 case FK_ReferenceInitDropsQualifiers:
5032 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5033 << DestType.getNonReferenceType()
5034 << Args[0]->getType()
5035 << Args[0]->getSourceRange();
5036 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005038 case FK_ReferenceInitFailed:
5039 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5040 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00005041 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005042 << Args[0]->getType()
5043 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005044 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5045 Args[0]->getType()->isObjCObjectPointerType())
5046 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005047 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Douglas Gregorb491ed32011-02-19 21:32:49 +00005049 case FK_ConversionFailed: {
5050 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00005051 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
5052 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005053 << DestType
John McCall086a4642010-11-24 05:12:34 +00005054 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00005055 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005056 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00005057 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5058 Args[0]->getType()->isObjCObjectPointerType())
5059 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005060 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00005061 }
John Wiegley01296292011-04-08 18:41:53 +00005062
5063 case FK_ConversionFromPropertyFailed:
5064 // No-op. This error has already been reported.
5065 break;
5066
Douglas Gregor51e77d52009-12-10 17:56:55 +00005067 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00005068 SourceRange R;
5069
5070 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00005071 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005072 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00005074 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00005075
Douglas Gregor8ec51732010-09-08 21:40:08 +00005076 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5077 if (Kind.isCStyleOrFunctionalCast())
5078 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5079 << R;
5080 else
5081 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5082 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00005083 break;
5084 }
5085
5086 case FK_ReferenceBindingToInitList:
5087 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5088 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5089 break;
5090
5091 case FK_InitListBadDestinationType:
5092 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5093 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5094 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005096 case FK_ConstructorOverloadFailed: {
5097 SourceRange ArgsRange;
5098 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005099 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005100 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005102 // FIXME: Using "DestType" for the entity we're printing is probably
5103 // bad.
5104 switch (FailedOverloadResult) {
5105 case OR_Ambiguous:
5106 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5107 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005108 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5109 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005110 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005111
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005112 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005113 if (Kind.getKind() == InitializationKind::IK_Default &&
5114 (Entity.getKind() == InitializedEntity::EK_Base ||
5115 Entity.getKind() == InitializedEntity::EK_Member) &&
5116 isa<CXXConstructorDecl>(S.CurContext)) {
5117 // This is implicit default initialization of a member or
5118 // base within a constructor. If no viable function was
5119 // found, notify the user that she needs to explicitly
5120 // initialize this base/member.
5121 CXXConstructorDecl *Constructor
5122 = cast<CXXConstructorDecl>(S.CurContext);
5123 if (Entity.getKind() == InitializedEntity::EK_Base) {
5124 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5125 << Constructor->isImplicit()
5126 << S.Context.getTypeDeclType(Constructor->getParent())
5127 << /*base=*/0
5128 << Entity.getType();
5129
5130 RecordDecl *BaseDecl
5131 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5132 ->getDecl();
5133 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5134 << S.Context.getTagDeclType(BaseDecl);
5135 } else {
5136 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5137 << Constructor->isImplicit()
5138 << S.Context.getTypeDeclType(Constructor->getParent())
5139 << /*member=*/1
5140 << Entity.getName();
5141 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5142
5143 if (const RecordType *Record
5144 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005145 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005146 diag::note_previous_decl)
5147 << S.Context.getTagDeclType(Record->getDecl());
5148 }
5149 break;
5150 }
5151
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005152 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5153 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00005154 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005155 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005157 case OR_Deleted: {
5158 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5159 << true << DestType << ArgsRange;
5160 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00005161 OverloadingResult Ovl
5162 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005163 if (Ovl == OR_Deleted) {
5164 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00005165 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005166 } else {
5167 llvm_unreachable("Inconsistent overload resolution?");
5168 }
5169 break;
5170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005172 case OR_Success:
5173 llvm_unreachable("Conversion did not fail!");
5174 break;
5175 }
5176 break;
5177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178
Douglas Gregor85dabae2009-12-16 01:38:02 +00005179 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005180 if (Entity.getKind() == InitializedEntity::EK_Member &&
5181 isa<CXXConstructorDecl>(S.CurContext)) {
5182 // This is implicit default-initialization of a const member in
5183 // a constructor. Complain that it needs to be explicitly
5184 // initialized.
5185 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5186 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5187 << Constructor->isImplicit()
5188 << S.Context.getTypeDeclType(Constructor->getParent())
5189 << /*const=*/1
5190 << Entity.getName();
5191 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5192 << Entity.getName();
5193 } else {
5194 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5195 << DestType << (bool)DestType->getAs<RecordType>();
5196 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005197 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005198
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005199 case FK_Incomplete:
5200 S.RequireCompleteType(Kind.getLocation(), DestType,
5201 diag::err_init_incomplete_type);
5202 break;
5203
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005204 case FK_ListInitializationFailed: {
5205 // Run the init list checker again to emit diagnostics.
5206 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5207 QualType DestType = Entity.getType();
5208 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redl8b6412a2011-10-16 18:19:28 +00005209 DestType, /*VerifyOnly=*/false,
5210 Kind.getKind() != InitializationKind::IK_Direct ||
5211 !S.getLangOptions().CPlusPlus0x);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005212 assert(DiagnoseInitList.HadError() &&
5213 "Inconsistent init list check result.");
5214 break;
5215 }
John McCall4124c492011-10-17 18:40:02 +00005216
5217 case FK_PlaceholderType: {
5218 // FIXME: Already diagnosed!
5219 break;
5220 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005222
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005223 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005224 return true;
5225}
Douglas Gregore1314a62009-12-18 05:02:21 +00005226
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005227void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005228 switch (SequenceKind) {
5229 case FailedSequence: {
5230 OS << "Failed sequence: ";
5231 switch (Failure) {
5232 case FK_TooManyInitsForReference:
5233 OS << "too many initializers for reference";
5234 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005235
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005236 case FK_ArrayNeedsInitList:
5237 OS << "array requires initializer list";
5238 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005239
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005240 case FK_ArrayNeedsInitListOrStringLiteral:
5241 OS << "array requires initializer list or string literal";
5242 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005243
Douglas Gregore2f943b2011-02-22 18:29:51 +00005244 case FK_ArrayTypeMismatch:
5245 OS << "array type mismatch";
5246 break;
5247
5248 case FK_NonConstantArrayInit:
5249 OS << "non-constant array initializer";
5250 break;
5251
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005252 case FK_AddressOfOverloadFailed:
5253 OS << "address of overloaded function failed";
5254 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005256 case FK_ReferenceInitOverloadFailed:
5257 OS << "overload resolution for reference initialization failed";
5258 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005259
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005260 case FK_NonConstLValueReferenceBindingToTemporary:
5261 OS << "non-const lvalue reference bound to temporary";
5262 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005263
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005264 case FK_NonConstLValueReferenceBindingToUnrelated:
5265 OS << "non-const lvalue reference bound to unrelated type";
5266 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005268 case FK_RValueReferenceBindingToLValue:
5269 OS << "rvalue reference bound to an lvalue";
5270 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005272 case FK_ReferenceInitDropsQualifiers:
5273 OS << "reference initialization drops qualifiers";
5274 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005275
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005276 case FK_ReferenceInitFailed:
5277 OS << "reference initialization failed";
5278 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005280 case FK_ConversionFailed:
5281 OS << "conversion failed";
5282 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005283
John Wiegley01296292011-04-08 18:41:53 +00005284 case FK_ConversionFromPropertyFailed:
5285 OS << "conversion from property failed";
5286 break;
5287
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005288 case FK_TooManyInitsForScalar:
5289 OS << "too many initializers for scalar";
5290 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005291
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005292 case FK_ReferenceBindingToInitList:
5293 OS << "referencing binding to initializer list";
5294 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005295
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005296 case FK_InitListBadDestinationType:
5297 OS << "initializer list for non-aggregate, non-scalar type";
5298 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005300 case FK_UserConversionOverloadFailed:
5301 OS << "overloading failed for user-defined conversion";
5302 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005304 case FK_ConstructorOverloadFailed:
5305 OS << "constructor overloading failed";
5306 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005307
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005308 case FK_DefaultInitOfConst:
5309 OS << "default initialization of a const variable";
5310 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005312 case FK_Incomplete:
5313 OS << "initialization of incomplete type";
5314 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005315
5316 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005317 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00005318 break;
5319
5320 case FK_PlaceholderType:
5321 OS << "initializer expression isn't contextually valid";
5322 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005324 OS << '\n';
5325 return;
5326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005327
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005328 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005329 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005330 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005331
Sebastian Redld201edf2011-06-05 13:59:11 +00005332 case NormalSequence:
5333 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005334 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005336
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005337 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5338 if (S != step_begin()) {
5339 OS << " -> ";
5340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005341
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005342 switch (S->Kind) {
5343 case SK_ResolveAddressOfOverloadedFunction:
5344 OS << "resolve address of overloaded function";
5345 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005347 case SK_CastDerivedToBaseRValue:
5348 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5349 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005350
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005351 case SK_CastDerivedToBaseXValue:
5352 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5353 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005355 case SK_CastDerivedToBaseLValue:
5356 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5357 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005359 case SK_BindReference:
5360 OS << "bind reference to lvalue";
5361 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005363 case SK_BindReferenceToTemporary:
5364 OS << "bind reference to a temporary";
5365 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005366
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005367 case SK_ExtraneousCopyToTemporary:
5368 OS << "extraneous C++03 copy to temporary";
5369 break;
5370
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005371 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005372 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005373 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005374
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005375 case SK_QualificationConversionRValue:
5376 OS << "qualification conversion (rvalue)";
5377
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005378 case SK_QualificationConversionXValue:
5379 OS << "qualification conversion (xvalue)";
5380
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005381 case SK_QualificationConversionLValue:
5382 OS << "qualification conversion (lvalue)";
5383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005385 case SK_ConversionSequence:
5386 OS << "implicit conversion sequence (";
5387 S->ICS->DebugPrint(); // FIXME: use OS
5388 OS << ")";
5389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005390
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005391 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00005392 OS << "list aggregate initialization";
5393 break;
5394
5395 case SK_ListConstructorCall:
5396 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005397 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005399 case SK_ConstructorInitialization:
5400 OS << "constructor initialization";
5401 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005402
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005403 case SK_ZeroInitialization:
5404 OS << "zero initialization";
5405 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005406
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005407 case SK_CAssignment:
5408 OS << "C assignment";
5409 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005410
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005411 case SK_StringInit:
5412 OS << "string initialization";
5413 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005414
5415 case SK_ObjCObjectConversion:
5416 OS << "Objective-C object conversion";
5417 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005418
5419 case SK_ArrayInit:
5420 OS << "array initialization";
5421 break;
John McCall31168b02011-06-15 23:02:42 +00005422
5423 case SK_PassByIndirectCopyRestore:
5424 OS << "pass by indirect copy and restore";
5425 break;
5426
5427 case SK_PassByIndirectRestore:
5428 OS << "pass by indirect restore";
5429 break;
5430
5431 case SK_ProduceObjCObject:
5432 OS << "Objective-C object retension";
5433 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005434 }
5435 }
5436}
5437
5438void InitializationSequence::dump() const {
5439 dump(llvm::errs());
5440}
5441
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005442static void DiagnoseNarrowingInInitList(
5443 Sema& S, QualType EntityType, const Expr *InitE,
5444 bool Constant, const APValue &ConstantValue) {
5445 if (Constant) {
5446 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005447 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005448 ? diag::err_init_list_constant_narrowing
5449 : diag::warn_init_list_constant_narrowing)
5450 << InitE->getSourceRange()
5451 << ConstantValue
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005452 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005453 } else
5454 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005455 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005456 ? diag::err_init_list_variable_narrowing
5457 : diag::warn_init_list_variable_narrowing)
5458 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005459 << InitE->getType().getLocalUnqualifiedType()
5460 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005461
5462 llvm::SmallString<128> StaticCast;
5463 llvm::raw_svector_ostream OS(StaticCast);
5464 OS << "static_cast<";
5465 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5466 // It's important to use the typedef's name if there is one so that the
5467 // fixit doesn't break code using types like int64_t.
5468 //
5469 // FIXME: This will break if the typedef requires qualification. But
5470 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00005471 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005472 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5473 OS << BT->getName(S.getLangOptions());
5474 else {
5475 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5476 // with a broken cast.
5477 return;
5478 }
5479 OS << ">(";
5480 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5481 << InitE->getSourceRange()
5482 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5483 << FixItHint::CreateInsertion(
5484 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5485}
5486
Douglas Gregore1314a62009-12-18 05:02:21 +00005487//===----------------------------------------------------------------------===//
5488// Initialization helper functions
5489//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005490bool
5491Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5492 ExprResult Init) {
5493 if (Init.isInvalid())
5494 return false;
5495
5496 Expr *InitE = Init.get();
5497 assert(InitE && "No initialization expression");
5498
5499 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5500 SourceLocation());
5501 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005502 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005503}
5504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005506Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5507 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005508 ExprResult Init,
5509 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005510 if (Init.isInvalid())
5511 return ExprError();
5512
John McCall1f425642010-11-11 03:21:53 +00005513 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005514 assert(InitE && "No initialization expression?");
5515
5516 if (EqualLoc.isInvalid())
5517 EqualLoc = InitE->getLocStart();
5518
5519 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5520 EqualLoc);
5521 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5522 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005523
5524 bool Constant = false;
5525 APValue Result;
5526 if (TopLevelOfInitList &&
5527 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5528 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5529 Constant, Result);
5530 }
John McCallfaf5fb42010-08-26 23:41:50 +00005531 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005532}