blob: c4314b6f6ce7e593d5e47ae80380e84975aa2c3a [file] [log] [blame]
Steve Naroff0cca7492008-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 Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +000095 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000100 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Eli Friedman8718a6a2009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000105 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000108 if (S.getLangOpts().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
112 //
113 // unsigned char a[2] = "\pa";
114 if (SL->isPascal())
115 StrLength--;
116 }
117
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000120 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
123 } else {
124 // C99 6.7.8p14.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000126 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
129 }
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Eli Friedman8718a6a2009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000136}
137
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregor9e80f722009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000156/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000169namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000173 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000174 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000175 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000176 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000178 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000179 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000181 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
201 unsigned &Index,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000205 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000211 unsigned &Index,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000214 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000215 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000218 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000219 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000226 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000227 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000232 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000233 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000234 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
237 unsigned &Index,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000240 bool FinishSubobjectInit,
241 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000249 Expr *expr);
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000261 void CheckValueInitializable(const InitializedEntity &Entity);
262
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000263public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000264 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000267 bool HadError() { return hadError; }
268
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272};
Chris Lattner8b419b92009-02-24 22:48:58 +0000273} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000274
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000275void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276 assert(VerifyOnly &&
277 "CheckValueInitializable is only inteded for verification mode.");
278
279 SourceLocation Loc;
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
284 hadError = true;
285}
286
Douglas Gregord6d37de2009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000291 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000292 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
296 // FIXME: We probably don't need to handle references
297 // specially here, since value-initialization of references is
298 // handled in InitializationSequence.
299 if (Field->getType()->isReferenceType()) {
300 // C++ [dcl.init.aggr]p9:
301 // If an incomplete or empty initializer-list leaves a
302 // member of reference type uninitialized, the program is
303 // ill-formed.
304 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
305 << Field->getType()
306 << ILE->getSyntacticForm()->getSourceRange();
307 SemaRef.Diag(Field->getLocation(),
308 diag::note_uninit_reference_member);
309 hadError = true;
310 return;
311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000312
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
314 true);
315 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
316 if (!InitSeq) {
317 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
318 hadError = true;
319 return;
320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321
John McCall60d7b3a2010-08-24 06:29:42 +0000322 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000323 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000324 if (MemberInit.isInvalid()) {
325 hadError = true;
326 return;
327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 if (hadError) {
330 // Do nothing
331 } else if (Init < NumInits) {
332 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000333 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000334 // Value-initialization requires a constructor call, so
335 // extend the initializer list to include the constructor
336 // call and make a note that we'll need to take another pass
337 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000338 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000339 RequiresSecondPass = true;
340 }
341 } else if (InitListExpr *InnerILE
342 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343 FillInValueInitializations(MemberEntity, InnerILE,
344 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345}
346
Douglas Gregor4c678342009-01-28 21:54:33 +0000347/// Recursively replaces NULL values within the given initializer list
348/// with expressions that perform value-initialization of the
349/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
352 InitListExpr *ILE,
353 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000355 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000356 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000358 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Ted Kremenek6217b802009-07-29 21:53:49 +0000360 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361 if (RType->getDecl()->isUnion() &&
362 ILE->getInitializedFieldInUnion())
363 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
364 Entity, ILE, RequiresSecondPass);
365 else {
366 unsigned Init = 0;
367 for (RecordDecl::field_iterator
368 Field = RType->getDecl()->field_begin(),
369 FieldEnd = RType->getDecl()->field_end();
370 Field != FieldEnd; ++Field) {
371 if (Field->isUnnamedBitfield())
372 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000373
Douglas Gregord6d37de2009-12-22 00:05:34 +0000374 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000375 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000376
David Blaikie581deb32012-06-06 20:45:41 +0000377 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000378 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380
Douglas Gregord6d37de2009-12-22 00:05:34 +0000381 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000382
Douglas Gregord6d37de2009-12-22 00:05:34 +0000383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
386 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 }
388
389 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000391
392 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000394 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 unsigned NumInits = ILE->getNumInits();
396 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000397 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000398 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
400 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000402 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000403 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000404 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000408 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000409 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000410
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000411
Douglas Gregor87fd7032009-02-02 17:43:21 +0000412 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000413 if (hadError)
414 return;
415
Anders Carlssond3d824d2010-01-23 04:34:47 +0000416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
417 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 ElementEntity.setElementIndex(Init);
419
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000420 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
421 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000422 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
423 true);
424 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
425 if (!InitSeq) {
426 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000427 hadError = true;
428 return;
429 }
430
John McCall60d7b3a2010-08-24 06:29:42 +0000431 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000432 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000433 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000434 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000435 return;
436 }
437
438 if (hadError) {
439 // Do nothing
440 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000441 // For arrays, just set the expression used for value-initialization
442 // of the "holes" in the array.
443 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
444 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
445 else
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000447 } else {
448 // For arrays, just set the expression used for value-initialization
449 // of the rest of elements and exit.
450 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
451 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
452 return;
453 }
454
Sebastian Redl7491c492011-06-05 13:59:11 +0000455 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000456 // Value-initialization requires a constructor call, so
457 // extend the initializer list to include the constructor
458 // call and make a note that we'll need to take another pass
459 // through the initializer list.
460 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
461 RequiresSecondPass = true;
462 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000463 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000464 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000465 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000466 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000467 }
468}
469
Chris Lattner68355a52009-01-29 05:10:57 +0000470
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000472 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000473 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000474 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000475 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000476
Eli Friedmanb85f7072008-05-19 19:16:24 +0000477 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000479 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000481 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000482 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000483 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000484
Sebastian Redl14b0c192011-09-24 17:48:00 +0000485 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000486 bool RequiresSecondPass = false;
487 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000488 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490 RequiresSecondPass);
491 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000492}
493
494int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000495 // FIXME: use a proper constant
496 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000497 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000498 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
500 }
501 return maxElements;
502}
503
504int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000508 Field = structDecl->field_begin(),
509 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000511 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000512 ++InitializableMembers;
513 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000514 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000515 return std::min(InitializableMembers, 1);
516 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000517}
518
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000519void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000520 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 QualType T, unsigned &Index,
522 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000523 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000524 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Steve Naroff0cca7492008-05-01 22:18:59 +0000526 if (T->isArrayType())
527 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000528 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000529 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000530 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000531 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000532 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000533 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000534
Eli Friedman402256f2008-05-25 13:49:22 +0000535 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000536 if (!VerifyOnly)
537 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
538 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000539 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000540 hadError = true;
541 return;
542 }
543
Douglas Gregor4c678342009-01-28 21:54:33 +0000544 // Build a structured initializer list corresponding to this subobject.
545 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000546 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
547 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000548 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000549 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000550 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000551
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000553 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000555 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000556 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000557 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000558
559 if (VerifyOnly) {
560 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
561 hadError = true;
562 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000563 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000564
Sebastian Redlc2235182011-10-16 18:19:28 +0000565 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000566 // Update the structured sub-object initializer so that it's ending
567 // range corresponds with the end of the last initializer it used.
568 if (EndIndex < ParentIList->getNumInits()) {
569 SourceLocation EndLoc
570 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
571 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573
Sebastian Redlc2235182011-10-16 18:19:28 +0000574 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000575 if (T->isArrayType() || T->isRecordType()) {
576 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000577 AllowBraceElision ? diag::warn_missing_braces :
578 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000579 << StructuredSubobjectInitList->getSourceRange()
580 << FixItHint::CreateInsertion(
581 StructuredSubobjectInitList->getLocStart(), "{")
582 << FixItHint::CreateInsertion(
583 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000585 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000586 if (!AllowBraceElision)
587 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000588 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000589 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000590}
591
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000592void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000593 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 unsigned &Index,
595 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000599 if (!VerifyOnly) {
600 SyntacticToSemantic[IList] = StructuredList;
601 StructuredList->setSyntacticForm(IList);
602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000604 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000605 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000606 QualType ExprTy = T;
607 if (!ExprTy->isArrayType())
608 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000609 IList->setType(ExprTy);
610 StructuredList->setType(ExprTy);
611 }
Eli Friedman638e1442008-05-25 13:22:35 +0000612 if (hadError)
613 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000614
Eli Friedman638e1442008-05-25 13:22:35 +0000615 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000616 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000617 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000618 if (SemaRef.getLangOpts().CPlusPlus ||
619 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000620 IList->getType()->isVectorType())) {
621 hadError = true;
622 }
623 return;
624 }
625
Eli Friedmane5408582009-05-29 20:20:05 +0000626 if (StructuredIndex == 1 &&
627 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000628 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000629 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000630 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000631 hadError = true;
632 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000633 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000634 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000635 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000636 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000637 // Don't complain for incomplete types, since we'll get an error
638 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000640 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000641 CurrentObjectType->isArrayType()? 0 :
642 CurrentObjectType->isVectorType()? 1 :
643 CurrentObjectType->isScalarType()? 2 :
644 CurrentObjectType->isUnionType()? 3 :
645 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000646
647 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000649 DK = diag::err_excess_initializers;
650 hadError = true;
651 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000652 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000653 DK = diag::err_excess_initializers;
654 hadError = true;
655 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000656
Chris Lattner08202542009-02-24 22:50:46 +0000657 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000658 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000659 }
660 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000661
Sebastian Redl14b0c192011-09-24 17:48:00 +0000662 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
663 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000664 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000665 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000666 << FixItHint::CreateRemoval(IList->getLocStart())
667 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000668}
669
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000670void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000671 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000672 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000673 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000676 unsigned &StructuredIndex,
677 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000678 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
679 // Explicitly braced initializer for complex type can be real+imaginary
680 // parts.
681 CheckComplexType(Entity, IList, DeclType, Index,
682 StructuredList, StructuredIndex);
683 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000684 CheckScalarType(Entity, IList, DeclType, Index,
685 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000686 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000687 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000688 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000689 } else if (DeclType->isRecordType()) {
690 assert(DeclType->isAggregateType() &&
691 "non-aggregate records should be handed in CheckSubElementType");
692 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
693 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
694 SubobjectIsDesignatorContext, Index,
695 StructuredList, StructuredIndex,
696 TopLevelObject);
697 } else if (DeclType->isArrayType()) {
698 llvm::APSInt Zero(
699 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
700 false);
701 CheckArrayType(Entity, IList, DeclType, Zero,
702 SubobjectIsDesignatorContext, Index,
703 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000711 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000712 CheckReferenceType(Entity, IList, DeclType, Index,
713 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000714 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000715 if (!VerifyOnly)
716 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
717 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000718 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000719 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
722 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000723 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000724 }
725}
726
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000727void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000728 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000729 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000730 unsigned &Index,
731 InitListExpr *StructuredList,
732 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000733 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000734 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000735 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
736 unsigned newIndex = 0;
737 unsigned newStructuredIndex = 0;
738 InitListExpr *newStructuredList
739 = getStructuredSubobjectInit(IList, Index, ElemType,
740 StructuredList, StructuredIndex,
741 SubInitList->getSourceRange());
742 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
743 newStructuredList, newStructuredIndex);
744 ++StructuredIndex;
745 ++Index;
746 return;
747 }
748 assert(SemaRef.getLangOpts().CPlusPlus &&
749 "non-aggregate records are only possible in C++");
750 // C++ initialization is handled later.
751 }
752
753 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000754 return CheckScalarType(Entity, IList, ElemType, Index,
755 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000756 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000757 return CheckReferenceType(Entity, IList, ElemType, Index,
758 StructuredList, StructuredIndex);
759 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000760
John McCallfef8b342011-02-21 07:57:55 +0000761 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
762 // arrayType can be incomplete if we're initializing a flexible
763 // array member. There's nothing we can do with the completed
764 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765
John McCallfef8b342011-02-21 07:57:55 +0000766 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000767 if (!VerifyOnly) {
768 CheckStringInit(Str, ElemType, arrayType, SemaRef);
769 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
770 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000771 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000772 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000773 }
John McCallfef8b342011-02-21 07:57:55 +0000774
775 // Fall through for subaggregate initialization.
776
David Blaikie4e4d0842012-03-11 07:00:24 +0000777 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000778 // C++ [dcl.init.aggr]p12:
779 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000780 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000781 // an initializer-list. If the initializer can initialize a
782 // member, the member is initialized. [...]
783
784 // FIXME: Better EqualLoc?
785 InitializationKind Kind =
786 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
787 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
788
789 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000790 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000791 ExprResult Result =
792 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
793 if (Result.isInvalid())
794 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000795
Sebastian Redl14b0c192011-09-24 17:48:00 +0000796 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000797 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000798 }
John McCallfef8b342011-02-21 07:57:55 +0000799 ++Index;
800 return;
801 }
802
803 // Fall through for subaggregate initialization
804 } else {
805 // C99 6.7.8p13:
806 //
807 // The initializer for a structure or union object that has
808 // automatic storage duration shall be either an initializer
809 // list as described below, or a single expression that has
810 // compatible structure or union type. In the latter case, the
811 // initial value of the object, including unnamed members, is
812 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000813 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000814 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000815 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
816 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000817 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000818 if (ExprRes.isInvalid())
819 hadError = true;
820 else {
821 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
822 if (ExprRes.isInvalid())
823 hadError = true;
824 }
825 UpdateStructuredListElement(StructuredList, StructuredIndex,
826 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000827 ++Index;
828 return;
829 }
John Wiegley429bb272011-04-08 18:41:53 +0000830 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000831 // Fall through for subaggregate initialization
832 }
833
834 // C++ [dcl.init.aggr]p12:
835 //
836 // [...] Otherwise, if the member is itself a non-empty
837 // subaggregate, brace elision is assumed and the initializer is
838 // considered for the initialization of the first member of
839 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000840 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000841 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000842 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
843 StructuredIndex);
844 ++StructuredIndex;
845 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000846 if (!VerifyOnly) {
847 // We cannot initialize this element, so let
848 // PerformCopyInitialization produce the appropriate diagnostic.
849 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
850 SemaRef.Owned(expr),
851 /*TopLevelOfInitList=*/true);
852 }
John McCallfef8b342011-02-21 07:57:55 +0000853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000856 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000857}
858
Eli Friedman0c706c22011-09-19 23:17:44 +0000859void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
860 InitListExpr *IList, QualType DeclType,
861 unsigned &Index,
862 InitListExpr *StructuredList,
863 unsigned &StructuredIndex) {
864 assert(Index == 0 && "Index in explicit init list must be zero");
865
866 // As an extension, clang supports complex initializers, which initialize
867 // a complex number component-wise. When an explicit initializer list for
868 // a complex number contains two two initializers, this extension kicks in:
869 // it exepcts the initializer list to contain two elements convertible to
870 // the element type of the complex type. The first element initializes
871 // the real part, and the second element intitializes the imaginary part.
872
873 if (IList->getNumInits() != 2)
874 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
875 StructuredIndex);
876
877 // This is an extension in C. (The builtin _Complex type does not exist
878 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000879 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000880 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
881 << IList->getSourceRange();
882
883 // Initialize the complex number.
884 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
885 InitializedEntity ElementEntity =
886 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
887
888 for (unsigned i = 0; i < 2; ++i) {
889 ElementEntity.setElementIndex(Index);
890 CheckSubElementType(ElementEntity, IList, elementType, Index,
891 StructuredList, StructuredIndex);
892 }
893}
894
895
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000896void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000897 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000898 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000899 InitListExpr *StructuredList,
900 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000901 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000902 if (!VerifyOnly)
903 SemaRef.Diag(IList->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +0000904 SemaRef.getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +0000905 diag::warn_cxx98_compat_empty_scalar_initializer :
906 diag::err_empty_scalar_initializer)
907 << IList->getSourceRange();
David Blaikie4e4d0842012-03-11 07:00:24 +0000908 hadError = !SemaRef.getLangOpts().CPlusPlus0x;
Douglas Gregor4c678342009-01-28 21:54:33 +0000909 ++Index;
910 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000911 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000912 }
John McCallb934c2d2010-11-11 00:46:36 +0000913
914 Expr *expr = IList->getInit(Index);
915 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000916 if (!VerifyOnly)
917 SemaRef.Diag(SubIList->getLocStart(),
918 diag::warn_many_braces_around_scalar_init)
919 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000920
921 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
922 StructuredIndex);
923 return;
924 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000925 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000926 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000927 diag::err_designator_for_scalar_init)
928 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000929 hadError = true;
930 ++Index;
931 ++StructuredIndex;
932 return;
933 }
934
Sebastian Redl14b0c192011-09-24 17:48:00 +0000935 if (VerifyOnly) {
936 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
937 hadError = true;
938 ++Index;
939 return;
940 }
941
John McCallb934c2d2010-11-11 00:46:36 +0000942 ExprResult Result =
943 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000944 SemaRef.Owned(expr),
945 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000946
947 Expr *ResultExpr = 0;
948
949 if (Result.isInvalid())
950 hadError = true; // types weren't compatible.
951 else {
952 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000953
John McCallb934c2d2010-11-11 00:46:36 +0000954 if (ResultExpr != expr) {
955 // The type was promoted, update initializer list.
956 IList->setInit(Index, ResultExpr);
957 }
958 }
959 if (hadError)
960 ++StructuredIndex;
961 else
962 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
963 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000964}
965
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000966void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
967 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000968 unsigned &Index,
969 InitListExpr *StructuredList,
970 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000971 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000972 // FIXME: It would be wonderful if we could point at the actual member. In
973 // general, it would be useful to pass location information down the stack,
974 // so that we know the location (or decl) of the "current object" being
975 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000976 if (!VerifyOnly)
977 SemaRef.Diag(IList->getLocStart(),
978 diag::err_init_reference_member_uninitialized)
979 << DeclType
980 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000981 hadError = true;
982 ++Index;
983 ++StructuredIndex;
984 return;
985 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000986
987 Expr *expr = IList->getInit(Index);
David Blaikie4e4d0842012-03-11 07:00:24 +0000988 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000989 if (!VerifyOnly)
990 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
991 << DeclType << IList->getSourceRange();
992 hadError = true;
993 ++Index;
994 ++StructuredIndex;
995 return;
996 }
997
998 if (VerifyOnly) {
999 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1000 hadError = true;
1001 ++Index;
1002 return;
1003 }
1004
1005 ExprResult Result =
1006 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1007 SemaRef.Owned(expr),
1008 /*TopLevelOfInitList=*/true);
1009
1010 if (Result.isInvalid())
1011 hadError = true;
1012
1013 expr = Result.takeAs<Expr>();
1014 IList->setInit(Index, expr);
1015
1016 if (hadError)
1017 ++StructuredIndex;
1018 else
1019 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1020 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001021}
1022
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001023void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001024 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001025 unsigned &Index,
1026 InitListExpr *StructuredList,
1027 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001028 const VectorType *VT = DeclType->getAs<VectorType>();
1029 unsigned maxElements = VT->getNumElements();
1030 unsigned numEltsInit = 0;
1031 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001032
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001033 if (Index >= IList->getNumInits()) {
1034 // Make sure the element type can be value-initialized.
1035 if (VerifyOnly)
1036 CheckValueInitializable(
1037 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1038 return;
1039 }
1040
David Blaikie4e4d0842012-03-11 07:00:24 +00001041 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001042 // If the initializing element is a vector, try to copy-initialize
1043 // instead of breaking it apart (which is doomed to failure anyway).
1044 Expr *Init = IList->getInit(Index);
1045 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001046 if (VerifyOnly) {
1047 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1048 hadError = true;
1049 ++Index;
1050 return;
1051 }
1052
John McCall20e047a2010-10-30 00:11:39 +00001053 ExprResult Result =
1054 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001055 SemaRef.Owned(Init),
1056 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001057
1058 Expr *ResultExpr = 0;
1059 if (Result.isInvalid())
1060 hadError = true; // types weren't compatible.
1061 else {
1062 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001063
John McCall20e047a2010-10-30 00:11:39 +00001064 if (ResultExpr != Init) {
1065 // The type was promoted, update initializer list.
1066 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001067 }
1068 }
John McCall20e047a2010-10-30 00:11:39 +00001069 if (hadError)
1070 ++StructuredIndex;
1071 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001072 UpdateStructuredListElement(StructuredList, StructuredIndex,
1073 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001074 ++Index;
1075 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
John McCall20e047a2010-10-30 00:11:39 +00001078 InitializedEntity ElementEntity =
1079 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
John McCall20e047a2010-10-30 00:11:39 +00001081 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1082 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001083 if (Index >= IList->getNumInits()) {
1084 if (VerifyOnly)
1085 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001086 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001087 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall20e047a2010-10-30 00:11:39 +00001089 ElementEntity.setElementIndex(Index);
1090 CheckSubElementType(ElementEntity, IList, elementType, Index,
1091 StructuredList, StructuredIndex);
1092 }
1093 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001094 }
John McCall20e047a2010-10-30 00:11:39 +00001095
1096 InitializedEntity ElementEntity =
1097 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098
John McCall20e047a2010-10-30 00:11:39 +00001099 // OpenCL initializers allows vectors to be constructed from vectors.
1100 for (unsigned i = 0; i < maxElements; ++i) {
1101 // Don't attempt to go past the end of the init list
1102 if (Index >= IList->getNumInits())
1103 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001104
John McCall20e047a2010-10-30 00:11:39 +00001105 ElementEntity.setElementIndex(Index);
1106
1107 QualType IType = IList->getInit(Index)->getType();
1108 if (!IType->isVectorType()) {
1109 CheckSubElementType(ElementEntity, IList, elementType, Index,
1110 StructuredList, StructuredIndex);
1111 ++numEltsInit;
1112 } else {
1113 QualType VecType;
1114 const VectorType *IVT = IType->getAs<VectorType>();
1115 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
John McCall20e047a2010-10-30 00:11:39 +00001117 if (IType->isExtVectorType())
1118 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1119 else
1120 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001121 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001122 CheckSubElementType(ElementEntity, IList, VecType, Index,
1123 StructuredList, StructuredIndex);
1124 numEltsInit += numIElts;
1125 }
1126 }
1127
1128 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001129 if (numEltsInit != maxElements) {
1130 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001131 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001132 diag::err_vector_incorrect_num_initializers)
1133 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1134 hadError = true;
1135 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001136}
1137
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001138void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001139 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001140 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001141 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001142 unsigned &Index,
1143 InitListExpr *StructuredList,
1144 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001145 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1146
Steve Naroff0cca7492008-05-01 22:18:59 +00001147 // Check for the special-case of initializing an array with a string.
1148 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001149 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001150 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001151 // We place the string literal directly into the resulting
1152 // initializer list. This is the only place where the structure
1153 // of the structured initializer list doesn't match exactly,
1154 // because doing so would involve allocating one character
1155 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001156 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001157 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001158 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1159 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1160 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001161 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001162 return;
1163 }
1164 }
John McCallce6c9b72011-02-21 07:22:22 +00001165 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001166 // Check for VLAs; in standard C it would be possible to check this
1167 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1168 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001169 if (!VerifyOnly)
1170 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1171 diag::err_variable_object_no_init)
1172 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001173 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001174 ++Index;
1175 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001176 return;
1177 }
1178
Douglas Gregor05c13a32009-01-22 00:58:24 +00001179 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001180 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1181 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001182 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001183 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001184 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001185 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001186 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 maxElementsKnown = true;
1188 }
1189
John McCallce6c9b72011-02-21 07:22:22 +00001190 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001191 while (Index < IList->getNumInits()) {
1192 Expr *Init = IList->getInit(Index);
1193 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001194 // If we're not the subobject that matches up with the '{' for
1195 // the designator, we shouldn't be handling the
1196 // designator. Return immediately.
1197 if (!SubobjectIsDesignatorContext)
1198 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001200 // Handle this designated initializer. elementIndex will be
1201 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001202 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001203 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001204 StructuredList, StructuredIndex, true,
1205 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001206 hadError = true;
1207 continue;
1208 }
1209
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001210 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001211 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001212 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001213 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001214 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001215
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001216 // If the array is of incomplete type, keep track of the number of
1217 // elements in the initializer.
1218 if (!maxElementsKnown && elementIndex > maxElements)
1219 maxElements = elementIndex;
1220
Douglas Gregor05c13a32009-01-22 00:58:24 +00001221 continue;
1222 }
1223
1224 // If we know the maximum number of elements, and we've already
1225 // hit it, stop consuming elements in the initializer list.
1226 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001227 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001228
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001229 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001230 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001231 Entity);
1232 // Check this element.
1233 CheckSubElementType(ElementEntity, IList, elementType, Index,
1234 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001235 ++elementIndex;
1236
1237 // If the array is of incomplete type, keep track of the number of
1238 // elements in the initializer.
1239 if (!maxElementsKnown && elementIndex > maxElements)
1240 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001241 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001242 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001243 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001244 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001245 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001247 // Sizing an array implicitly to zero is not allowed by ISO C,
1248 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001249 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001250 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001251 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001252
Mike Stump1eb44332009-09-09 15:08:12 +00001253 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001254 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001255 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001256 if (!hadError && VerifyOnly) {
1257 // Check if there are any members of the array that get value-initialized.
1258 // If so, check if doing that is possible.
1259 // FIXME: This needs to detect holes left by designated initializers too.
1260 if (maxElementsKnown && elementIndex < maxElements)
1261 CheckValueInitializable(InitializedEntity::InitializeElement(
1262 SemaRef.Context, 0, Entity));
1263 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001264}
1265
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001266bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1267 Expr *InitExpr,
1268 FieldDecl *Field,
1269 bool TopLevelObject) {
1270 // Handle GNU flexible array initializers.
1271 unsigned FlexArrayDiag;
1272 if (isa<InitListExpr>(InitExpr) &&
1273 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1274 // Empty flexible array init always allowed as an extension
1275 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001276 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001277 // Disallow flexible array init in C++; it is not required for gcc
1278 // compatibility, and it needs work to IRGen correctly in general.
1279 FlexArrayDiag = diag::err_flexible_array_init;
1280 } else if (!TopLevelObject) {
1281 // Disallow flexible array init on non-top-level object
1282 FlexArrayDiag = diag::err_flexible_array_init;
1283 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1284 // Disallow flexible array init on anything which is not a variable.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1287 // Disallow flexible array init on local variables.
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else {
1290 // Allow other cases.
1291 FlexArrayDiag = diag::ext_flexible_array_init;
1292 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001293
1294 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001295 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001296 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001297 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001298 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1299 << Field;
1300 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001301
1302 return FlexArrayDiag != diag::ext_flexible_array_init;
1303}
1304
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001305void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001306 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001308 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001309 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001310 unsigned &Index,
1311 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001312 unsigned &StructuredIndex,
1313 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001314 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Eli Friedmanb85f7072008-05-19 19:16:24 +00001316 // If the record is invalid, some of it's members are invalid. To avoid
1317 // confusion, we forgo checking the intializer for the entire record.
1318 if (structDecl->isInvalidDecl()) {
1319 hadError = true;
1320 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001321 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001322
1323 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001324 // Value-initialize the first named member of the union.
1325 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1326 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1327 Field != FieldEnd; ++Field) {
1328 if (Field->getDeclName()) {
1329 if (VerifyOnly)
1330 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001331 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001332 else
David Blaikie581deb32012-06-06 20:45:41 +00001333 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001334 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001335 }
1336 }
1337 return;
1338 }
1339
Douglas Gregor05c13a32009-01-22 00:58:24 +00001340 // If structDecl is a forward declaration, this loop won't do
1341 // anything except look at designated initializers; That's okay,
1342 // because an error should get printed out elsewhere. It might be
1343 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001344 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001345 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001346 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001347 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001348 while (Index < IList->getNumInits()) {
1349 Expr *Init = IList->getInit(Index);
1350
1351 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001352 // If we're not the subobject that matches up with the '{' for
1353 // the designator, we shouldn't be handling the
1354 // designator. Return immediately.
1355 if (!SubobjectIsDesignatorContext)
1356 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001357
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001358 // Handle this designated initializer. Field will be updated to
1359 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001360 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001361 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001362 StructuredList, StructuredIndex,
1363 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001364 hadError = true;
1365
Douglas Gregordfb5e592009-02-12 19:00:39 +00001366 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001367
1368 // Disable check for missing fields when designators are used.
1369 // This matches gcc behaviour.
1370 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001371 continue;
1372 }
1373
1374 if (Field == FieldEnd) {
1375 // We've run out of fields. We're done.
1376 break;
1377 }
1378
Douglas Gregordfb5e592009-02-12 19:00:39 +00001379 // We've already initialized a member of a union. We're done.
1380 if (InitializedSomething && DeclType->isUnionType())
1381 break;
1382
Douglas Gregor44b43212008-12-11 16:49:14 +00001383 // If we've hit the flexible array member at the end, we're done.
1384 if (Field->getType()->isIncompleteArrayType())
1385 break;
1386
Douglas Gregor0bb76892009-01-29 16:53:55 +00001387 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001388 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001389 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001390 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001391 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001392
Douglas Gregor54001c12011-06-29 21:51:31 +00001393 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001394 bool InvalidUse;
1395 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001396 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001397 else
David Blaikie581deb32012-06-06 20:45:41 +00001398 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001399 IList->getInit(Index)->getLocStart());
1400 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001401 ++Index;
1402 ++Field;
1403 hadError = true;
1404 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001405 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001406
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001407 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001408 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001409 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1410 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001411 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001412
Sebastian Redl14b0c192011-09-24 17:48:00 +00001413 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001414 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001415 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001416 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001417
1418 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001419 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001420
John McCall80639de2010-03-11 19:32:38 +00001421 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001422 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1423 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1424 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001425 // It is possible we have one or more unnamed bitfields remaining.
1426 // Find first (if any) named field and emit warning.
1427 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1428 it != end; ++it) {
1429 if (!it->isUnnamedBitfield()) {
1430 SemaRef.Diag(IList->getSourceRange().getEnd(),
1431 diag::warn_missing_field_initializers) << it->getName();
1432 break;
1433 }
1434 }
1435 }
1436
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001437 // Check that any remaining fields can be value-initialized.
1438 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1439 !Field->getType()->isIncompleteArrayType()) {
1440 // FIXME: Should check for holes left by designated initializers too.
1441 for (; Field != FieldEnd && !hadError; ++Field) {
1442 if (!Field->isUnnamedBitfield())
1443 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001444 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001445 }
1446 }
1447
Mike Stump1eb44332009-09-09 15:08:12 +00001448 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001449 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001450 return;
1451
David Blaikie581deb32012-06-06 20:45:41 +00001452 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001453 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001454 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001455 ++Index;
1456 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001457 }
1458
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001459 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001460 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001462 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001464 StructuredList, StructuredIndex);
1465 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001467 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001468}
Steve Naroff0cca7492008-05-01 22:18:59 +00001469
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001470/// \brief Expand a field designator that refers to a member of an
1471/// anonymous struct or union into a series of field designators that
1472/// refers to the field within the appropriate subobject.
1473///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001474static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001475 DesignatedInitExpr *DIE,
1476 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001477 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001478 typedef DesignatedInitExpr::Designator Designator;
1479
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001480 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001481 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001482 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1483 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1484 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001485 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001486 DIE->getDesignator(DesigIdx)->getDotLoc(),
1487 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1488 else
1489 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1490 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001491 assert(isa<FieldDecl>(*PI));
1492 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001493 }
1494
1495 // Expand the current designator into the set of replacement
1496 // designators, so we have a full subobject path down to where the
1497 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001498 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001499 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001500}
Mike Stump1eb44332009-09-09 15:08:12 +00001501
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001502/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001503/// corresponds to FieldName.
1504static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1505 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001506 if (!FieldName)
1507 return 0;
1508
Francois Picheta0e27f02010-12-22 03:46:10 +00001509 assert(AnonField->isAnonymousStructOrUnion());
1510 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001511 while (IndirectFieldDecl *IF =
1512 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001513 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001514 return IF;
1515 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001516 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001517 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001518}
1519
Sebastian Redl14b0c192011-09-24 17:48:00 +00001520static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1521 DesignatedInitExpr *DIE) {
1522 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1523 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1524 for (unsigned I = 0; I < NumIndexExprs; ++I)
1525 IndexExprs[I] = DIE->getSubExpr(I + 1);
1526 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001527 DIE->size(), IndexExprs,
1528 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001529 DIE->usesGNUSyntax(), DIE->getInit());
1530}
1531
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001532namespace {
1533
1534// Callback to only accept typo corrections that are for field members of
1535// the given struct or union.
1536class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1537 public:
1538 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1539 : Record(RD) {}
1540
1541 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1542 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1543 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1544 }
1545
1546 private:
1547 RecordDecl *Record;
1548};
1549
1550}
1551
Douglas Gregor05c13a32009-01-22 00:58:24 +00001552/// @brief Check the well-formedness of a C99 designated initializer.
1553///
1554/// Determines whether the designated initializer @p DIE, which
1555/// resides at the given @p Index within the initializer list @p
1556/// IList, is well-formed for a current object of type @p DeclType
1557/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001558/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001559/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001560///
1561/// @param IList The initializer list in which this designated
1562/// initializer occurs.
1563///
Douglas Gregor71199712009-04-15 04:56:10 +00001564/// @param DIE The designated initializer expression.
1565///
1566/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001567///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001568/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001569/// into which the designation in @p DIE should refer.
1570///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571/// @param NextField If non-NULL and the first designator in @p DIE is
1572/// a field, this will be set to the field declaration corresponding
1573/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001574///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001575/// @param NextElementIndex If non-NULL and the first designator in @p
1576/// DIE is an array designator or GNU array-range designator, this
1577/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001578///
1579/// @param Index Index into @p IList where the designated initializer
1580/// @p DIE occurs.
1581///
Douglas Gregor4c678342009-01-28 21:54:33 +00001582/// @param StructuredList The initializer list expression that
1583/// describes all of the subobject initializers in the order they'll
1584/// actually be initialized.
1585///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001586/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001587bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001588InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001589 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001590 DesignatedInitExpr *DIE,
1591 unsigned DesigIdx,
1592 QualType &CurrentObjectType,
1593 RecordDecl::field_iterator *NextField,
1594 llvm::APSInt *NextElementIndex,
1595 unsigned &Index,
1596 InitListExpr *StructuredList,
1597 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001598 bool FinishSubobjectInit,
1599 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001600 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001601 // Check the actual initialization for the designated object type.
1602 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001603
1604 // Temporarily remove the designator expression from the
1605 // initializer list that the child calls see, so that we don't try
1606 // to re-process the designator.
1607 unsigned OldIndex = Index;
1608 IList->setInit(OldIndex, DIE->getInit());
1609
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001610 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001611 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001612
1613 // Restore the designated initializer expression in the syntactic
1614 // form of the initializer list.
1615 if (IList->getInit(OldIndex) != DIE->getInit())
1616 DIE->setInit(IList->getInit(OldIndex));
1617 IList->setInit(OldIndex, DIE);
1618
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001619 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620 }
1621
Douglas Gregor71199712009-04-15 04:56:10 +00001622 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001623 bool IsFirstDesignator = (DesigIdx == 0);
1624 if (!VerifyOnly) {
1625 assert((IsFirstDesignator || StructuredList) &&
1626 "Need a non-designated initializer list to start from");
1627
1628 // Determine the structural initializer list that corresponds to the
1629 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001630 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001631 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1632 StructuredList, StructuredIndex,
1633 SourceRange(D->getStartLocation(),
1634 DIE->getSourceRange().getEnd()));
1635 assert(StructuredList && "Expected a structured initializer list");
1636 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001637
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001638 if (D->isFieldDesignator()) {
1639 // C99 6.7.8p7:
1640 //
1641 // If a designator has the form
1642 //
1643 // . identifier
1644 //
1645 // then the current object (defined below) shall have
1646 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001647 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001648 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001649 if (!RT) {
1650 SourceLocation Loc = D->getDotLoc();
1651 if (Loc.isInvalid())
1652 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001653 if (!VerifyOnly)
1654 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001655 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001656 ++Index;
1657 return true;
1658 }
1659
Douglas Gregor4c678342009-01-28 21:54:33 +00001660 // Note: we perform a linear search of the fields here, despite
1661 // the fact that we have a faster lookup method, because we always
1662 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001663 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001664 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001665 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001666 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001667 Field = RT->getDecl()->field_begin(),
1668 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001669 for (; Field != FieldEnd; ++Field) {
1670 if (Field->isUnnamedBitfield())
1671 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001672
Francois Picheta0e27f02010-12-22 03:46:10 +00001673 // If we find a field representing an anonymous field, look in the
1674 // IndirectFieldDecl that follow for the designated initializer.
1675 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1676 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001677 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001678 // In verify mode, don't modify the original.
1679 if (VerifyOnly)
1680 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001681 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1682 D = DIE->getDesignator(DesigIdx);
1683 break;
1684 }
1685 }
David Blaikie581deb32012-06-06 20:45:41 +00001686 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001687 break;
1688 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 break;
1690
1691 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001692 }
1693
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001695 if (VerifyOnly) {
1696 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001697 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001698 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001699
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001700 // There was no normal field in the struct with the designated
1701 // name. Perform another lookup for this name, which may find
1702 // something that we can't designate (e.g., a member function),
1703 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001704 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001705 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001706 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001707 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001708 // Name lookup didn't find anything. Determine whether this
1709 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001710 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001711 TypoCorrection Corrected = SemaRef.CorrectTypo(
1712 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001713 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001714 RT->getDecl());
1715 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001716 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001717 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001718 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001719 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001720 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001721 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001722 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001723 << FieldName << CurrentObjectType << CorrectedQuotedStr
1724 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001725 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001726 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001727 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001728 } else {
1729 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1730 << FieldName << CurrentObjectType;
1731 ++Index;
1732 return true;
1733 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001734 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001736 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001737 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001738 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001739 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001740 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001741 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001742 ++Index;
1743 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001744 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001745
Francois Picheta0e27f02010-12-22 03:46:10 +00001746 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001747 // The replacement field comes from typo correction; find it
1748 // in the list of fields.
1749 FieldIndex = 0;
1750 Field = RT->getDecl()->field_begin();
1751 for (; Field != FieldEnd; ++Field) {
1752 if (Field->isUnnamedBitfield())
1753 continue;
1754
David Blaikie581deb32012-06-06 20:45:41 +00001755 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001756 Field->getIdentifier() == ReplacementField->getIdentifier())
1757 break;
1758
1759 ++FieldIndex;
1760 }
1761 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001762 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001763
1764 // All of the fields of a union are located at the same place in
1765 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001766 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001767 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001768 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001769 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001770 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001771
Douglas Gregor54001c12011-06-29 21:51:31 +00001772 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001773 bool InvalidUse;
1774 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001775 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001776 else
David Blaikie581deb32012-06-06 20:45:41 +00001777 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001778 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001779 ++Index;
1780 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001781 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001782
Sebastian Redl14b0c192011-09-24 17:48:00 +00001783 if (!VerifyOnly) {
1784 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001785 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Sebastian Redl14b0c192011-09-24 17:48:00 +00001787 // Make sure that our non-designated initializer list has space
1788 // for a subobject corresponding to this field.
1789 if (FieldIndex >= StructuredList->getNumInits())
1790 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1791 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001792
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001793 // This designator names a flexible array member.
1794 if (Field->getType()->isIncompleteArrayType()) {
1795 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001796 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001797 // We can't designate an object within the flexible array
1798 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001799 if (!VerifyOnly) {
1800 DesignatedInitExpr::Designator *NextD
1801 = DIE->getDesignator(DesigIdx + 1);
1802 SemaRef.Diag(NextD->getStartLocation(),
1803 diag::err_designator_into_flexible_array_member)
1804 << SourceRange(NextD->getStartLocation(),
1805 DIE->getSourceRange().getEnd());
1806 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001807 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001808 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001809 Invalid = true;
1810 }
1811
Chris Lattner9046c222010-10-10 17:49:49 +00001812 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1813 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001814 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001815 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001816 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001817 diag::err_flexible_array_init_needs_braces)
1818 << DIE->getInit()->getSourceRange();
1819 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001820 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001821 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001822 Invalid = true;
1823 }
1824
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001825 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001826 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001827 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001828 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001829
1830 if (Invalid) {
1831 ++Index;
1832 return true;
1833 }
1834
1835 // Initialize the array.
1836 bool prevHadError = hadError;
1837 unsigned newStructuredIndex = FieldIndex;
1838 unsigned OldIndex = Index;
1839 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001840
1841 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001842 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001843 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001844 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001845
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001846 IList->setInit(OldIndex, DIE);
1847 if (hadError && !prevHadError) {
1848 ++Field;
1849 ++FieldIndex;
1850 if (NextField)
1851 *NextField = Field;
1852 StructuredIndex = FieldIndex;
1853 return true;
1854 }
1855 } else {
1856 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001857 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001858 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001859
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001860 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001861 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1863 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001864 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001865 true, false))
1866 return true;
1867 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001868
1869 // Find the position of the next field to be initialized in this
1870 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001871 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001872 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001873
1874 // If this the first designator, our caller will continue checking
1875 // the rest of this struct/class/union subobject.
1876 if (IsFirstDesignator) {
1877 if (NextField)
1878 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001879 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001880 return false;
1881 }
1882
Douglas Gregor34e79462009-01-28 23:36:17 +00001883 if (!FinishSubobjectInit)
1884 return false;
1885
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001886 // We've already initialized something in the union; we're done.
1887 if (RT->getDecl()->isUnion())
1888 return hadError;
1889
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001890 // Check the remaining fields within this class/struct/union subobject.
1891 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001892
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001893 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001894 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001895 return hadError && !prevHadError;
1896 }
1897
1898 // C99 6.7.8p6:
1899 //
1900 // If a designator has the form
1901 //
1902 // [ constant-expression ]
1903 //
1904 // then the current object (defined below) shall have array
1905 // type and the expression shall be an integer constant
1906 // expression. If the array is of unknown size, any
1907 // nonnegative value is valid.
1908 //
1909 // Additionally, cope with the GNU extension that permits
1910 // designators of the form
1911 //
1912 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001913 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001914 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001915 if (!VerifyOnly)
1916 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1917 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001918 ++Index;
1919 return true;
1920 }
1921
1922 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001923 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1924 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001925 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001926 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001927 DesignatedEndIndex = DesignatedStartIndex;
1928 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001929 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001930
Mike Stump1eb44332009-09-09 15:08:12 +00001931 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001932 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001933 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001934 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001935 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001936
Chris Lattnere0fd8322011-02-19 22:28:58 +00001937 // Codegen can't handle evaluating array range designators that have side
1938 // effects, because we replicate the AST value for each initialized element.
1939 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1940 // elements with something that has a side effect, so codegen can emit an
1941 // "error unsupported" error instead of miscompiling the app.
1942 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001943 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001944 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001945 }
1946
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001947 if (isa<ConstantArrayType>(AT)) {
1948 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001949 DesignatedStartIndex
1950 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001951 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001952 DesignatedEndIndex
1953 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001954 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1955 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001956 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001957 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001958 diag::err_array_designator_too_large)
1959 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1960 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001961 ++Index;
1962 return true;
1963 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001964 } else {
1965 // Make sure the bit-widths and signedness match.
1966 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001967 DesignatedEndIndex
1968 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001969 else if (DesignatedStartIndex.getBitWidth() <
1970 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001971 DesignatedStartIndex
1972 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001973 DesignatedStartIndex.setIsUnsigned(true);
1974 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor4c678342009-01-28 21:54:33 +00001977 // Make sure that our non-designated initializer list has space
1978 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001979 if (!VerifyOnly &&
1980 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001981 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001982 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001983
Douglas Gregor34e79462009-01-28 23:36:17 +00001984 // Repeatedly perform subobject initializations in the range
1985 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001986
Douglas Gregor34e79462009-01-28 23:36:17 +00001987 // Move to the next designator
1988 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1989 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001990
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001991 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001992 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001993
Douglas Gregor34e79462009-01-28 23:36:17 +00001994 while (DesignatedStartIndex <= DesignatedEndIndex) {
1995 // Recurse to check later designated subobjects.
1996 QualType ElementType = AT->getElementType();
1997 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001998
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001999 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002000 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2001 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002002 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002003 (DesignatedStartIndex == DesignatedEndIndex),
2004 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002005 return true;
2006
2007 // Move to the next index in the array that we'll be initializing.
2008 ++DesignatedStartIndex;
2009 ElementIndex = DesignatedStartIndex.getZExtValue();
2010 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002011
2012 // If this the first designator, our caller will continue checking
2013 // the rest of this array subobject.
2014 if (IsFirstDesignator) {
2015 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002016 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002017 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002018 return false;
2019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Douglas Gregor34e79462009-01-28 23:36:17 +00002021 if (!FinishSubobjectInit)
2022 return false;
2023
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002024 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002025 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002026 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002027 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002028 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002029 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002030}
2031
Douglas Gregor4c678342009-01-28 21:54:33 +00002032// Get the structured initializer list for a subobject of type
2033// @p CurrentObjectType.
2034InitListExpr *
2035InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2036 QualType CurrentObjectType,
2037 InitListExpr *StructuredList,
2038 unsigned StructuredIndex,
2039 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002040 if (VerifyOnly)
2041 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002042 Expr *ExistingInit = 0;
2043 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002044 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002045 else if (StructuredIndex < StructuredList->getNumInits())
2046 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Douglas Gregor4c678342009-01-28 21:54:33 +00002048 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2049 return Result;
2050
2051 if (ExistingInit) {
2052 // We are creating an initializer list that initializes the
2053 // subobjects of the current object, but there was already an
2054 // initialization that completely initialized the current
2055 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002056 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002057 // struct X { int a, b; };
2058 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002059 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002060 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2061 // designated initializer re-initializes the whole
2062 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002063 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002064 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002065 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002066 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002067 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002068 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002069 << ExistingInit->getSourceRange();
2070 }
2071
Mike Stump1eb44332009-09-09 15:08:12 +00002072 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002073 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002074 InitRange.getBegin(), MultiExprArg(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00002075 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002076
Eli Friedman5c89c392012-02-23 02:25:10 +00002077 QualType ResultType = CurrentObjectType;
2078 if (!ResultType->isArrayType())
2079 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2080 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002081
Douglas Gregorfa219202009-03-20 23:58:33 +00002082 // Pre-allocate storage for the structured initializer list.
2083 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002084 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002085 bool GotNumInits = false;
2086 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002087 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002088 GotNumInits = true;
2089 } else if (Index < IList->getNumInits()) {
2090 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002091 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002092 GotNumInits = true;
2093 }
Douglas Gregor08457732009-03-21 18:13:52 +00002094 }
2095
Mike Stump1eb44332009-09-09 15:08:12 +00002096 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002097 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2098 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2099 NumElements = CAType->getSize().getZExtValue();
2100 // Simple heuristic so that we don't allocate a very large
2101 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002102 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002103 NumElements = 0;
2104 }
John McCall183700f2009-09-21 23:43:11 +00002105 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002106 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002107 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002108 RecordDecl *RDecl = RType->getDecl();
2109 if (RDecl->isUnion())
2110 NumElements = 1;
2111 else
Mike Stump1eb44332009-09-09 15:08:12 +00002112 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002113 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002114 }
2115
Ted Kremenek709210f2010-04-13 23:39:13 +00002116 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002117
Douglas Gregor4c678342009-01-28 21:54:33 +00002118 // Link this new initializer list into the structured initializer
2119 // lists.
2120 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002121 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002122 else {
2123 Result->setSyntacticForm(IList);
2124 SyntacticToSemantic[IList] = Result;
2125 }
2126
2127 return Result;
2128}
2129
2130/// Update the initializer at index @p StructuredIndex within the
2131/// structured initializer list to the value @p expr.
2132void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2133 unsigned &StructuredIndex,
2134 Expr *expr) {
2135 // No structured initializer list to update
2136 if (!StructuredList)
2137 return;
2138
Ted Kremenek709210f2010-04-13 23:39:13 +00002139 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2140 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002141 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002142 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002143 diag::warn_initializer_overrides)
2144 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002145 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002146 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002147 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002148 << PrevInit->getSourceRange();
2149 }
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Douglas Gregor4c678342009-01-28 21:54:33 +00002151 ++StructuredIndex;
2152}
2153
Douglas Gregor05c13a32009-01-22 00:58:24 +00002154/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002155/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002156/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002157/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002158/// failure. Returns the index expression, possibly with an implicit cast
2159/// added, on success. If everything went okay, Value will receive the
2160/// value of the constant expression.
2161static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002162CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002163 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002164
2165 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002166 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2167 if (Result.isInvalid())
2168 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002169
Chris Lattner3bf68932009-04-25 21:59:05 +00002170 if (Value.isSigned() && Value.isNegative())
2171 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002172 << Value.toString(10) << Index->getSourceRange();
2173
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002174 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002175 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002176}
2177
John McCall60d7b3a2010-08-24 06:29:42 +00002178ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002179 SourceLocation Loc,
2180 bool GNUSyntax,
2181 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002182 typedef DesignatedInitExpr::Designator ASTDesignator;
2183
2184 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002185 SmallVector<ASTDesignator, 32> Designators;
2186 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002187
2188 // Build designators and check array designator expressions.
2189 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2190 const Designator &D = Desig.getDesignator(Idx);
2191 switch (D.getKind()) {
2192 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002193 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002194 D.getFieldLoc()));
2195 break;
2196
2197 case Designator::ArrayDesignator: {
2198 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2199 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002200 if (!Index->isTypeDependent() && !Index->isValueDependent())
2201 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2202 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002203 Invalid = true;
2204 else {
2205 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002206 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002207 D.getRBracketLoc()));
2208 InitExpressions.push_back(Index);
2209 }
2210 break;
2211 }
2212
2213 case Designator::ArrayRangeDesignator: {
2214 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2215 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2216 llvm::APSInt StartValue;
2217 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002218 bool StartDependent = StartIndex->isTypeDependent() ||
2219 StartIndex->isValueDependent();
2220 bool EndDependent = EndIndex->isTypeDependent() ||
2221 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002222 if (!StartDependent)
2223 StartIndex =
2224 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2225 if (!EndDependent)
2226 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2227
2228 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002229 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002230 else {
2231 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002232 if (StartDependent || EndDependent) {
2233 // Nothing to compute.
2234 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002235 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002236 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002237 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002238
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002239 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002240 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002241 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002242 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2243 Invalid = true;
2244 } else {
2245 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002246 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002247 D.getEllipsisLoc(),
2248 D.getRBracketLoc()));
2249 InitExpressions.push_back(StartIndex);
2250 InitExpressions.push_back(EndIndex);
2251 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002252 }
2253 break;
2254 }
2255 }
2256 }
2257
2258 if (Invalid || Init.isInvalid())
2259 return ExprError();
2260
2261 // Clear out the expressions within the designation.
2262 Desig.ClearExprs(*this);
2263
2264 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002265 = DesignatedInitExpr::Create(Context,
2266 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002267 InitExpressions, Loc, GNUSyntax,
2268 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002269
David Blaikie4e4d0842012-03-11 07:00:24 +00002270 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002271 Diag(DIE->getLocStart(), diag::ext_designated_init)
2272 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002273
Douglas Gregor05c13a32009-01-22 00:58:24 +00002274 return Owned(DIE);
2275}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002276
Douglas Gregor20093b42009-12-09 23:02:17 +00002277//===----------------------------------------------------------------------===//
2278// Initialization entity
2279//===----------------------------------------------------------------------===//
2280
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002281InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002282 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002284{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002285 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2286 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002287 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002288 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002289 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002290 Type = VT->getElementType();
2291 } else {
2292 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2293 assert(CT && "Unexpected type");
2294 Kind = EK_ComplexElement;
2295 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002296 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002297}
2298
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002299InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002300 CXXBaseSpecifier *Base,
2301 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002302{
2303 InitializedEntity Result;
2304 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002305 Result.Base = reinterpret_cast<uintptr_t>(Base);
2306 if (IsInheritedVirtualBase)
2307 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002308
Douglas Gregord6542d82009-12-22 15:35:07 +00002309 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002310 return Result;
2311}
2312
Douglas Gregor99a2e602009-12-16 01:38:02 +00002313DeclarationName InitializedEntity::getName() const {
2314 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002315 case EK_Parameter: {
2316 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2317 return (D ? D->getDeclName() : DeclarationName());
2318 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002319
2320 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002321 case EK_Member:
2322 return VariableOrMember->getDeclName();
2323
Douglas Gregor47736542012-02-15 16:57:26 +00002324 case EK_LambdaCapture:
2325 return Capture.Var->getDeclName();
2326
Douglas Gregor99a2e602009-12-16 01:38:02 +00002327 case EK_Result:
2328 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002329 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002330 case EK_Temporary:
2331 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002332 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002333 case EK_ArrayElement:
2334 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002335 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002336 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002337 return DeclarationName();
2338 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339
David Blaikie7530c032012-01-17 06:56:22 +00002340 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002341}
2342
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002343DeclaratorDecl *InitializedEntity::getDecl() const {
2344 switch (getKind()) {
2345 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002346 case EK_Member:
2347 return VariableOrMember;
2348
John McCallf85e1932011-06-15 23:02:42 +00002349 case EK_Parameter:
2350 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2351
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002352 case EK_Result:
2353 case EK_Exception:
2354 case EK_New:
2355 case EK_Temporary:
2356 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002357 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002358 case EK_ArrayElement:
2359 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002360 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002361 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002362 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002363 return 0;
2364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002365
David Blaikie7530c032012-01-17 06:56:22 +00002366 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002367}
2368
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002369bool InitializedEntity::allowsNRVO() const {
2370 switch (getKind()) {
2371 case EK_Result:
2372 case EK_Exception:
2373 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002374
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002375 case EK_Variable:
2376 case EK_Parameter:
2377 case EK_Member:
2378 case EK_New:
2379 case EK_Temporary:
2380 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002381 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002382 case EK_ArrayElement:
2383 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002384 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002385 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002386 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002387 break;
2388 }
2389
2390 return false;
2391}
2392
Douglas Gregor20093b42009-12-09 23:02:17 +00002393//===----------------------------------------------------------------------===//
2394// Initialization sequence
2395//===----------------------------------------------------------------------===//
2396
2397void InitializationSequence::Step::Destroy() {
2398 switch (Kind) {
2399 case SK_ResolveAddressOfOverloadedFunction:
2400 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002401 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002402 case SK_CastDerivedToBaseLValue:
2403 case SK_BindReference:
2404 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002405 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002406 case SK_UserConversion:
2407 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002408 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002409 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002410 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002411 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002412 case SK_UnwrapInitList:
2413 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002414 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002415 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002416 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002417 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002418 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002419 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002420 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002421 case SK_PassByIndirectCopyRestore:
2422 case SK_PassByIndirectRestore:
2423 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002424 case SK_StdInitializerList:
Douglas Gregor20093b42009-12-09 23:02:17 +00002425 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002426
Douglas Gregor20093b42009-12-09 23:02:17 +00002427 case SK_ConversionSequence:
2428 delete ICS;
2429 }
2430}
2431
Douglas Gregorb70cf442010-03-26 20:14:36 +00002432bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002433 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002434}
2435
2436bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002437 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002438 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439
Douglas Gregorb70cf442010-03-26 20:14:36 +00002440 switch (getFailureKind()) {
2441 case FK_TooManyInitsForReference:
2442 case FK_ArrayNeedsInitList:
2443 case FK_ArrayNeedsInitListOrStringLiteral:
2444 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2445 case FK_NonConstLValueReferenceBindingToTemporary:
2446 case FK_NonConstLValueReferenceBindingToUnrelated:
2447 case FK_RValueReferenceBindingToLValue:
2448 case FK_ReferenceInitDropsQualifiers:
2449 case FK_ReferenceInitFailed:
2450 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002451 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002452 case FK_TooManyInitsForScalar:
2453 case FK_ReferenceBindingToInitList:
2454 case FK_InitListBadDestinationType:
2455 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002456 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002457 case FK_ArrayTypeMismatch:
2458 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002459 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002460 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002461 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002462 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002463 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002464 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002465
Douglas Gregorb70cf442010-03-26 20:14:36 +00002466 case FK_ReferenceInitOverloadFailed:
2467 case FK_UserConversionOverloadFailed:
2468 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002469 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002470 return FailedOverloadResult == OR_Ambiguous;
2471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002472
David Blaikie7530c032012-01-17 06:56:22 +00002473 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002474}
2475
Douglas Gregord6e44a32010-04-16 22:09:46 +00002476bool InitializationSequence::isConstructorInitialization() const {
2477 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2478}
2479
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002480void
2481InitializationSequence
2482::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2483 DeclAccessPair Found,
2484 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002485 Step S;
2486 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2487 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002488 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002489 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002490 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002491 Steps.push_back(S);
2492}
2493
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002494void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002495 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002496 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002497 switch (VK) {
2498 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2499 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2500 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002501 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002502 S.Type = BaseType;
2503 Steps.push_back(S);
2504}
2505
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002506void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002507 bool BindingTemporary) {
2508 Step S;
2509 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2510 S.Type = T;
2511 Steps.push_back(S);
2512}
2513
Douglas Gregor523d46a2010-04-18 07:40:54 +00002514void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2515 Step S;
2516 S.Kind = SK_ExtraneousCopyToTemporary;
2517 S.Type = T;
2518 Steps.push_back(S);
2519}
2520
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002521void
2522InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2523 DeclAccessPair FoundDecl,
2524 QualType T,
2525 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002526 Step S;
2527 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002528 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002529 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002530 S.Function.Function = Function;
2531 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002532 Steps.push_back(S);
2533}
2534
2535void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002536 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002537 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002538 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002539 switch (VK) {
2540 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002541 S.Kind = SK_QualificationConversionRValue;
2542 break;
John McCall5baba9d2010-08-25 10:28:54 +00002543 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002544 S.Kind = SK_QualificationConversionXValue;
2545 break;
John McCall5baba9d2010-08-25 10:28:54 +00002546 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002547 S.Kind = SK_QualificationConversionLValue;
2548 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002549 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002550 S.Type = Ty;
2551 Steps.push_back(S);
2552}
2553
2554void InitializationSequence::AddConversionSequenceStep(
2555 const ImplicitConversionSequence &ICS,
2556 QualType T) {
2557 Step S;
2558 S.Kind = SK_ConversionSequence;
2559 S.Type = T;
2560 S.ICS = new ImplicitConversionSequence(ICS);
2561 Steps.push_back(S);
2562}
2563
Douglas Gregord87b61f2009-12-10 17:56:55 +00002564void InitializationSequence::AddListInitializationStep(QualType T) {
2565 Step S;
2566 S.Kind = SK_ListInitialization;
2567 S.Type = T;
2568 Steps.push_back(S);
2569}
2570
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002572InitializationSequence
2573::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2574 AccessSpecifier Access,
2575 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002576 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002577 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002578 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002579 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2580 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002581 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002582 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002583 S.Function.Function = Constructor;
2584 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002585 Steps.push_back(S);
2586}
2587
Douglas Gregor71d17402009-12-15 00:01:57 +00002588void InitializationSequence::AddZeroInitializationStep(QualType T) {
2589 Step S;
2590 S.Kind = SK_ZeroInitialization;
2591 S.Type = T;
2592 Steps.push_back(S);
2593}
2594
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002595void InitializationSequence::AddCAssignmentStep(QualType T) {
2596 Step S;
2597 S.Kind = SK_CAssignment;
2598 S.Type = T;
2599 Steps.push_back(S);
2600}
2601
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002602void InitializationSequence::AddStringInitStep(QualType T) {
2603 Step S;
2604 S.Kind = SK_StringInit;
2605 S.Type = T;
2606 Steps.push_back(S);
2607}
2608
Douglas Gregor569c3162010-08-07 11:51:51 +00002609void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2610 Step S;
2611 S.Kind = SK_ObjCObjectConversion;
2612 S.Type = T;
2613 Steps.push_back(S);
2614}
2615
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002616void InitializationSequence::AddArrayInitStep(QualType T) {
2617 Step S;
2618 S.Kind = SK_ArrayInit;
2619 S.Type = T;
2620 Steps.push_back(S);
2621}
2622
Richard Smith0f163e92012-02-15 22:38:09 +00002623void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2624 Step S;
2625 S.Kind = SK_ParenthesizedArrayInit;
2626 S.Type = T;
2627 Steps.push_back(S);
2628}
2629
John McCallf85e1932011-06-15 23:02:42 +00002630void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2631 bool shouldCopy) {
2632 Step s;
2633 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2634 : SK_PassByIndirectRestore);
2635 s.Type = type;
2636 Steps.push_back(s);
2637}
2638
2639void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2640 Step S;
2641 S.Kind = SK_ProduceObjCObject;
2642 S.Type = T;
2643 Steps.push_back(S);
2644}
2645
Sebastian Redl2b916b82012-01-17 22:49:42 +00002646void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2647 Step S;
2648 S.Kind = SK_StdInitializerList;
2649 S.Type = T;
2650 Steps.push_back(S);
2651}
2652
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002653void InitializationSequence::RewrapReferenceInitList(QualType T,
2654 InitListExpr *Syntactic) {
2655 assert(Syntactic->getNumInits() == 1 &&
2656 "Can only rewrap trivial init lists.");
2657 Step S;
2658 S.Kind = SK_UnwrapInitList;
2659 S.Type = Syntactic->getInit(0)->getType();
2660 Steps.insert(Steps.begin(), S);
2661
2662 S.Kind = SK_RewrapInitList;
2663 S.Type = T;
2664 S.WrappingSyntacticList = Syntactic;
2665 Steps.push_back(S);
2666}
2667
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002668void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002669 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002670 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002671 this->Failure = Failure;
2672 this->FailedOverloadResult = Result;
2673}
2674
2675//===----------------------------------------------------------------------===//
2676// Attempt initialization
2677//===----------------------------------------------------------------------===//
2678
John McCallf85e1932011-06-15 23:02:42 +00002679static void MaybeProduceObjCObject(Sema &S,
2680 InitializationSequence &Sequence,
2681 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002682 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002683
2684 /// When initializing a parameter, produce the value if it's marked
2685 /// __attribute__((ns_consumed)).
2686 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2687 if (!Entity.isParameterConsumed())
2688 return;
2689
2690 assert(Entity.getType()->isObjCRetainableType() &&
2691 "consuming an object of unretainable type?");
2692 Sequence.AddProduceObjCObjectStep(Entity.getType());
2693
2694 /// When initializing a return value, if the return type is a
2695 /// retainable type, then returns need to immediately retain the
2696 /// object. If an autorelease is required, it will be done at the
2697 /// last instant.
2698 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2699 if (!Entity.getType()->isObjCRetainableType())
2700 return;
2701
2702 Sequence.AddProduceObjCObjectStep(Entity.getType());
2703 }
2704}
2705
Richard Smithf4bb8d02012-07-05 08:39:21 +00002706/// \brief When initializing from init list via constructor, handle
2707/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002708///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002709/// \return true if we have handled initialization of an object of type
2710/// std::initializer_list<T>, false otherwise.
2711static bool TryInitializerListConstruction(Sema &S,
2712 InitListExpr *List,
2713 QualType DestType,
2714 InitializationSequence &Sequence) {
2715 QualType E;
2716 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002717 return false;
2718
Richard Smithf4bb8d02012-07-05 08:39:21 +00002719 // Check that each individual element can be copy-constructed. But since we
2720 // have no place to store further information, we'll recalculate everything
2721 // later.
2722 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2723 S.Context.getConstantArrayType(E,
2724 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2725 List->getNumInits()),
2726 ArrayType::Normal, 0));
2727 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2728 0, HiddenArray);
2729 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2730 Element.setElementIndex(i);
2731 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2732 Sequence.SetFailed(
2733 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002734 return true;
2735 }
2736 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002737 Sequence.AddStdInitializerListConstructionStep(DestType);
2738 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002739}
2740
Sebastian Redl96715b22012-02-04 21:27:39 +00002741static OverloadingResult
2742ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2743 Expr **Args, unsigned NumArgs,
2744 OverloadCandidateSet &CandidateSet,
2745 DeclContext::lookup_iterator Con,
2746 DeclContext::lookup_iterator ConEnd,
2747 OverloadCandidateSet::iterator &Best,
2748 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002749 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002750 CandidateSet.clear();
2751
2752 for (; Con != ConEnd; ++Con) {
2753 NamedDecl *D = *Con;
2754 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2755 bool SuppressUserConversions = false;
2756
2757 // Find the constructor (which may be a template).
2758 CXXConstructorDecl *Constructor = 0;
2759 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2760 if (ConstructorTmpl)
2761 Constructor = cast<CXXConstructorDecl>(
2762 ConstructorTmpl->getTemplatedDecl());
2763 else {
2764 Constructor = cast<CXXConstructorDecl>(D);
2765
2766 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002767 // suppress user-defined conversions on the arguments. We do the same for
2768 // move constructors.
2769 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2770 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002771 SuppressUserConversions = true;
2772 }
2773
2774 if (!Constructor->isInvalidDecl() &&
2775 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002776 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002777 if (ConstructorTmpl)
2778 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2779 /*ExplicitArgs*/ 0,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002780 llvm::makeArrayRef(Args, NumArgs),
2781 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002782 else {
2783 // C++ [over.match.copy]p1:
2784 // - When initializing a temporary to be bound to the first parameter
2785 // of a constructor that takes a reference to possibly cv-qualified
2786 // T as its first argument, called with a single argument in the
2787 // context of direct-initialization, explicit conversion functions
2788 // are also considered.
2789 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2790 NumArgs == 1 &&
2791 Constructor->isCopyOrMoveConstructor();
Sebastian Redl96715b22012-02-04 21:27:39 +00002792 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002793 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002794 SuppressUserConversions,
2795 /*PartialOverloading=*/false,
2796 /*AllowExplicit=*/AllowExplicitConv);
2797 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002798 }
2799 }
2800
2801 // Perform overload resolution and return the result.
2802 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2803}
2804
Sebastian Redl10f04a62011-12-22 14:44:04 +00002805/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2806/// enumerates the constructors of the initialized entity and performs overload
2807/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002808/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002809/// class type.
2810static void TryConstructorInitialization(Sema &S,
2811 const InitializedEntity &Entity,
2812 const InitializationKind &Kind,
2813 Expr **Args, unsigned NumArgs,
2814 QualType DestType,
2815 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002816 bool InitListSyntax = false) {
2817 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2818 "InitListSyntax must come with a single initializer list argument.");
2819
Sebastian Redl10f04a62011-12-22 14:44:04 +00002820 // Check constructor arguments for self reference.
2821 if (DeclaratorDecl *DD = Entity.getDecl())
2822 // Parameters arguments are occassionially constructed with itself,
2823 // for instance, in recursive functions. Skip them.
2824 if (!isa<ParmVarDecl>(DD))
2825 for (unsigned i = 0; i < NumArgs; ++i)
2826 S.CheckSelfReference(DD, Args[i]);
2827
Sebastian Redl10f04a62011-12-22 14:44:04 +00002828 // The type we're constructing needs to be complete.
2829 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002830 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002831 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002832 }
2833
2834 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2835 assert(DestRecordType && "Constructor initialization requires record type");
2836 CXXRecordDecl *DestRecordDecl
2837 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2838
Sebastian Redl96715b22012-02-04 21:27:39 +00002839 // Build the candidate set directly in the initialization sequence
2840 // structure, so that it will persist if we fail.
2841 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2842
2843 // Determine whether we are allowed to call explicit constructors or
2844 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002845 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002846 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002847
Sebastian Redl10f04a62011-12-22 14:44:04 +00002848 // - Otherwise, if T is a class type, constructors are considered. The
2849 // applicable constructors are enumerated, and the best one is chosen
2850 // through overload resolution.
Sebastian Redl96715b22012-02-04 21:27:39 +00002851 DeclContext::lookup_iterator ConStart, ConEnd;
2852 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002853
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002854 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002855 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002856 bool AsInitializerList = false;
2857
2858 // C++11 [over.match.list]p1:
2859 // When objects of non-aggregate type T are list-initialized, overload
2860 // resolution selects the constructor in two phases:
2861 // - Initially, the candidate functions are the initializer-list
2862 // constructors of the class T and the argument list consists of the
2863 // initializer list as a single argument.
2864 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002865 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002866 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002867
2868 // If the initializer list has no elements and T has a default constructor,
2869 // the first phase is omitted.
2870 if (ILE->getNumInits() != 0 ||
2871 (!DestRecordDecl->hasDeclaredDefaultConstructor() &&
2872 !DestRecordDecl->needsImplicitDefaultConstructor()))
2873 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2874 CandidateSet, ConStart, ConEnd, Best,
2875 CopyInitialization, AllowExplicit,
2876 /*OnlyListConstructor=*/true,
2877 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002878
2879 // Time to unwrap the init list.
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002880 Args = ILE->getInits();
2881 NumArgs = ILE->getNumInits();
2882 }
2883
2884 // C++11 [over.match.list]p1:
2885 // - If no viable initializer-list constructor is found, overload resolution
2886 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002887 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002888 // elements of the initializer list.
2889 if (Result == OR_No_Viable_Function) {
2890 AsInitializerList = false;
2891 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2892 CandidateSet, ConStart, ConEnd, Best,
2893 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002894 /*OnlyListConstructors=*/false,
2895 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002896 }
2897 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002898 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002899 InitializationSequence::FK_ListConstructorOverloadFailed :
2900 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002901 Result);
2902 return;
2903 }
2904
Richard Smithf4bb8d02012-07-05 08:39:21 +00002905 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002906 // If a program calls for the default initialization of an object
2907 // of a const-qualified type T, T shall be a class type with a
2908 // user-provided default constructor.
2909 if (Kind.getKind() == InitializationKind::IK_Default &&
2910 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002911 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002912 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2913 return;
2914 }
2915
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002916 // C++11 [over.match.list]p1:
2917 // In copy-list-initialization, if an explicit constructor is chosen, the
2918 // initializer is ill-formed.
2919 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2920 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2921 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2922 return;
2923 }
2924
Sebastian Redl10f04a62011-12-22 14:44:04 +00002925 // Add the constructor initialization step. Any cv-qualification conversion is
2926 // subsumed by the initialization.
2927 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002928 Sequence.AddConstructorInitializationStep(CtorDecl,
2929 Best->FoundDecl.getAccess(),
2930 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002931 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002932}
2933
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002934static bool
2935ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2936 Expr *Initializer,
2937 QualType &SourceType,
2938 QualType &UnqualifiedSourceType,
2939 QualType UnqualifiedTargetType,
2940 InitializationSequence &Sequence) {
2941 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2942 S.Context.OverloadTy) {
2943 DeclAccessPair Found;
2944 bool HadMultipleCandidates = false;
2945 if (FunctionDecl *Fn
2946 = S.ResolveAddressOfOverloadedFunction(Initializer,
2947 UnqualifiedTargetType,
2948 false, Found,
2949 &HadMultipleCandidates)) {
2950 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2951 HadMultipleCandidates);
2952 SourceType = Fn->getType();
2953 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2954 } else if (!UnqualifiedTargetType->isRecordType()) {
2955 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2956 return true;
2957 }
2958 }
2959 return false;
2960}
2961
2962static void TryReferenceInitializationCore(Sema &S,
2963 const InitializedEntity &Entity,
2964 const InitializationKind &Kind,
2965 Expr *Initializer,
2966 QualType cv1T1, QualType T1,
2967 Qualifiers T1Quals,
2968 QualType cv2T2, QualType T2,
2969 Qualifiers T2Quals,
2970 InitializationSequence &Sequence);
2971
Richard Smithf4bb8d02012-07-05 08:39:21 +00002972static void TryValueInitialization(Sema &S,
2973 const InitializedEntity &Entity,
2974 const InitializationKind &Kind,
2975 InitializationSequence &Sequence,
2976 InitListExpr *InitList = 0);
2977
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002978static void TryListInitialization(Sema &S,
2979 const InitializedEntity &Entity,
2980 const InitializationKind &Kind,
2981 InitListExpr *InitList,
2982 InitializationSequence &Sequence);
2983
2984/// \brief Attempt list initialization of a reference.
2985static void TryReferenceListInitialization(Sema &S,
2986 const InitializedEntity &Entity,
2987 const InitializationKind &Kind,
2988 InitListExpr *InitList,
2989 InitializationSequence &Sequence)
2990{
2991 // First, catch C++03 where this isn't possible.
David Blaikie4e4d0842012-03-11 07:00:24 +00002992 if (!S.getLangOpts().CPlusPlus0x) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002993 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2994 return;
2995 }
2996
2997 QualType DestType = Entity.getType();
2998 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2999 Qualifiers T1Quals;
3000 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3001
3002 // Reference initialization via an initializer list works thus:
3003 // If the initializer list consists of a single element that is
3004 // reference-related to the referenced type, bind directly to that element
3005 // (possibly creating temporaries).
3006 // Otherwise, initialize a temporary with the initializer list and
3007 // bind to that.
3008 if (InitList->getNumInits() == 1) {
3009 Expr *Initializer = InitList->getInit(0);
3010 QualType cv2T2 = Initializer->getType();
3011 Qualifiers T2Quals;
3012 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3013
3014 // If this fails, creating a temporary wouldn't work either.
3015 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3016 T1, Sequence))
3017 return;
3018
3019 SourceLocation DeclLoc = Initializer->getLocStart();
3020 bool dummy1, dummy2, dummy3;
3021 Sema::ReferenceCompareResult RefRelationship
3022 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3023 dummy2, dummy3);
3024 if (RefRelationship >= Sema::Ref_Related) {
3025 // Try to bind the reference here.
3026 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3027 T1Quals, cv2T2, T2, T2Quals, Sequence);
3028 if (Sequence)
3029 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3030 return;
3031 }
3032 }
3033
3034 // Not reference-related. Create a temporary and bind to that.
3035 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3036
3037 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3038 if (Sequence) {
3039 if (DestType->isRValueReferenceType() ||
3040 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3041 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3042 else
3043 Sequence.SetFailed(
3044 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3045 }
3046}
3047
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003048/// \brief Attempt list initialization (C++0x [dcl.init.list])
3049static void TryListInitialization(Sema &S,
3050 const InitializedEntity &Entity,
3051 const InitializationKind &Kind,
3052 InitListExpr *InitList,
3053 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003054 QualType DestType = Entity.getType();
3055
Sebastian Redl14b0c192011-09-24 17:48:00 +00003056 // C++ doesn't allow scalar initialization with more than one argument.
3057 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003058 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003059 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3060 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3061 return;
3062 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003063 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003064 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003065 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003066 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003067 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003068 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003069 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003070 return;
3071 }
3072
Richard Smithf4bb8d02012-07-05 08:39:21 +00003073 // C++11 [dcl.init.list]p3:
3074 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003075 if (!DestType->isAggregateType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003076 if (S.getLangOpts().CPlusPlus0x) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003077 // - Otherwise, if the initializer list has no elements and T is a
3078 // class type with a default constructor, the object is
3079 // value-initialized.
3080 if (InitList->getNumInits() == 0) {
3081 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3082 if (RD->hasDeclaredDefaultConstructor() ||
3083 RD->needsImplicitDefaultConstructor()) {
3084 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3085 return;
3086 }
3087 }
3088
3089 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3090 // an initializer_list object constructed [...]
3091 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3092 return;
3093
3094 // - Otherwise, if T is a class type, constructors are considered.
Sebastian Redld2231c92012-02-19 12:27:43 +00003095 Expr *Arg = InitList;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003096 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3097 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003098 } else
3099 Sequence.SetFailed(
3100 InitializationSequence::FK_InitListBadDestinationType);
3101 return;
3102 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003103 }
3104
Sebastian Redl14b0c192011-09-24 17:48:00 +00003105 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003106 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003107 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003108 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003109 if (CheckInitList.HadError()) {
3110 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3111 return;
3112 }
3113
3114 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003115 Sequence.AddListInitializationStep(DestType);
3116}
Douglas Gregor20093b42009-12-09 23:02:17 +00003117
3118/// \brief Try a reference initialization that involves calling a conversion
3119/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003120static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3121 const InitializedEntity &Entity,
3122 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003123 Expr *Initializer,
3124 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003125 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003126 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003127 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3128 QualType T1 = cv1T1.getUnqualifiedType();
3129 QualType cv2T2 = Initializer->getType();
3130 QualType T2 = cv2T2.getUnqualifiedType();
3131
3132 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003133 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003134 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003135 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003136 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003137 ObjCConversion,
3138 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003139 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003140 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003141 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003142 (void)ObjCLifetimeConversion;
3143
Douglas Gregor20093b42009-12-09 23:02:17 +00003144 // Build the candidate set directly in the initialization sequence
3145 // structure, so that it will persist if we fail.
3146 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3147 CandidateSet.clear();
3148
3149 // Determine whether we are allowed to call explicit constructors or
3150 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003151 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003152 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3153
Douglas Gregor20093b42009-12-09 23:02:17 +00003154 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003155 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3156 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003157 // The type we're converting to is a class type. Enumerate its constructors
3158 // to see if there is a suitable conversion.
3159 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003160
Douglas Gregor20093b42009-12-09 23:02:17 +00003161 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003162 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00003163 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003164 NamedDecl *D = *Con;
3165 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3166
Douglas Gregor20093b42009-12-09 23:02:17 +00003167 // Find the constructor (which may be a template).
3168 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003169 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003170 if (ConstructorTmpl)
3171 Constructor = cast<CXXConstructorDecl>(
3172 ConstructorTmpl->getTemplatedDecl());
3173 else
John McCall9aa472c2010-03-19 07:35:19 +00003174 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
Douglas Gregor20093b42009-12-09 23:02:17 +00003176 if (!Constructor->isInvalidDecl() &&
3177 Constructor->isConvertingConstructor(AllowExplicit)) {
3178 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003179 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003180 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003181 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003182 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003183 else
John McCall9aa472c2010-03-19 07:35:19 +00003184 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003185 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003186 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003187 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003188 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003189 }
John McCall572fc622010-08-17 07:23:57 +00003190 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3191 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003192
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003193 const RecordType *T2RecordType = 0;
3194 if ((T2RecordType = T2->getAs<RecordType>()) &&
3195 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003196 // The type we're converting from is a class type, enumerate its conversion
3197 // functions.
3198 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3199
John McCalleec51cf2010-01-20 00:46:10 +00003200 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00003201 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003202 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3203 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003204 NamedDecl *D = *I;
3205 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3206 if (isa<UsingShadowDecl>(D))
3207 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003208
Douglas Gregor20093b42009-12-09 23:02:17 +00003209 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3210 CXXConversionDecl *Conv;
3211 if (ConvTemplate)
3212 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3213 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003214 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
Douglas Gregor20093b42009-12-09 23:02:17 +00003216 // If the conversion function doesn't return a reference type,
3217 // it can't be considered for this conversion unless we're allowed to
3218 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219 // FIXME: Do we need to make sure that we only consider conversion
3220 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003221 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003222 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003223 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3224 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003225 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003226 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003227 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003228 else
John McCall9aa472c2010-03-19 07:35:19 +00003229 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003230 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003231 }
3232 }
3233 }
John McCall572fc622010-08-17 07:23:57 +00003234 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3235 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003236
Douglas Gregor20093b42009-12-09 23:02:17 +00003237 SourceLocation DeclLoc = Initializer->getLocStart();
3238
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003239 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003240 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003242 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003243 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003244
Douglas Gregor20093b42009-12-09 23:02:17 +00003245 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003246
Chandler Carruth25ca4212011-02-25 19:41:05 +00003247 // This is the overload that will actually be used for the initialization, so
3248 // mark it as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +00003249 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003250
Eli Friedman03981012009-12-11 02:42:07 +00003251 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003252 if (isa<CXXConversionDecl>(Function))
3253 T2 = Function->getResultType();
3254 else
3255 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003256
3257 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003258 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003259 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003260 T2.getNonLValueExprType(S.Context),
3261 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003262
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003263 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003264 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003265 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003266 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003267 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003268 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003269 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003270
Douglas Gregor20093b42009-12-09 23:02:17 +00003271 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003272 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003273 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003274 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003275 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003276 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003277 NewDerivedToBase, NewObjCConversion,
3278 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003279 if (NewRefRelationship == Sema::Ref_Incompatible) {
3280 // If the type we've converted to is not reference-related to the
3281 // type we're looking for, then there is another conversion step
3282 // we need to perform to produce a temporary of the right type
3283 // that we'll be binding to.
3284 ImplicitConversionSequence ICS;
3285 ICS.setStandard();
3286 ICS.Standard = Best->FinalConversion;
3287 T2 = ICS.Standard.getToType(2);
3288 Sequence.AddConversionSequenceStep(ICS, T2);
3289 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003290 Sequence.AddDerivedToBaseCastStep(
3291 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003292 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003293 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003294 else if (NewObjCConversion)
3295 Sequence.AddObjCObjectConversionStep(
3296 S.Context.getQualifiedType(T1,
3297 T2.getNonReferenceType().getQualifiers()));
3298
Douglas Gregor20093b42009-12-09 23:02:17 +00003299 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003300 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003301
Douglas Gregor20093b42009-12-09 23:02:17 +00003302 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3303 return OR_Success;
3304}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305
Richard Smith83da2e72011-10-19 16:55:56 +00003306static void CheckCXX98CompatAccessibleCopy(Sema &S,
3307 const InitializedEntity &Entity,
3308 Expr *CurInitExpr);
3309
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003310/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3311static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003312 const InitializedEntity &Entity,
3313 const InitializationKind &Kind,
3314 Expr *Initializer,
3315 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003316 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003317 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003318 Qualifiers T1Quals;
3319 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003320 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003321 Qualifiers T2Quals;
3322 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003323
Douglas Gregor20093b42009-12-09 23:02:17 +00003324 // If the initializer is the address of an overloaded function, try
3325 // to resolve the overloaded function. If all goes well, T2 is the
3326 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003327 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3328 T1, Sequence))
3329 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003330
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003331 // Delegate everything else to a subfunction.
3332 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3333 T1Quals, cv2T2, T2, T2Quals, Sequence);
3334}
3335
3336/// \brief Reference initialization without resolving overloaded functions.
3337static void TryReferenceInitializationCore(Sema &S,
3338 const InitializedEntity &Entity,
3339 const InitializationKind &Kind,
3340 Expr *Initializer,
3341 QualType cv1T1, QualType T1,
3342 Qualifiers T1Quals,
3343 QualType cv2T2, QualType T2,
3344 Qualifiers T2Quals,
3345 InitializationSequence &Sequence) {
3346 QualType DestType = Entity.getType();
3347 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003348 // Compute some basic properties of the types and the initializer.
3349 bool isLValueRef = DestType->isLValueReferenceType();
3350 bool isRValueRef = !isLValueRef;
3351 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003352 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003353 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003354 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003355 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003356 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003357 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003358
Douglas Gregor20093b42009-12-09 23:02:17 +00003359 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003361 // "cv2 T2" as follows:
3362 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003364 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003365 // Note the analogous bullet points for rvlaue refs to functions. Because
3366 // there are no function rvalues in C++, rvalue refs to functions are treated
3367 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003368 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003369 bool T1Function = T1->isFunctionType();
3370 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003372 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003374 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003376 // reference-compatible with "cv2 T2," or
3377 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003379 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003380 // can occur. However, we do pay attention to whether it is a bit-field
3381 // to decide whether we're actually binding to a temporary created from
3382 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 if (DerivedToBase)
3384 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003386 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003387 else if (ObjCConversion)
3388 Sequence.AddObjCObjectConversionStep(
3389 S.Context.getQualifiedType(T1, T2Quals));
3390
Chandler Carruth5535c382010-01-12 20:32:25 +00003391 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003392 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003393 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003394 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003395 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003396 return;
3397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003398
3399 // - has a class type (i.e., T2 is a class type), where T1 is not
3400 // reference-related to T2, and can be implicitly converted to an
3401 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3402 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003403 // applicable conversion functions (13.3.1.6) and choosing the best
3404 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003405 // If we have an rvalue ref to function type here, the rhs must be
3406 // an rvalue.
3407 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3408 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003409 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003410 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003411 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003412 Sequence);
3413 if (ConvOvlResult == OR_Success)
3414 return;
John McCall1d318332010-01-12 00:44:57 +00003415 if (ConvOvlResult != OR_No_Viable_Function) {
3416 Sequence.SetOverloadFailure(
3417 InitializationSequence::FK_ReferenceInitOverloadFailed,
3418 ConvOvlResult);
3419 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003420 }
3421 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003422
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003424 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003425 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003426 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003427 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3428 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3429 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003430 Sequence.SetOverloadFailure(
3431 InitializationSequence::FK_ReferenceInitOverloadFailed,
3432 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003433 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003434 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003435 ? (RefRelationship == Sema::Ref_Related
3436 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3437 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3438 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003439
Douglas Gregor20093b42009-12-09 23:02:17 +00003440 return;
3441 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003442
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003443 // - If the initializer expression
3444 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3445 // "cv1 T1" is reference-compatible with "cv2 T2"
3446 // Note: functions are handled below.
3447 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003448 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003449 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003450 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003451 (InitCategory.isXValue() ||
3452 (InitCategory.isPRValue() && T2->isRecordType()) ||
3453 (InitCategory.isPRValue() && T2->isArrayType()))) {
3454 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3455 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003456 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3457 // compiler the freedom to perform a copy here or bind to the
3458 // object, while C++0x requires that we bind directly to the
3459 // object. Hence, we always bind to the object without making an
3460 // extra copy. However, in C++03 requires that we check for the
3461 // presence of a suitable copy constructor:
3462 //
3463 // The constructor that would be used to make the copy shall
3464 // be callable whether or not the copy is actually done.
David Blaikie4e4d0842012-03-11 07:00:24 +00003465 if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003466 Sequence.AddExtraneousCopyToTemporary(cv2T2);
David Blaikie4e4d0842012-03-11 07:00:24 +00003467 else if (S.getLangOpts().CPlusPlus0x)
Richard Smith83da2e72011-10-19 16:55:56 +00003468 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003470
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003471 if (DerivedToBase)
3472 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3473 ValueKind);
3474 else if (ObjCConversion)
3475 Sequence.AddObjCObjectConversionStep(
3476 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003477
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003478 if (T1Quals != T2Quals)
3479 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003480 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003481 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003482 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003483 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484
3485 // - has a class type (i.e., T2 is a class type), where T1 is not
3486 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003487 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3488 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003489 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003490 if (RefRelationship == Sema::Ref_Incompatible) {
3491 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3492 Kind, Initializer,
3493 /*AllowRValues=*/true,
3494 Sequence);
3495 if (ConvOvlResult)
3496 Sequence.SetOverloadFailure(
3497 InitializationSequence::FK_ReferenceInitOverloadFailed,
3498 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003499
Douglas Gregor20093b42009-12-09 23:02:17 +00003500 return;
3501 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003502
Douglas Gregor20093b42009-12-09 23:02:17 +00003503 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3504 return;
3505 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003506
3507 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003508 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003509 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003510 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003511
Douglas Gregor20093b42009-12-09 23:02:17 +00003512 // Determine whether we are allowed to call explicit constructors or
3513 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003514 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003515
3516 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3517
John McCallf85e1932011-06-15 23:02:42 +00003518 ImplicitConversionSequence ICS
3519 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003520 /*SuppressUserConversions*/ false,
3521 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003522 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003523 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3524 /*AllowObjCWritebackConversion=*/false);
3525
3526 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003527 // FIXME: Use the conversion function set stored in ICS to turn
3528 // this into an overloading ambiguity diagnostic. However, we need
3529 // to keep that set as an OverloadCandidateSet rather than as some
3530 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003531 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3532 Sequence.SetOverloadFailure(
3533 InitializationSequence::FK_ReferenceInitOverloadFailed,
3534 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003535 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3536 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003537 else
3538 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 return;
John McCallf85e1932011-06-15 23:02:42 +00003540 } else {
3541 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003542 }
3543
3544 // [...] If T1 is reference-related to T2, cv1 must be the
3545 // same cv-qualification as, or greater cv-qualification
3546 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003547 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3548 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003550 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003551 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3552 return;
3553 }
3554
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003555 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003556 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003557 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003558 InitCategory.isLValue()) {
3559 Sequence.SetFailed(
3560 InitializationSequence::FK_RValueReferenceBindingToLValue);
3561 return;
3562 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003563
Douglas Gregor20093b42009-12-09 23:02:17 +00003564 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3565 return;
3566}
3567
3568/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003569/// (C++ [dcl.init.string], C99 6.7.8).
3570static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003571 const InitializedEntity &Entity,
3572 const InitializationKind &Kind,
3573 Expr *Initializer,
3574 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003575 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003576}
3577
Douglas Gregor71d17402009-12-15 00:01:57 +00003578/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003579static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003580 const InitializedEntity &Entity,
3581 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003582 InitializationSequence &Sequence,
3583 InitListExpr *InitList) {
3584 assert((!InitList || InitList->getNumInits() == 0) &&
3585 "Shouldn't use value-init for non-empty init lists");
3586
Richard Smith1d0c9a82012-02-14 21:14:13 +00003587 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003588 //
3589 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003590 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003591
Douglas Gregor71d17402009-12-15 00:01:57 +00003592 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003593 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003594
Douglas Gregor71d17402009-12-15 00:01:57 +00003595 if (const RecordType *RT = T->getAs<RecordType>()) {
3596 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003597 bool NeedZeroInitialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00003598 if (!S.getLangOpts().CPlusPlus0x) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003599 // C++98:
3600 // -- if T is a class type (clause 9) with a user-declared constructor
3601 // (12.1), then the default constructor for T is called (and the
3602 // initialization is ill-formed if T has no accessible default
3603 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003604 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003605 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003606 } else {
3607 // C++11:
3608 // -- if T is a class type (clause 9) with either no default constructor
3609 // (12.1 [class.ctor]) or a default constructor that is user-provided
3610 // or deleted, then the object is default-initialized;
3611 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3612 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003613 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003614 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003615
Richard Smith1d0c9a82012-02-14 21:14:13 +00003616 // -- if T is a (possibly cv-qualified) non-union class type without a
3617 // user-provided or deleted default constructor, then the object is
3618 // zero-initialized and, if T has a non-trivial default constructor,
3619 // default-initialized;
Richard Smithd079abf2012-05-07 01:07:30 +00003620 // FIXME: The 'non-union' here is a defect (not yet assigned an issue
3621 // number). Update the quotation when the defect is resolved.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003622 if (NeedZeroInitialization)
3623 Sequence.AddZeroInitializationStep(Entity.getType());
3624
3625 // If this is list-value-initialization, pass the empty init list on when
3626 // building the constructor call. This affects the semantics of a few
3627 // things (such as whether an explicit default constructor can be called).
3628 Expr *InitListAsExpr = InitList;
3629 Expr **Args = InitList ? &InitListAsExpr : 0;
3630 unsigned NumArgs = InitList ? 1 : 0;
3631 bool InitListSyntax = InitList;
3632
3633 return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3634 Sequence, InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003635 }
3636 }
3637
Douglas Gregord6542d82009-12-22 15:35:07 +00003638 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003639}
3640
Douglas Gregor99a2e602009-12-16 01:38:02 +00003641/// \brief Attempt default initialization (C++ [dcl.init]p6).
3642static void TryDefaultInitialization(Sema &S,
3643 const InitializedEntity &Entity,
3644 const InitializationKind &Kind,
3645 InitializationSequence &Sequence) {
3646 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003647
Douglas Gregor99a2e602009-12-16 01:38:02 +00003648 // C++ [dcl.init]p6:
3649 // To default-initialize an object of type T means:
3650 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003651 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3652
Douglas Gregor99a2e602009-12-16 01:38:02 +00003653 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3654 // constructor for T is called (and the initialization is ill-formed if
3655 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003656 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003657 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3658 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003659 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003660
Douglas Gregor99a2e602009-12-16 01:38:02 +00003661 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003662
Douglas Gregor99a2e602009-12-16 01:38:02 +00003663 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003665 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003666 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003667 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003668 return;
3669 }
3670
3671 // If the destination type has a lifetime property, zero-initialize it.
3672 if (DestType.getQualifiers().hasObjCLifetime()) {
3673 Sequence.AddZeroInitializationStep(Entity.getType());
3674 return;
3675 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003676}
3677
Douglas Gregor20093b42009-12-09 23:02:17 +00003678/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3679/// which enumerates all conversion functions and performs overload resolution
3680/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003681static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003682 const InitializedEntity &Entity,
3683 const InitializationKind &Kind,
3684 Expr *Initializer,
3685 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003686 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003687 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3688 QualType SourceType = Initializer->getType();
3689 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3690 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003691
Douglas Gregor4a520a22009-12-14 17:27:33 +00003692 // Build the candidate set directly in the initialization sequence
3693 // structure, so that it will persist if we fail.
3694 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3695 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696
Douglas Gregor4a520a22009-12-14 17:27:33 +00003697 // Determine whether we are allowed to call explicit constructors or
3698 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003699 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003700
Douglas Gregor4a520a22009-12-14 17:27:33 +00003701 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3702 // The type we're converting to is a class type. Enumerate its constructors
3703 // to see if there is a suitable conversion.
3704 CXXRecordDecl *DestRecordDecl
3705 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003706
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003707 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003709 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003710 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003711 Con != ConEnd; ++Con) {
3712 NamedDecl *D = *Con;
3713 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003715 // Find the constructor (which may be a template).
3716 CXXConstructorDecl *Constructor = 0;
3717 FunctionTemplateDecl *ConstructorTmpl
3718 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003719 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003720 Constructor = cast<CXXConstructorDecl>(
3721 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003722 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003723 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003724
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003725 if (!Constructor->isInvalidDecl() &&
3726 Constructor->isConvertingConstructor(AllowExplicit)) {
3727 if (ConstructorTmpl)
3728 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3729 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003730 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003731 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003732 else
3733 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003734 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003735 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003737 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003738 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003739 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003740
3741 SourceLocation DeclLoc = Initializer->getLocStart();
3742
Douglas Gregor4a520a22009-12-14 17:27:33 +00003743 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3744 // The type we're converting from is a class type, enumerate its conversion
3745 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003746
Eli Friedman33c2da92009-12-20 22:12:03 +00003747 // We can only enumerate the conversion functions for a complete type; if
3748 // the type isn't complete, simply skip this step.
3749 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3750 CXXRecordDecl *SourceRecordDecl
3751 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003752
John McCalleec51cf2010-01-20 00:46:10 +00003753 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003754 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003755 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003757 I != E; ++I) {
3758 NamedDecl *D = *I;
3759 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3760 if (isa<UsingShadowDecl>(D))
3761 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003762
Eli Friedman33c2da92009-12-20 22:12:03 +00003763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3764 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003765 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003766 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003767 else
John McCall32daa422010-03-31 01:36:47 +00003768 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003769
Eli Friedman33c2da92009-12-20 22:12:03 +00003770 if (AllowExplicit || !Conv->isExplicit()) {
3771 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003772 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003773 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003774 CandidateSet);
3775 else
John McCall9aa472c2010-03-19 07:35:19 +00003776 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003777 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003778 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003779 }
3780 }
3781 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782
3783 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003784 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003785 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003786 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003787 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003789 Result);
3790 return;
3791 }
John McCall1d318332010-01-12 00:44:57 +00003792
Douglas Gregor4a520a22009-12-14 17:27:33 +00003793 FunctionDecl *Function = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00003794 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003795 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003796
Douglas Gregor4a520a22009-12-14 17:27:33 +00003797 if (isa<CXXConstructorDecl>(Function)) {
3798 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003799 // subsumed by the initialization. Per DR5, the created temporary is of the
3800 // cv-unqualified type of the destination.
3801 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3802 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003803 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003804 return;
3805 }
3806
3807 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003808 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003809 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003810 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003811 // the resulting temporary object (possible to create an object of
3812 // a base class type). That copy is not a separate conversion, so
3813 // we just make a note of the actual destination type (possibly a
3814 // base class of the type returned by the conversion function) and
3815 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003816 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3817 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003818 return;
3819 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003820
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003821 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3822 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003824 // If the conversion following the call to the conversion function
3825 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003826 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3827 Best->FinalConversion.Third) {
3828 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003829 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003830 ICS.Standard = Best->FinalConversion;
3831 Sequence.AddConversionSequenceStep(ICS, DestType);
3832 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003833}
3834
John McCallf85e1932011-06-15 23:02:42 +00003835/// The non-zero enum values here are indexes into diagnostic alternatives.
3836enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3837
3838/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003839static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3840 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003841 // Skip parens.
3842 e = e->IgnoreParens();
3843
3844 // Skip address-of nodes.
3845 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3846 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003847 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003848
3849 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003850 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3851 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003852 case CK_Dependent:
3853 case CK_BitCast:
3854 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003855 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003856 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003857
3858 case CK_ArrayToPointerDecay:
3859 return IIK_nonscalar;
3860
3861 case CK_NullToPointer:
3862 return IIK_okay;
3863
3864 default:
3865 break;
3866 }
3867
3868 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00003869 } else if (isa<DeclRefExpr>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003870 if (!isAddressOf) return IIK_nonlocal;
3871
John McCallf4b88a42012-03-10 09:33:50 +00003872 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3873 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00003874
3875 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003876
3877 // If we have a conditional operator, check both sides.
3878 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003879 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003880 return iik;
3881
John McCallc03fa492011-06-27 23:59:58 +00003882 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003883
3884 // These are never scalar.
3885 } else if (isa<ArraySubscriptExpr>(e)) {
3886 return IIK_nonscalar;
3887
3888 // Otherwise, it needs to be a null pointer constant.
3889 } else {
3890 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3891 ? IIK_okay : IIK_nonlocal);
3892 }
3893
3894 return IIK_nonlocal;
3895}
3896
3897/// Check whether the given expression is a valid operand for an
3898/// indirect copy/restore.
3899static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3900 assert(src->isRValue());
3901
John McCallc03fa492011-06-27 23:59:58 +00003902 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003903 if (iik == IIK_okay) return;
3904
3905 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3906 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3907 << src->getSourceRange();
3908}
3909
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003910/// \brief Determine whether we have compatible array types for the
3911/// purposes of GNU by-copy array initialization.
3912static bool hasCompatibleArrayTypes(ASTContext &Context,
3913 const ArrayType *Dest,
3914 const ArrayType *Source) {
3915 // If the source and destination array types are equivalent, we're
3916 // done.
3917 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3918 return true;
3919
3920 // Make sure that the element types are the same.
3921 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3922 return false;
3923
3924 // The only mismatch we allow is when the destination is an
3925 // incomplete array type and the source is a constant array type.
3926 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3927}
3928
John McCallf85e1932011-06-15 23:02:42 +00003929static bool tryObjCWritebackConversion(Sema &S,
3930 InitializationSequence &Sequence,
3931 const InitializedEntity &Entity,
3932 Expr *Initializer) {
3933 bool ArrayDecay = false;
3934 QualType ArgType = Initializer->getType();
3935 QualType ArgPointee;
3936 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3937 ArrayDecay = true;
3938 ArgPointee = ArgArrayType->getElementType();
3939 ArgType = S.Context.getPointerType(ArgPointee);
3940 }
3941
3942 // Handle write-back conversion.
3943 QualType ConvertedArgType;
3944 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3945 ConvertedArgType))
3946 return false;
3947
3948 // We should copy unless we're passing to an argument explicitly
3949 // marked 'out'.
3950 bool ShouldCopy = true;
3951 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3952 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3953
3954 // Do we need an lvalue conversion?
3955 if (ArrayDecay || Initializer->isGLValue()) {
3956 ImplicitConversionSequence ICS;
3957 ICS.setStandard();
3958 ICS.Standard.setAsIdentityConversion();
3959
3960 QualType ResultType;
3961 if (ArrayDecay) {
3962 ICS.Standard.First = ICK_Array_To_Pointer;
3963 ResultType = S.Context.getPointerType(ArgPointee);
3964 } else {
3965 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3966 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3967 }
3968
3969 Sequence.AddConversionSequenceStep(ICS, ResultType);
3970 }
3971
3972 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3973 return true;
3974}
3975
Douglas Gregor20093b42009-12-09 23:02:17 +00003976InitializationSequence::InitializationSequence(Sema &S,
3977 const InitializedEntity &Entity,
3978 const InitializationKind &Kind,
3979 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003980 unsigned NumArgs)
3981 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003982 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregor20093b42009-12-09 23:02:17 +00003984 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003985 // The semantics of initializers are as follows. The destination type is
3986 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003987 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003989 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003990 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003991
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003992 if (DestType->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +00003993 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003994 SequenceKind = DependentSequence;
3995 return;
3996 }
3997
Sebastian Redl7491c492011-06-05 13:59:11 +00003998 // Almost everything is a normal sequence.
3999 setSequenceKind(NormalSequence);
4000
John McCall241d5582010-12-07 22:54:16 +00004001 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00004002 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00004003 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00004004 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4005 if (result.isInvalid()) {
4006 SetFailed(FK_PlaceholderType);
4007 return;
John McCall5acb0c92011-10-17 18:40:02 +00004008 }
John McCall32509f12011-11-15 01:35:18 +00004009 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00004010 }
John McCall241d5582010-12-07 22:54:16 +00004011
John McCall5acb0c92011-10-17 18:40:02 +00004012
Douglas Gregor20093b42009-12-09 23:02:17 +00004013 QualType SourceType;
4014 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004015 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004016 Initializer = Args[0];
4017 if (!isa<InitListExpr>(Initializer))
4018 SourceType = Initializer->getType();
4019 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004020
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004021 // - If the initializer is a (non-parenthesized) braced-init-list, the
4022 // object is list-initialized (8.5.4).
4023 if (Kind.getKind() != InitializationKind::IK_Direct) {
4024 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4025 TryListInitialization(S, Entity, Kind, InitList, *this);
4026 return;
4027 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004028 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004029
Douglas Gregor20093b42009-12-09 23:02:17 +00004030 // - If the destination type is a reference type, see 8.5.3.
4031 if (DestType->isReferenceType()) {
4032 // C++0x [dcl.init.ref]p1:
4033 // A variable declared to be a T& or T&&, that is, "reference to type T"
4034 // (8.3.2), shall be initialized by an object, or function, of type T or
4035 // by an object that can be converted into a T.
4036 // (Therefore, multiple arguments are not permitted.)
4037 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004038 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004039 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004040 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004041 return;
4042 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004043
Douglas Gregor20093b42009-12-09 23:02:17 +00004044 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004045 if (Kind.getKind() == InitializationKind::IK_Value ||
4046 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004047 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004048 return;
4049 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004050
Douglas Gregor99a2e602009-12-16 01:38:02 +00004051 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004052 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004053 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004054 return;
4055 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004056
John McCallce6c9b72011-02-21 07:22:22 +00004057 // - If the destination type is an array of characters, an array of
4058 // char16_t, an array of char32_t, or an array of wchar_t, and the
4059 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004060 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004061 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004062 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004063 if (Initializer && isa<VariableArrayType>(DestAT)) {
4064 SetFailed(FK_VariableLengthArrayHasInitializer);
4065 return;
4066 }
4067
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004068 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004069 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004070 return;
4071 }
4072
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004073 // Note: as an GNU C extension, we allow initialization of an
4074 // array from a compound literal that creates an array of the same
4075 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004076 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004077 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4078 Initializer->getType()->isArrayType()) {
4079 const ArrayType *SourceAT
4080 = Context.getAsArrayType(Initializer->getType());
4081 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004082 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004083 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004084 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004085 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004086 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004087 }
Richard Smith0f163e92012-02-15 22:38:09 +00004088 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004089 // Note: as a GNU C++ extension, we allow list-initialization of a
4090 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004091 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004092 Entity.getKind() == InitializedEntity::EK_Member &&
4093 Initializer && isa<InitListExpr>(Initializer)) {
4094 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4095 *this);
4096 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004097 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004098 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004099 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004100 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004101
Douglas Gregor20093b42009-12-09 23:02:17 +00004102 return;
4103 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004104
John McCallf85e1932011-06-15 23:02:42 +00004105 // Determine whether we should consider writeback conversions for
4106 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004107 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004108 Entity.getKind() == InitializedEntity::EK_Parameter;
4109
4110 // We're at the end of the line for C: it's either a write-back conversion
4111 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004112 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004113 // If allowed, check whether this is an Objective-C writeback conversion.
4114 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004115 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004116 return;
4117 }
4118
4119 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004120 AddCAssignmentStep(DestType);
4121 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004122 return;
4123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004124
David Blaikie4e4d0842012-03-11 07:00:24 +00004125 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004126
Douglas Gregor20093b42009-12-09 23:02:17 +00004127 // - If the destination type is a (possibly cv-qualified) class type:
4128 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004129 // - If the initialization is direct-initialization, or if it is
4130 // copy-initialization where the cv-unqualified version of the
4131 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004132 // class of the destination, constructors are considered. [...]
4133 if (Kind.getKind() == InitializationKind::IK_Direct ||
4134 (Kind.getKind() == InitializationKind::IK_Copy &&
4135 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4136 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004137 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004138 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004139 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004140 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004141 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004142 // used) to a derived class thereof are enumerated as described in
4143 // 13.3.1.4, and the best one is chosen through overload resolution
4144 // (13.3).
4145 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004146 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004147 return;
4148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004149
Douglas Gregor99a2e602009-12-16 01:38:02 +00004150 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004151 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004152 return;
4153 }
4154 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004155
4156 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004157 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004158 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004159 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4160 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004161 return;
4162 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163
Douglas Gregor20093b42009-12-09 23:02:17 +00004164 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004165 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004166 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004167 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004168 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004169
4170 ImplicitConversionSequence ICS
4171 = S.TryImplicitConversion(Initializer, Entity.getType(),
4172 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004173 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004174 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004175 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4176 allowObjCWritebackConversion);
4177
4178 if (ICS.isStandard() &&
4179 ICS.Standard.Second == ICK_Writeback_Conversion) {
4180 // Objective-C ARC writeback conversion.
4181
4182 // We should copy unless we're passing to an argument explicitly
4183 // marked 'out'.
4184 bool ShouldCopy = true;
4185 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4186 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4187
4188 // If there was an lvalue adjustment, add it as a separate conversion.
4189 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4190 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4191 ImplicitConversionSequence LvalueICS;
4192 LvalueICS.setStandard();
4193 LvalueICS.Standard.setAsIdentityConversion();
4194 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4195 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004196 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004197 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004198
4199 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004200 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004201 DeclAccessPair dap;
4202 if (Initializer->getType() == Context.OverloadTy &&
4203 !S.ResolveAddressOfOverloadedFunction(Initializer
4204 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004205 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004206 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004207 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004208 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004209 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004210
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004211 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004212 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004213}
4214
4215InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004216 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004217 StepEnd = Steps.end();
4218 Step != StepEnd; ++Step)
4219 Step->Destroy();
4220}
4221
4222//===----------------------------------------------------------------------===//
4223// Perform initialization
4224//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004225static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004226getAssignmentAction(const InitializedEntity &Entity) {
4227 switch(Entity.getKind()) {
4228 case InitializedEntity::EK_Variable:
4229 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004230 case InitializedEntity::EK_Exception:
4231 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004232 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004233 return Sema::AA_Initializing;
4234
4235 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004237 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4238 return Sema::AA_Sending;
4239
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004240 return Sema::AA_Passing;
4241
4242 case InitializedEntity::EK_Result:
4243 return Sema::AA_Returning;
4244
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004245 case InitializedEntity::EK_Temporary:
4246 // FIXME: Can we tell apart casting vs. converting?
4247 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004248
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004249 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004250 case InitializedEntity::EK_ArrayElement:
4251 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004252 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004253 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004254 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004255 return Sema::AA_Initializing;
4256 }
4257
David Blaikie7530c032012-01-17 06:56:22 +00004258 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004259}
4260
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004261/// \brief Whether we should binding a created object as a temporary when
4262/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004263static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004264 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004265 case InitializedEntity::EK_ArrayElement:
4266 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004267 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004268 case InitializedEntity::EK_New:
4269 case InitializedEntity::EK_Variable:
4270 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004271 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004272 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004273 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004274 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004275 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004276 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004277 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004279 case InitializedEntity::EK_Parameter:
4280 case InitializedEntity::EK_Temporary:
4281 return true;
4282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004284 llvm_unreachable("missed an InitializedEntity kind?");
4285}
4286
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004287/// \brief Whether the given entity, when initialized with an object
4288/// created for that initialization, requires destruction.
4289static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4290 switch (Entity.getKind()) {
4291 case InitializedEntity::EK_Member:
4292 case InitializedEntity::EK_Result:
4293 case InitializedEntity::EK_New:
4294 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004295 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004296 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004297 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004298 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004299 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004300 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004302 case InitializedEntity::EK_Variable:
4303 case InitializedEntity::EK_Parameter:
4304 case InitializedEntity::EK_Temporary:
4305 case InitializedEntity::EK_ArrayElement:
4306 case InitializedEntity::EK_Exception:
4307 return true;
4308 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309
4310 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004311}
4312
Richard Smith83da2e72011-10-19 16:55:56 +00004313/// \brief Look for copy and move constructors and constructor templates, for
4314/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4315static void LookupCopyAndMoveConstructors(Sema &S,
4316 OverloadCandidateSet &CandidateSet,
4317 CXXRecordDecl *Class,
4318 Expr *CurInitExpr) {
4319 DeclContext::lookup_iterator Con, ConEnd;
4320 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4321 Con != ConEnd; ++Con) {
4322 CXXConstructorDecl *Constructor = 0;
4323
4324 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4325 // Handle copy/moveconstructors, only.
4326 if (!Constructor || Constructor->isInvalidDecl() ||
4327 !Constructor->isCopyOrMoveConstructor() ||
4328 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4329 continue;
4330
4331 DeclAccessPair FoundDecl
4332 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4333 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004334 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004335 continue;
4336 }
4337
4338 // Handle constructor templates.
4339 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4340 if (ConstructorTmpl->isInvalidDecl())
4341 continue;
4342
4343 Constructor = cast<CXXConstructorDecl>(
4344 ConstructorTmpl->getTemplatedDecl());
4345 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4346 continue;
4347
4348 // FIXME: Do we need to limit this to copy-constructor-like
4349 // candidates?
4350 DeclAccessPair FoundDecl
4351 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4352 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004353 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004354 }
4355}
4356
4357/// \brief Get the location at which initialization diagnostics should appear.
4358static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4359 Expr *Initializer) {
4360 switch (Entity.getKind()) {
4361 case InitializedEntity::EK_Result:
4362 return Entity.getReturnLoc();
4363
4364 case InitializedEntity::EK_Exception:
4365 return Entity.getThrowLoc();
4366
4367 case InitializedEntity::EK_Variable:
4368 return Entity.getDecl()->getLocation();
4369
Douglas Gregor47736542012-02-15 16:57:26 +00004370 case InitializedEntity::EK_LambdaCapture:
4371 return Entity.getCaptureLoc();
4372
Richard Smith83da2e72011-10-19 16:55:56 +00004373 case InitializedEntity::EK_ArrayElement:
4374 case InitializedEntity::EK_Member:
4375 case InitializedEntity::EK_Parameter:
4376 case InitializedEntity::EK_Temporary:
4377 case InitializedEntity::EK_New:
4378 case InitializedEntity::EK_Base:
4379 case InitializedEntity::EK_Delegating:
4380 case InitializedEntity::EK_VectorElement:
4381 case InitializedEntity::EK_ComplexElement:
4382 case InitializedEntity::EK_BlockElement:
4383 return Initializer->getLocStart();
4384 }
4385 llvm_unreachable("missed an InitializedEntity kind?");
4386}
4387
Douglas Gregor523d46a2010-04-18 07:40:54 +00004388/// \brief Make a (potentially elidable) temporary copy of the object
4389/// provided by the given initializer by calling the appropriate copy
4390/// constructor.
4391///
4392/// \param S The Sema object used for type-checking.
4393///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004394/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004395/// the type of the initializer expression or a superclass thereof.
4396///
James Dennett1dfbd922012-06-14 21:40:34 +00004397/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004398///
4399/// \param CurInit The initializer expression.
4400///
4401/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4402/// is permitted in C++03 (but not C++0x) when binding a reference to
4403/// an rvalue.
4404///
4405/// \returns An expression that copies the initializer expression into
4406/// a temporary object, or an error expression if a copy could not be
4407/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004408static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004409 QualType T,
4410 const InitializedEntity &Entity,
4411 ExprResult CurInit,
4412 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004413 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004414 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004415 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004416 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004417 Class = cast<CXXRecordDecl>(Record->getDecl());
4418 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004419 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004420
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004421 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004422 // When certain criteria are met, an implementation is allowed to
4423 // omit the copy/move construction of a class object, even if the
4424 // copy/move constructor and/or destructor for the object have
4425 // side effects. [...]
4426 // - when a temporary class object that has not been bound to a
4427 // reference (12.2) would be copied/moved to a class object
4428 // with the same cv-unqualified type, the copy/move operation
4429 // can be omitted by constructing the temporary object
4430 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004431 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004432 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004433 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004434 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004435 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004436 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004437 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004438
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004440 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004441 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004442
Douglas Gregorcc15f012011-01-21 19:38:21 +00004443 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004444 // Only consider constructors and constructor templates. Per
4445 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4446 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004447 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004448 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004449
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004450 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4451
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004452 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004453 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004454 case OR_Success:
4455 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004456
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004457 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004458 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4459 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4460 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004461 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004462 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004463 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004464 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004465 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004466 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004468 case OR_Ambiguous:
4469 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004470 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004471 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004472 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004473 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004474
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004475 case OR_Deleted:
4476 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004477 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004478 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004479 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004480 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004481 }
4482
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004483 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004484 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004485 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004486
Anders Carlsson9a68a672010-04-21 18:47:17 +00004487 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004488 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004489
4490 if (IsExtraneousCopy) {
4491 // If this is a totally extraneous copy for C++03 reference
4492 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004493 // expression. We don't generate an (elided) copy operation here
4494 // because doing so would require us to pass down a flag to avoid
4495 // infinite recursion, where each step adds another extraneous,
4496 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004497
Douglas Gregor2559a702010-04-18 07:57:34 +00004498 // Instantiate the default arguments of any extra parameters in
4499 // the selected copy constructor, as if we were going to create a
4500 // proper call to the copy constructor.
4501 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4502 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4503 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004504 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004505 break;
4506
4507 // Build the default argument expression; we don't actually care
4508 // if this succeeds or not, because this routine will complain
4509 // if there was a problem.
4510 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4511 }
4512
Douglas Gregor523d46a2010-04-18 07:40:54 +00004513 return S.Owned(CurInitExpr);
4514 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004515
Eli Friedman5f2987c2012-02-02 03:46:19 +00004516 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00004517
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004518 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004519 // constructor call (we might have derived-to-base conversions, or
4520 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004521 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004522 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004523 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004524
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004525 // Actually perform the constructor call.
4526 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004527 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004528 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004529 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004530 CXXConstructExpr::CK_Complete,
4531 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004532
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004533 // If we're supposed to bind temporaries, do so.
4534 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4535 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004536 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004537}
Douglas Gregor20093b42009-12-09 23:02:17 +00004538
Richard Smith83da2e72011-10-19 16:55:56 +00004539/// \brief Check whether elidable copy construction for binding a reference to
4540/// a temporary would have succeeded if we were building in C++98 mode, for
4541/// -Wc++98-compat.
4542static void CheckCXX98CompatAccessibleCopy(Sema &S,
4543 const InitializedEntity &Entity,
4544 Expr *CurInitExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004545 assert(S.getLangOpts().CPlusPlus0x);
Richard Smith83da2e72011-10-19 16:55:56 +00004546
4547 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4548 if (!Record)
4549 return;
4550
4551 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4552 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4553 == DiagnosticsEngine::Ignored)
4554 return;
4555
4556 // Find constructors which would have been considered.
4557 OverloadCandidateSet CandidateSet(Loc);
4558 LookupCopyAndMoveConstructors(
4559 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4560
4561 // Perform overload resolution.
4562 OverloadCandidateSet::iterator Best;
4563 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4564
4565 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4566 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4567 << CurInitExpr->getSourceRange();
4568
4569 switch (OR) {
4570 case OR_Success:
4571 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004572 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004573 // FIXME: Check default arguments as far as that's possible.
4574 break;
4575
4576 case OR_No_Viable_Function:
4577 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004578 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004579 break;
4580
4581 case OR_Ambiguous:
4582 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004583 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004584 break;
4585
4586 case OR_Deleted:
4587 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004588 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004589 break;
4590 }
4591}
4592
Douglas Gregora41a8c52010-04-22 00:20:18 +00004593void InitializationSequence::PrintInitLocationNote(Sema &S,
4594 const InitializedEntity &Entity) {
4595 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4596 if (Entity.getDecl()->getLocation().isInvalid())
4597 return;
4598
4599 if (Entity.getDecl()->getDeclName())
4600 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4601 << Entity.getDecl()->getDeclName();
4602 else
4603 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4604 }
4605}
4606
Sebastian Redl3b802322011-07-14 19:07:55 +00004607static bool isReferenceBinding(const InitializationSequence::Step &s) {
4608 return s.Kind == InitializationSequence::SK_BindReference ||
4609 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4610}
4611
Sebastian Redl10f04a62011-12-22 14:44:04 +00004612static ExprResult
4613PerformConstructorInitialization(Sema &S,
4614 const InitializedEntity &Entity,
4615 const InitializationKind &Kind,
4616 MultiExprArg Args,
4617 const InitializationSequence::Step& Step,
4618 bool &ConstructorInitRequiresZeroInit) {
4619 unsigned NumArgs = Args.size();
4620 CXXConstructorDecl *Constructor
4621 = cast<CXXConstructorDecl>(Step.Function.Function);
4622 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4623
4624 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004625 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004626 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4627 ? Kind.getEqualLoc()
4628 : Kind.getLocation();
4629
4630 if (Kind.getKind() == InitializationKind::IK_Default) {
4631 // Force even a trivial, implicit default constructor to be
4632 // semantically checked. We do this explicitly because we don't build
4633 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004634 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004635 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004636 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004637 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4638 }
4639
4640 ExprResult CurInit = S.Owned((Expr *)0);
4641
Douglas Gregored878af2012-02-24 23:56:31 +00004642 // C++ [over.match.copy]p1:
4643 // - When initializing a temporary to be bound to the first parameter
4644 // of a constructor that takes a reference to possibly cv-qualified
4645 // T as its first argument, called with a single argument in the
4646 // context of direct-initialization, explicit conversion functions
4647 // are also considered.
4648 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4649 Args.size() == 1 &&
4650 Constructor->isCopyOrMoveConstructor();
4651
Sebastian Redl10f04a62011-12-22 14:44:04 +00004652 // Determine the arguments required to actually perform the constructor
4653 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004654 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004655 Loc, ConstructorArgs,
4656 AllowExplicitConv))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004657 return ExprError();
4658
4659
4660 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004661 (Kind.getKind() == InitializationKind::IK_DirectList ||
4662 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4663 (Kind.getKind() == InitializationKind::IK_Direct ||
4664 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004665 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004666 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redl10f04a62011-12-22 14:44:04 +00004667 S.DiagnoseUseOfDecl(Constructor, Loc);
4668
4669 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4670 if (!TSInfo)
4671 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004672 SourceRange ParenRange;
4673 if (Kind.getKind() != InitializationKind::IK_DirectList)
4674 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004675
4676 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4677 Constructor,
4678 TSInfo,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004679 ConstructorArgs,
Sebastian Redl188158d2012-03-08 21:05:45 +00004680 ParenRange,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004681 HadMultipleCandidates,
4682 ConstructorInitRequiresZeroInit));
4683 } else {
4684 CXXConstructExpr::ConstructionKind ConstructKind =
4685 CXXConstructExpr::CK_Complete;
4686
4687 if (Entity.getKind() == InitializedEntity::EK_Base) {
4688 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4689 CXXConstructExpr::CK_VirtualBase :
4690 CXXConstructExpr::CK_NonVirtualBase;
4691 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4692 ConstructKind = CXXConstructExpr::CK_Delegating;
4693 }
4694
4695 // Only get the parenthesis range if it is a direct construction.
4696 SourceRange parenRange =
4697 Kind.getKind() == InitializationKind::IK_Direct ?
4698 Kind.getParenRange() : SourceRange();
4699
4700 // If the entity allows NRVO, mark the construction as elidable
4701 // unconditionally.
4702 if (Entity.allowsNRVO())
4703 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4704 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004705 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004706 HadMultipleCandidates,
4707 ConstructorInitRequiresZeroInit,
4708 ConstructKind,
4709 parenRange);
4710 else
4711 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4712 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004713 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004714 HadMultipleCandidates,
4715 ConstructorInitRequiresZeroInit,
4716 ConstructKind,
4717 parenRange);
4718 }
4719 if (CurInit.isInvalid())
4720 return ExprError();
4721
4722 // Only check access if all of that succeeded.
4723 S.CheckConstructorAccess(Loc, Constructor, Entity,
4724 Step.Function.FoundDecl.getAccess());
4725 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4726
4727 if (shouldBindAsTemporary(Entity))
4728 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4729
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004730 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004731}
4732
Richard Smith36d02af2012-06-04 22:27:30 +00004733/// Determine whether the specified InitializedEntity definitely has a lifetime
4734/// longer than the current full-expression. Conservatively returns false if
4735/// it's unclear.
4736static bool
4737InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4738 const InitializedEntity *Top = &Entity;
4739 while (Top->getParent())
4740 Top = Top->getParent();
4741
4742 switch (Top->getKind()) {
4743 case InitializedEntity::EK_Variable:
4744 case InitializedEntity::EK_Result:
4745 case InitializedEntity::EK_Exception:
4746 case InitializedEntity::EK_Member:
4747 case InitializedEntity::EK_New:
4748 case InitializedEntity::EK_Base:
4749 case InitializedEntity::EK_Delegating:
4750 return true;
4751
4752 case InitializedEntity::EK_ArrayElement:
4753 case InitializedEntity::EK_VectorElement:
4754 case InitializedEntity::EK_BlockElement:
4755 case InitializedEntity::EK_ComplexElement:
4756 // Could not determine what the full initialization is. Assume it might not
4757 // outlive the full-expression.
4758 return false;
4759
4760 case InitializedEntity::EK_Parameter:
4761 case InitializedEntity::EK_Temporary:
4762 case InitializedEntity::EK_LambdaCapture:
4763 // The entity being initialized might not outlive the full-expression.
4764 return false;
4765 }
4766
4767 llvm_unreachable("unknown entity kind");
4768}
4769
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004770ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004771InitializationSequence::Perform(Sema &S,
4772 const InitializedEntity &Entity,
4773 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004774 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004775 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004776 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004777 unsigned NumArgs = Args.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00004778 Diagnose(S, Entity, Kind, Args.data(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004779 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004780 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004781
Sebastian Redl7491c492011-06-05 13:59:11 +00004782 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004783 // If the declaration is a non-dependent, incomplete array type
4784 // that has an initializer, then its type will be completed once
4785 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004786 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004787 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004788 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004789 if (const IncompleteArrayType *ArrayT
4790 = S.Context.getAsIncompleteArrayType(DeclType)) {
4791 // FIXME: We don't currently have the ability to accurately
4792 // compute the length of an initializer list without
4793 // performing full type-checking of the initializer list
4794 // (since we have to determine where braces are implicitly
4795 // introduced and such). So, we fall back to making the array
4796 // type a dependently-sized array type with no specified
4797 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004798 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004799 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004800
Douglas Gregord87b61f2009-12-10 17:56:55 +00004801 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004802 if (DeclaratorDecl *DD = Entity.getDecl()) {
4803 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4804 TypeLoc TL = TInfo->getTypeLoc();
4805 if (IncompleteArrayTypeLoc *ArrayLoc
4806 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4807 Brackets = ArrayLoc->getBracketsRange();
4808 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004809 }
4810
4811 *ResultType
4812 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4813 /*NumElts=*/0,
4814 ArrayT->getSizeModifier(),
4815 ArrayT->getIndexTypeCVRQualifiers(),
4816 Brackets);
4817 }
4818
4819 }
4820 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004821 if (Kind.getKind() == InitializationKind::IK_Direct &&
4822 !Kind.isExplicitCast()) {
4823 // Rebuild the ParenListExpr.
4824 SourceRange ParenRange = Kind.getParenRange();
4825 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004826 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004827 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004828 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00004829 Kind.isExplicitCast() ||
4830 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004831 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004832 }
4833
Sebastian Redl7491c492011-06-05 13:59:11 +00004834 // No steps means no initialization.
4835 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004836 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004837
Richard Smith03544fc2012-04-19 06:58:00 +00004838 if (S.getLangOpts().CPlusPlus0x && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004839 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00004840 Entity.getKind() != InitializedEntity::EK_Parameter) {
4841 // Produce a C++98 compatibility warning if we are initializing a reference
4842 // from an initializer list. For parameters, we produce a better warning
4843 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004844 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00004845 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
4846 << Init->getSourceRange();
4847 }
4848
Richard Smith36d02af2012-06-04 22:27:30 +00004849 // Diagnose cases where we initialize a pointer to an array temporary, and the
4850 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004851 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00004852 Entity.getType()->isPointerType() &&
4853 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004854 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00004855 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
4856 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
4857 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
4858 << Init->getSourceRange();
4859 }
4860
Douglas Gregord6542d82009-12-22 15:35:07 +00004861 QualType DestType = Entity.getType().getNonReferenceType();
4862 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004863 // the same as Entity.getDecl()->getType() in cases involving type merging,
4864 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004865 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004866 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004867 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004868
John McCall60d7b3a2010-08-24 06:29:42 +00004869 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004870
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004871 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004872 // grab the only argument out the Args and place it into the "current"
4873 // initializer.
4874 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004875 case SK_ResolveAddressOfOverloadedFunction:
4876 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004877 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004878 case SK_CastDerivedToBaseLValue:
4879 case SK_BindReference:
4880 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004881 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004882 case SK_UserConversion:
4883 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004884 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004885 case SK_QualificationConversionRValue:
4886 case SK_ConversionSequence:
4887 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004888 case SK_UnwrapInitList:
4889 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004890 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004891 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004892 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004893 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00004894 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00004895 case SK_PassByIndirectCopyRestore:
4896 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00004897 case SK_ProduceObjCObject:
4898 case SK_StdInitializerList: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004899 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004900 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00004901 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004902 break;
John McCallf6a16482010-12-04 03:47:34 +00004903 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004904
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004905 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00004906 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004907 case SK_ZeroInitialization:
4908 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004909 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004910
4911 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004912 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004913 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004914 for (step_iterator Step = step_begin(), StepEnd = step_end();
4915 Step != StepEnd; ++Step) {
4916 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004917 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004918
John Wiegley429bb272011-04-08 18:41:53 +00004919 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004920
Douglas Gregor20093b42009-12-09 23:02:17 +00004921 switch (Step->Kind) {
4922 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004923 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004924 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004925 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004926 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004927 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00004928 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004929 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004930 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004931
Douglas Gregor20093b42009-12-09 23:02:17 +00004932 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004933 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004934 case SK_CastDerivedToBaseLValue: {
4935 // We have a derived-to-base cast that produces either an rvalue or an
4936 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004937
John McCallf871d0c2010-08-07 06:22:56 +00004938 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004939
Douglas Gregor20093b42009-12-09 23:02:17 +00004940 // Casts to inaccessible base classes are allowed with C-style casts.
4941 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4942 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004943 CurInit.get()->getLocStart(),
4944 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004945 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004946 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004947
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004948 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4949 QualType T = SourceType;
4950 if (const PointerType *Pointer = T->getAs<PointerType>())
4951 T = Pointer->getPointeeType();
4952 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004953 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004954 cast<CXXRecordDecl>(RecordTy->getDecl()));
4955 }
4956
John McCall5baba9d2010-08-25 10:28:54 +00004957 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004958 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004959 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004960 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004961 VK_XValue :
4962 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004963 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4964 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004965 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004966 CurInit.get(),
4967 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004968 break;
4969 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004970
Douglas Gregor20093b42009-12-09 23:02:17 +00004971 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004972 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004973 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4974 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004975 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004976 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004977 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004978 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004979 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004980 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004981
John Wiegley429bb272011-04-08 18:41:53 +00004982 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004983 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004984 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4985 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004986 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004987 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004988 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004989 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004990
Douglas Gregor20093b42009-12-09 23:02:17 +00004991 // Reference binding does not have any corresponding ASTs.
4992
4993 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004994 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004995 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004996
Douglas Gregor20093b42009-12-09 23:02:17 +00004997 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004998
Douglas Gregor20093b42009-12-09 23:02:17 +00004999 case SK_BindReferenceToTemporary:
5000 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005001 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005002 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005003
Douglas Gregor03e80032011-06-21 17:03:29 +00005004 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005005 CurInit = new (S.Context) MaterializeTemporaryExpr(
5006 Entity.getType().getNonReferenceType(),
5007 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005008 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005009
5010 // If we're binding to an Objective-C object that has lifetime, we
5011 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005012 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005013 CurInit.get()->getType()->isObjCLifetimeType())
5014 S.ExprNeedsCleanups = true;
5015
Douglas Gregor20093b42009-12-09 23:02:17 +00005016 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005017
Douglas Gregor523d46a2010-04-18 07:40:54 +00005018 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005019 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005020 /*IsExtraneousCopy=*/true);
5021 break;
5022
Douglas Gregor20093b42009-12-09 23:02:17 +00005023 case SK_UserConversion: {
5024 // We have a user-defined conversion that invokes either a constructor
5025 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005026 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005027 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005028 FunctionDecl *Fn = Step->Function.Function;
5029 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005030 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005031 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005032 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005033 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005034 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005035 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005036 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005037
Douglas Gregor20093b42009-12-09 23:02:17 +00005038 // Determine the arguments required to actually perform the constructor
5039 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005040 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005041 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005042 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005043 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005044 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005045
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005046 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005047 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005048 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005049 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00005050 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005051 CXXConstructExpr::CK_Complete,
5052 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005053 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005054 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005055
Anders Carlsson9a68a672010-04-21 18:47:17 +00005056 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005057 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00005058 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005059
John McCall2de56d12010-08-25 11:45:40 +00005060 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005061 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5062 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5063 S.IsDerivedFrom(SourceType, Class))
5064 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005065
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005066 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005067 } else {
5068 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005069 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005070 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005071 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00005072 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005073
5074 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005075 // derived-to-base conversion? I believe the answer is "no", because
5076 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005077 ExprResult CurInitExprRes =
5078 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5079 FoundFn, Conversion);
5080 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005081 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005082 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005083
Douglas Gregor20093b42009-12-09 23:02:17 +00005084 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005085 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5086 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005087 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005088 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005089
John McCall2de56d12010-08-25 11:45:40 +00005090 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005092 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005093 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094
Sebastian Redl3b802322011-07-14 19:07:55 +00005095 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005096 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5097
5098 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005099 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005100 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005102 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005103 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005104 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005105 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley429bb272011-04-08 18:41:53 +00005106 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005107 }
5108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005109
John McCallf871d0c2010-08-07 06:22:56 +00005110 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005111 CurInit.get()->getType(),
5112 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005113 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005114 if (MaybeBindToTemp)
5115 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005116 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005117 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005118 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005119 break;
5120 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005121
Douglas Gregor20093b42009-12-09 23:02:17 +00005122 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005123 case SK_QualificationConversionXValue:
5124 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005125 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005126 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005127 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005128 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005129 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005130 VK_XValue :
5131 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005132 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005133 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005134 }
5135
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005136 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005137 Sema::CheckedConversionKind CCK
5138 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5139 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005140 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005141 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005142 ExprResult CurInitExprRes =
5143 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005144 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005145 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005146 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005147 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005148 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005149 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005150
Douglas Gregord87b61f2009-12-10 17:56:55 +00005151 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005152 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005153 // Hack: We must pass *ResultType if available in order to set the type
5154 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5155 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5156 // temporary, not a reference, so we should pass Ty.
5157 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5158 // Since this step is never used for a reference directly, we explicitly
5159 // unwrap references here and rewrap them afterwards.
5160 // We also need to create a InitializeTemporary entity for this.
5161 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005162 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005163 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5164 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5165 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005166 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00005167 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005168 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005169 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005170
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005171 if (ResultType) {
5172 if ((*ResultType)->isRValueReferenceType())
5173 Ty = S.Context.getRValueReferenceType(Ty);
5174 else if ((*ResultType)->isLValueReferenceType())
5175 Ty = S.Context.getLValueReferenceType(Ty,
5176 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5177 *ResultType = Ty;
5178 }
5179
5180 InitListExpr *StructuredInitList =
5181 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005182 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005183 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005184 break;
5185 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005186
Sebastian Redl10f04a62011-12-22 14:44:04 +00005187 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005188 // When an initializer list is passed for a parameter of type "reference
5189 // to object", we don't get an EK_Temporary entity, but instead an
5190 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005191 // FIXME: This is a hack. What we really should do is create a user
5192 // conversion step for this case, but this makes it considerably more
5193 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005194 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5195 Entity.getType().getNonReferenceType());
5196 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005197 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005198 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005199 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5200 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005201 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005202 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5203 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005204 Kind, Arg, *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005205 ConstructorInitRequiresZeroInit);
5206 break;
5207 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005208
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005209 case SK_UnwrapInitList:
5210 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5211 break;
5212
5213 case SK_RewrapInitList: {
5214 Expr *E = CurInit.take();
5215 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5216 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005217 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005218 ILE->setSyntacticForm(Syntactic);
5219 ILE->setType(E->getType());
5220 ILE->setValueKind(E->getValueKind());
5221 CurInit = S.Owned(ILE);
5222 break;
5223 }
5224
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005225 case SK_ConstructorInitialization: {
5226 // When an initializer list is passed for a parameter of type "reference
5227 // to object", we don't get an EK_Temporary entity, but instead an
5228 // EK_Parameter entity with reference type.
5229 // FIXME: This is a hack. What we really should do is create a user
5230 // conversion step for this case, but this makes it considerably more
5231 // complicated. For now, this will do.
5232 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5233 Entity.getType().getNonReferenceType());
5234 bool UseTemporary = Entity.getType()->isReferenceType();
5235 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5236 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005237 Kind, Args, *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005238 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005239 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005241
Douglas Gregor71d17402009-12-15 00:01:57 +00005242 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005243 step_iterator NextStep = Step;
5244 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005245 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005246 (NextStep->Kind == SK_ConstructorInitialization ||
5247 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005248 // The need for zero-initialization is recorded directly into
5249 // the call to the object's constructor within the next step.
5250 ConstructorInitRequiresZeroInit = true;
5251 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005252 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005253 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005254 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5255 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005256 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005257 Kind.getRange().getBegin());
5258
5259 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5260 TSInfo->getType().getNonLValueExprType(S.Context),
5261 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005262 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005263 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005264 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005265 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005266 break;
5267 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005268
5269 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005270 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005271 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005272 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005273 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5274 if (Result.isInvalid())
5275 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005276 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005277
5278 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005279 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005280 if (ConvTy != Sema::Compatible &&
5281 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005282 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005283 == Sema::Compatible)
5284 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005285 if (CurInitExprRes.isInvalid())
5286 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005287 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005288
Douglas Gregora41a8c52010-04-22 00:20:18 +00005289 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005290 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5291 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005292 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005293 getAssignmentAction(Entity),
5294 &Complained)) {
5295 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005296 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005297 } else if (Complained)
5298 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005299 break;
5300 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005301
5302 case SK_StringInit: {
5303 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005304 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005305 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005306 break;
5307 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005308
5309 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005310 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005311 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005312 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005313 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005314
5315 case SK_ArrayInit:
5316 // Okay: we checked everything before creating this step. Note that
5317 // this is a GNU extension.
5318 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005319 << Step->Type << CurInit.get()->getType()
5320 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005321
5322 // If the destination type is an incomplete array type, update the
5323 // type accordingly.
5324 if (ResultType) {
5325 if (const IncompleteArrayType *IncompleteDest
5326 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5327 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005328 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005329 *ResultType = S.Context.getConstantArrayType(
5330 IncompleteDest->getElementType(),
5331 ConstantSource->getSize(),
5332 ArrayType::Normal, 0);
5333 }
5334 }
5335 }
John McCallf85e1932011-06-15 23:02:42 +00005336 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005337
Richard Smith0f163e92012-02-15 22:38:09 +00005338 case SK_ParenthesizedArrayInit:
5339 // Okay: we checked everything before creating this step. Note that
5340 // this is a GNU extension.
5341 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5342 << CurInit.get()->getSourceRange();
5343 break;
5344
John McCallf85e1932011-06-15 23:02:42 +00005345 case SK_PassByIndirectCopyRestore:
5346 case SK_PassByIndirectRestore:
5347 checkIndirectCopyRestoreSource(S, CurInit.get());
5348 CurInit = S.Owned(new (S.Context)
5349 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5350 Step->Kind == SK_PassByIndirectCopyRestore));
5351 break;
5352
5353 case SK_ProduceObjCObject:
5354 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005355 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005356 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005357 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005358
5359 case SK_StdInitializerList: {
5360 QualType Dest = Step->Type;
5361 QualType E;
5362 bool Success = S.isStdInitializerList(Dest, &E);
5363 (void)Success;
5364 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005365
5366 // If the element type has a destructor, check it.
5367 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5368 if (!RD->hasIrrelevantDestructor()) {
5369 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5370 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5371 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5372 S.PDiag(diag::err_access_dtor_temp) << E);
5373 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5374 }
5375 }
5376 }
5377
Sebastian Redl2b916b82012-01-17 22:49:42 +00005378 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005379 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5380 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005381 unsigned NumInits = ILE->getNumInits();
5382 SmallVector<Expr*, 16> Converted(NumInits);
5383 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5384 S.Context.getConstantArrayType(E,
5385 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5386 NumInits),
5387 ArrayType::Normal, 0));
5388 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5389 0, HiddenArray);
5390 for (unsigned i = 0; i < NumInits; ++i) {
5391 Element.setElementIndex(i);
5392 ExprResult Init = S.Owned(ILE->getInit(i));
5393 ExprResult Res = S.PerformCopyInitialization(Element,
5394 Init.get()->getExprLoc(),
5395 Init);
5396 assert(!Res.isInvalid() && "Result changed since try phase.");
5397 Converted[i] = Res.take();
5398 }
5399 InitListExpr *Semantic = new (S.Context)
5400 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005401 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005402 Semantic->setSyntacticForm(ILE);
5403 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005404 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005405 CurInit = S.Owned(Semantic);
5406 break;
5407 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005408 }
5409 }
John McCall15d7d122010-11-11 03:21:53 +00005410
5411 // Diagnose non-fatal problems with the completed initialization.
5412 if (Entity.getKind() == InitializedEntity::EK_Member &&
5413 cast<FieldDecl>(Entity.getDecl())->isBitField())
5414 S.CheckBitFieldInitialization(Kind.getLocation(),
5415 cast<FieldDecl>(Entity.getDecl()),
5416 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005417
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005418 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005419}
5420
5421//===----------------------------------------------------------------------===//
5422// Diagnose initialization failures
5423//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005425 const InitializedEntity &Entity,
5426 const InitializationKind &Kind,
5427 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005428 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005429 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005430
Douglas Gregord6542d82009-12-22 15:35:07 +00005431 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005432 switch (Failure) {
5433 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005434 // FIXME: Customize for the initialized entity?
5435 if (NumArgs == 0)
5436 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5437 << DestType.getNonReferenceType();
5438 else // FIXME: diagnostic below could be better!
5439 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5440 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005441 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005442
Douglas Gregor20093b42009-12-09 23:02:17 +00005443 case FK_ArrayNeedsInitList:
5444 case FK_ArrayNeedsInitListOrStringLiteral:
5445 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5446 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5447 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005448
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005449 case FK_ArrayTypeMismatch:
5450 case FK_NonConstantArrayInit:
5451 S.Diag(Kind.getLocation(),
5452 (Failure == FK_ArrayTypeMismatch
5453 ? diag::err_array_init_different_type
5454 : diag::err_array_init_non_constant_array))
5455 << DestType.getNonReferenceType()
5456 << Args[0]->getType()
5457 << Args[0]->getSourceRange();
5458 break;
5459
John McCall73076432012-01-05 00:13:19 +00005460 case FK_VariableLengthArrayHasInitializer:
5461 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5462 << Args[0]->getSourceRange();
5463 break;
5464
John McCall6bb80172010-03-30 21:47:33 +00005465 case FK_AddressOfOverloadFailed: {
5466 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005467 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005468 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005469 true,
5470 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005471 break;
John McCall6bb80172010-03-30 21:47:33 +00005472 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005473
Douglas Gregor20093b42009-12-09 23:02:17 +00005474 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005475 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005476 switch (FailedOverloadResult) {
5477 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005478 if (Failure == FK_UserConversionOverloadFailed)
5479 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5480 << Args[0]->getType() << DestType
5481 << Args[0]->getSourceRange();
5482 else
5483 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5484 << DestType << Args[0]->getType()
5485 << Args[0]->getSourceRange();
5486
Ahmed Charles13a140c2012-02-25 11:00:22 +00005487 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5488 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005489 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005490
Douglas Gregor20093b42009-12-09 23:02:17 +00005491 case OR_No_Viable_Function:
5492 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5493 << Args[0]->getType() << DestType.getNonReferenceType()
5494 << Args[0]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005495 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5496 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005497 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005498
Douglas Gregor20093b42009-12-09 23:02:17 +00005499 case OR_Deleted: {
5500 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5501 << Args[0]->getType() << DestType.getNonReferenceType()
5502 << Args[0]->getSourceRange();
5503 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005504 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005505 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5506 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005507 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005508 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005509 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005510 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005511 }
5512 break;
5513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005514
Douglas Gregor20093b42009-12-09 23:02:17 +00005515 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005516 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005517 }
5518 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005519
Douglas Gregor20093b42009-12-09 23:02:17 +00005520 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005521 if (isa<InitListExpr>(Args[0])) {
5522 S.Diag(Kind.getLocation(),
5523 diag::err_lvalue_reference_bind_to_initlist)
5524 << DestType.getNonReferenceType().isVolatileQualified()
5525 << DestType.getNonReferenceType()
5526 << Args[0]->getSourceRange();
5527 break;
5528 }
5529 // Intentional fallthrough
5530
Douglas Gregor20093b42009-12-09 23:02:17 +00005531 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005533 Failure == FK_NonConstLValueReferenceBindingToTemporary
5534 ? diag::err_lvalue_reference_bind_to_temporary
5535 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005536 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005537 << DestType.getNonReferenceType()
5538 << Args[0]->getType()
5539 << Args[0]->getSourceRange();
5540 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005541
Douglas Gregor20093b42009-12-09 23:02:17 +00005542 case FK_RValueReferenceBindingToLValue:
5543 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005544 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005545 << Args[0]->getSourceRange();
5546 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005547
Douglas Gregor20093b42009-12-09 23:02:17 +00005548 case FK_ReferenceInitDropsQualifiers:
5549 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5550 << DestType.getNonReferenceType()
5551 << Args[0]->getType()
5552 << Args[0]->getSourceRange();
5553 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005554
Douglas Gregor20093b42009-12-09 23:02:17 +00005555 case FK_ReferenceInitFailed:
5556 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5557 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005558 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005559 << Args[0]->getType()
5560 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005561 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5562 Args[0]->getType()->isObjCObjectPointerType())
5563 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005564 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005565
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005566 case FK_ConversionFailed: {
5567 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005568 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005569 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005570 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005571 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005572 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005573 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005574 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5575 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005576 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5577 Args[0]->getType()->isObjCObjectPointerType())
5578 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005579 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005580 }
John Wiegley429bb272011-04-08 18:41:53 +00005581
5582 case FK_ConversionFromPropertyFailed:
5583 // No-op. This error has already been reported.
5584 break;
5585
Douglas Gregord87b61f2009-12-10 17:56:55 +00005586 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005587 SourceRange R;
5588
5589 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005590 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005591 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005592 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005593 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005594
Douglas Gregor19311e72010-09-08 21:40:08 +00005595 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5596 if (Kind.isCStyleOrFunctionalCast())
5597 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5598 << R;
5599 else
5600 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5601 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005602 break;
5603 }
5604
5605 case FK_ReferenceBindingToInitList:
5606 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5607 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5608 break;
5609
5610 case FK_InitListBadDestinationType:
5611 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5612 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5613 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005614
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005615 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005616 case FK_ConstructorOverloadFailed: {
5617 SourceRange ArgsRange;
5618 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005619 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005620 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005621
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005622 if (Failure == FK_ListConstructorOverloadFailed) {
5623 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5624 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5625 Args = InitList->getInits();
5626 NumArgs = InitList->getNumInits();
5627 }
5628
Douglas Gregor51c56d62009-12-14 20:49:26 +00005629 // FIXME: Using "DestType" for the entity we're printing is probably
5630 // bad.
5631 switch (FailedOverloadResult) {
5632 case OR_Ambiguous:
5633 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5634 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005635 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005636 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005637 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005638
Douglas Gregor51c56d62009-12-14 20:49:26 +00005639 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005640 if (Kind.getKind() == InitializationKind::IK_Default &&
5641 (Entity.getKind() == InitializedEntity::EK_Base ||
5642 Entity.getKind() == InitializedEntity::EK_Member) &&
5643 isa<CXXConstructorDecl>(S.CurContext)) {
5644 // This is implicit default initialization of a member or
5645 // base within a constructor. If no viable function was
5646 // found, notify the user that she needs to explicitly
5647 // initialize this base/member.
5648 CXXConstructorDecl *Constructor
5649 = cast<CXXConstructorDecl>(S.CurContext);
5650 if (Entity.getKind() == InitializedEntity::EK_Base) {
5651 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5652 << Constructor->isImplicit()
5653 << S.Context.getTypeDeclType(Constructor->getParent())
5654 << /*base=*/0
5655 << Entity.getType();
5656
5657 RecordDecl *BaseDecl
5658 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5659 ->getDecl();
5660 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5661 << S.Context.getTagDeclType(BaseDecl);
5662 } else {
5663 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5664 << Constructor->isImplicit()
5665 << S.Context.getTypeDeclType(Constructor->getParent())
5666 << /*member=*/1
5667 << Entity.getName();
5668 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5669
5670 if (const RecordType *Record
5671 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005672 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005673 diag::note_previous_decl)
5674 << S.Context.getTagDeclType(Record->getDecl());
5675 }
5676 break;
5677 }
5678
Douglas Gregor51c56d62009-12-14 20:49:26 +00005679 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5680 << DestType << ArgsRange;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005681 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5682 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005683 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005684
Douglas Gregor51c56d62009-12-14 20:49:26 +00005685 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00005686 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005687 OverloadingResult Ovl
5688 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00005689 if (Ovl != OR_Deleted) {
5690 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5691 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005692 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00005693 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005694 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00005695
5696 // If this is a defaulted or implicitly-declared function, then
5697 // it was implicitly deleted. Make it clear that the deletion was
5698 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005699 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00005700 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005701 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00005702 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005703 else
5704 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5705 << true << DestType << ArgsRange;
5706
5707 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005708 break;
5709 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005710
Douglas Gregor51c56d62009-12-14 20:49:26 +00005711 case OR_Success:
5712 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00005713 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005714 }
David Blaikie9fdefb32012-01-17 08:24:58 +00005715 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005716
Douglas Gregor99a2e602009-12-16 01:38:02 +00005717 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005718 if (Entity.getKind() == InitializedEntity::EK_Member &&
5719 isa<CXXConstructorDecl>(S.CurContext)) {
5720 // This is implicit default-initialization of a const member in
5721 // a constructor. Complain that it needs to be explicitly
5722 // initialized.
5723 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5724 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5725 << Constructor->isImplicit()
5726 << S.Context.getTypeDeclType(Constructor->getParent())
5727 << /*const=*/1
5728 << Entity.getName();
5729 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5730 << Entity.getName();
5731 } else {
5732 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5733 << DestType << (bool)DestType->getAs<RecordType>();
5734 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005735 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005736
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005737 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00005738 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005739 diag::err_init_incomplete_type);
5740 break;
5741
Sebastian Redl14b0c192011-09-24 17:48:00 +00005742 case FK_ListInitializationFailed: {
5743 // Run the init list checker again to emit diagnostics.
5744 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5745 QualType DestType = Entity.getType();
5746 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005747 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005748 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00005749 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005750 assert(DiagnoseInitList.HadError() &&
5751 "Inconsistent init list check result.");
5752 break;
5753 }
John McCall5acb0c92011-10-17 18:40:02 +00005754
5755 case FK_PlaceholderType: {
5756 // FIXME: Already diagnosed!
5757 break;
5758 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00005759
5760 case FK_InitListElementCopyFailure: {
5761 // Try to perform all copies again.
5762 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5763 unsigned NumInits = InitList->getNumInits();
5764 QualType DestType = Entity.getType();
5765 QualType E;
5766 bool Success = S.isStdInitializerList(DestType, &E);
5767 (void)Success;
5768 assert(Success && "Where did the std::initializer_list go?");
5769 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5770 S.Context.getConstantArrayType(E,
5771 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5772 NumInits),
5773 ArrayType::Normal, 0));
5774 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5775 0, HiddenArray);
5776 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5777 // where the init list type is wrong, e.g.
5778 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5779 // FIXME: Emit a note if we hit the limit?
5780 int ErrorCount = 0;
5781 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5782 Element.setElementIndex(i);
5783 ExprResult Init = S.Owned(InitList->getInit(i));
5784 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5785 .isInvalid())
5786 ++ErrorCount;
5787 }
5788 break;
5789 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005790
5791 case FK_ExplicitConstructor: {
5792 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
5793 << Args[0]->getSourceRange();
5794 OverloadCandidateSet::iterator Best;
5795 OverloadingResult Ovl
5796 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00005797 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005798 assert(Ovl == OR_Success && "Inconsistent overload resolution");
5799 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5800 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
5801 break;
5802 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005803 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005804
Douglas Gregora41a8c52010-04-22 00:20:18 +00005805 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005806 return true;
5807}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005808
Chris Lattner5f9e2722011-07-23 10:55:15 +00005809void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005810 switch (SequenceKind) {
5811 case FailedSequence: {
5812 OS << "Failed sequence: ";
5813 switch (Failure) {
5814 case FK_TooManyInitsForReference:
5815 OS << "too many initializers for reference";
5816 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005817
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005818 case FK_ArrayNeedsInitList:
5819 OS << "array requires initializer list";
5820 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005821
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005822 case FK_ArrayNeedsInitListOrStringLiteral:
5823 OS << "array requires initializer list or string literal";
5824 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005825
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005826 case FK_ArrayTypeMismatch:
5827 OS << "array type mismatch";
5828 break;
5829
5830 case FK_NonConstantArrayInit:
5831 OS << "non-constant array initializer";
5832 break;
5833
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005834 case FK_AddressOfOverloadFailed:
5835 OS << "address of overloaded function failed";
5836 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005837
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005838 case FK_ReferenceInitOverloadFailed:
5839 OS << "overload resolution for reference initialization failed";
5840 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005841
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005842 case FK_NonConstLValueReferenceBindingToTemporary:
5843 OS << "non-const lvalue reference bound to temporary";
5844 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005845
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005846 case FK_NonConstLValueReferenceBindingToUnrelated:
5847 OS << "non-const lvalue reference bound to unrelated type";
5848 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005849
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005850 case FK_RValueReferenceBindingToLValue:
5851 OS << "rvalue reference bound to an lvalue";
5852 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005853
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005854 case FK_ReferenceInitDropsQualifiers:
5855 OS << "reference initialization drops qualifiers";
5856 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005857
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005858 case FK_ReferenceInitFailed:
5859 OS << "reference initialization failed";
5860 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005861
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005862 case FK_ConversionFailed:
5863 OS << "conversion failed";
5864 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005865
John Wiegley429bb272011-04-08 18:41:53 +00005866 case FK_ConversionFromPropertyFailed:
5867 OS << "conversion from property failed";
5868 break;
5869
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005870 case FK_TooManyInitsForScalar:
5871 OS << "too many initializers for scalar";
5872 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005873
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005874 case FK_ReferenceBindingToInitList:
5875 OS << "referencing binding to initializer list";
5876 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005877
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005878 case FK_InitListBadDestinationType:
5879 OS << "initializer list for non-aggregate, non-scalar type";
5880 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005881
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005882 case FK_UserConversionOverloadFailed:
5883 OS << "overloading failed for user-defined conversion";
5884 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005885
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005886 case FK_ConstructorOverloadFailed:
5887 OS << "constructor overloading failed";
5888 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005889
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005890 case FK_DefaultInitOfConst:
5891 OS << "default initialization of a const variable";
5892 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005893
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005894 case FK_Incomplete:
5895 OS << "initialization of incomplete type";
5896 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005897
5898 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005899 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005900 break;
5901
John McCall73076432012-01-05 00:13:19 +00005902 case FK_VariableLengthArrayHasInitializer:
5903 OS << "variable length array has an initializer";
5904 break;
5905
John McCall5acb0c92011-10-17 18:40:02 +00005906 case FK_PlaceholderType:
5907 OS << "initializer expression isn't contextually valid";
5908 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005909
5910 case FK_ListConstructorOverloadFailed:
5911 OS << "list constructor overloading failed";
5912 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005913
5914 case FK_InitListElementCopyFailure:
5915 OS << "copy construction of initializer list element failed";
5916 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005917
5918 case FK_ExplicitConstructor:
5919 OS << "list copy initialization chose explicit constructor";
5920 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005921 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005922 OS << '\n';
5923 return;
5924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005925
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005926 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005927 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005928 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005929
Sebastian Redl7491c492011-06-05 13:59:11 +00005930 case NormalSequence:
5931 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005932 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005933 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005934
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005935 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5936 if (S != step_begin()) {
5937 OS << " -> ";
5938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005939
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005940 switch (S->Kind) {
5941 case SK_ResolveAddressOfOverloadedFunction:
5942 OS << "resolve address of overloaded function";
5943 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005944
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005945 case SK_CastDerivedToBaseRValue:
5946 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5947 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005948
Sebastian Redl906082e2010-07-20 04:20:21 +00005949 case SK_CastDerivedToBaseXValue:
5950 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5951 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005953 case SK_CastDerivedToBaseLValue:
5954 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5955 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005956
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005957 case SK_BindReference:
5958 OS << "bind reference to lvalue";
5959 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005960
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005961 case SK_BindReferenceToTemporary:
5962 OS << "bind reference to a temporary";
5963 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005964
Douglas Gregor523d46a2010-04-18 07:40:54 +00005965 case SK_ExtraneousCopyToTemporary:
5966 OS << "extraneous C++03 copy to temporary";
5967 break;
5968
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005969 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005970 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005971 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005972
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005973 case SK_QualificationConversionRValue:
5974 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005975 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005976
Sebastian Redl906082e2010-07-20 04:20:21 +00005977 case SK_QualificationConversionXValue:
5978 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005979 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005980
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005981 case SK_QualificationConversionLValue:
5982 OS << "qualification conversion (lvalue)";
5983 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005984
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005985 case SK_ConversionSequence:
5986 OS << "implicit conversion sequence (";
5987 S->ICS->DebugPrint(); // FIXME: use OS
5988 OS << ")";
5989 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005990
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005991 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005992 OS << "list aggregate initialization";
5993 break;
5994
5995 case SK_ListConstructorCall:
5996 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005997 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005998
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005999 case SK_UnwrapInitList:
6000 OS << "unwrap reference initializer list";
6001 break;
6002
6003 case SK_RewrapInitList:
6004 OS << "rewrap reference initializer list";
6005 break;
6006
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006007 case SK_ConstructorInitialization:
6008 OS << "constructor initialization";
6009 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006010
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006011 case SK_ZeroInitialization:
6012 OS << "zero initialization";
6013 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006014
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006015 case SK_CAssignment:
6016 OS << "C assignment";
6017 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006018
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006019 case SK_StringInit:
6020 OS << "string initialization";
6021 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006022
6023 case SK_ObjCObjectConversion:
6024 OS << "Objective-C object conversion";
6025 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006026
6027 case SK_ArrayInit:
6028 OS << "array initialization";
6029 break;
John McCallf85e1932011-06-15 23:02:42 +00006030
Richard Smith0f163e92012-02-15 22:38:09 +00006031 case SK_ParenthesizedArrayInit:
6032 OS << "parenthesized array initialization";
6033 break;
6034
John McCallf85e1932011-06-15 23:02:42 +00006035 case SK_PassByIndirectCopyRestore:
6036 OS << "pass by indirect copy and restore";
6037 break;
6038
6039 case SK_PassByIndirectRestore:
6040 OS << "pass by indirect restore";
6041 break;
6042
6043 case SK_ProduceObjCObject:
6044 OS << "Objective-C object retension";
6045 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006046
6047 case SK_StdInitializerList:
6048 OS << "std::initializer_list from initializer list";
6049 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006050 }
6051 }
6052}
6053
6054void InitializationSequence::dump() const {
6055 dump(llvm::errs());
6056}
6057
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006058static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6059 QualType EntityType,
6060 const Expr *PreInit,
6061 const Expr *PostInit) {
6062 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6063 return;
6064
6065 // A narrowing conversion can only appear as the final implicit conversion in
6066 // an initialization sequence.
6067 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6068 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6069 return;
6070
6071 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6072 const StandardConversionSequence *SCS = 0;
6073 switch (ICS.getKind()) {
6074 case ImplicitConversionSequence::StandardConversion:
6075 SCS = &ICS.Standard;
6076 break;
6077 case ImplicitConversionSequence::UserDefinedConversion:
6078 SCS = &ICS.UserDefined.After;
6079 break;
6080 case ImplicitConversionSequence::AmbiguousConversion:
6081 case ImplicitConversionSequence::EllipsisConversion:
6082 case ImplicitConversionSequence::BadConversion:
6083 return;
6084 }
6085
6086 // Determine the type prior to the narrowing conversion. If a conversion
6087 // operator was used, this may be different from both the type of the entity
6088 // and of the pre-initialization expression.
6089 QualType PreNarrowingType = PreInit->getType();
6090 if (Seq.step_begin() + 1 != Seq.step_end())
6091 PreNarrowingType = Seq.step_end()[-2].Type;
6092
6093 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6094 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006095 QualType ConstantType;
6096 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6097 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006098 case NK_Not_Narrowing:
6099 // No narrowing occurred.
6100 return;
6101
6102 case NK_Type_Narrowing:
6103 // This was a floating-to-integer conversion, which is always considered a
6104 // narrowing conversion even if the value is a constant and can be
6105 // represented exactly as an integer.
6106 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006107 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006108 diag::warn_init_list_type_narrowing
6109 : S.isSFINAEContext()?
6110 diag::err_init_list_type_narrowing_sfinae
6111 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006112 << PostInit->getSourceRange()
6113 << PreNarrowingType.getLocalUnqualifiedType()
6114 << EntityType.getLocalUnqualifiedType();
6115 break;
6116
6117 case NK_Constant_Narrowing:
6118 // A constant value was narrowed.
6119 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006120 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006121 diag::warn_init_list_constant_narrowing
6122 : S.isSFINAEContext()?
6123 diag::err_init_list_constant_narrowing_sfinae
6124 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006125 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006126 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006127 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006128 break;
6129
6130 case NK_Variable_Narrowing:
6131 // A variable's value may have been narrowed.
6132 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006133 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006134 diag::warn_init_list_variable_narrowing
6135 : S.isSFINAEContext()?
6136 diag::err_init_list_variable_narrowing_sfinae
6137 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006138 << PostInit->getSourceRange()
6139 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006140 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006141 break;
6142 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006143
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006144 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006145 llvm::raw_svector_ostream OS(StaticCast);
6146 OS << "static_cast<";
6147 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6148 // It's important to use the typedef's name if there is one so that the
6149 // fixit doesn't break code using types like int64_t.
6150 //
6151 // FIXME: This will break if the typedef requires qualification. But
6152 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006153 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006154 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006155 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006156 else {
6157 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6158 // with a broken cast.
6159 return;
6160 }
6161 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006162 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6163 << PostInit->getSourceRange()
6164 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006165 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006166 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006167}
6168
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006169//===----------------------------------------------------------------------===//
6170// Initialization helper functions
6171//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006172bool
6173Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6174 ExprResult Init) {
6175 if (Init.isInvalid())
6176 return false;
6177
6178 Expr *InitE = Init.get();
6179 assert(InitE && "No initialization expression");
6180
Douglas Gregor3c394c52012-07-31 22:15:04 +00006181 InitializationKind Kind
6182 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Sean Hunt2be7e902011-05-12 22:46:29 +00006183 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00006184 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006185}
6186
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006187ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006188Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6189 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006190 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006191 bool TopLevelOfInitList,
6192 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006193 if (Init.isInvalid())
6194 return ExprError();
6195
John McCall15d7d122010-11-11 03:21:53 +00006196 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006197 assert(InitE && "No initialization expression?");
6198
6199 if (EqualLoc.isInvalid())
6200 EqualLoc = InitE->getLocStart();
6201
6202 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006203 EqualLoc,
6204 AllowExplicit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006205 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6206 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006207
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006208 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6209
6210 if (!Result.isInvalid() && TopLevelOfInitList)
6211 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6212 InitE, Result.get());
6213
6214 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006215}