blob: b6d55aae8062df69c62257533c26bd7acdae924b [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.
95 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000174 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000175 bool AllowBraceElision;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000176 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
177 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000179 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000180 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000182 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000183 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000184 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000185 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000186 unsigned &StructuredIndex,
187 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000188 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000189 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000190 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000193 unsigned &StructuredIndex,
194 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000195 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000196 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000197 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000198 InitListExpr *StructuredList,
199 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000200 void CheckComplexType(const InitializedEntity &Entity,
201 InitListExpr *IList, QualType DeclType,
202 unsigned &Index,
203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000205 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000206 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000207 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
209 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000210 void CheckReferenceType(const InitializedEntity &Entity,
211 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000212 unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000215 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000216 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000217 InitListExpr *StructuredList,
218 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000219 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000220 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000221 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 unsigned &StructuredIndex,
225 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000226 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000227 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000228 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000232 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000233 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000234 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000235 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 RecordDecl::field_iterator *NextField,
237 llvm::APSInt *NextElementIndex,
238 unsigned &Index,
239 InitListExpr *StructuredList,
240 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000241 bool FinishSubobjectInit,
242 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000243 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
244 QualType CurrentObjectType,
245 InitListExpr *StructuredList,
246 unsigned StructuredIndex,
247 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 void UpdateStructuredListElement(InitListExpr *StructuredList,
249 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000250 Expr *expr);
251 int numArrayElements(QualType DeclType);
252 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000253
Douglas Gregord6d37de2009-12-22 00:05:34 +0000254 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000257 void FillInValueInitializations(const InitializedEntity &Entity,
258 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000259 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
260 Expr *InitExpr, FieldDecl *Field,
261 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000262 void CheckValueInitializable(const InitializedEntity &Entity);
263
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000264public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000265 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000266 InitListExpr *IL, QualType &T, bool VerifyOnly,
267 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000268 bool HadError() { return hadError; }
269
270 // @brief Retrieves the fully-structured initializer list used for
271 // semantic analysis and code generation.
272 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
273};
Chris Lattner8b419b92009-02-24 22:48:58 +0000274} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000275
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000276void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
277 assert(VerifyOnly &&
278 "CheckValueInitializable is only inteded for verification mode.");
279
280 SourceLocation Loc;
281 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
282 true);
283 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
284 if (InitSeq.Failed())
285 hadError = true;
286}
287
Douglas Gregord6d37de2009-12-22 00:05:34 +0000288void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
289 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000290 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000291 bool &RequiresSecondPass) {
292 SourceLocation Loc = ILE->getSourceRange().getBegin();
293 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000295 = InitializedEntity::InitializeMember(Field, &ParentEntity);
296 if (Init >= NumInits || !ILE->getInit(Init)) {
297 // FIXME: We probably don't need to handle references
298 // specially here, since value-initialization of references is
299 // handled in InitializationSequence.
300 if (Field->getType()->isReferenceType()) {
301 // C++ [dcl.init.aggr]p9:
302 // If an incomplete or empty initializer-list leaves a
303 // member of reference type uninitialized, the program is
304 // ill-formed.
305 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
306 << Field->getType()
307 << ILE->getSyntacticForm()->getSourceRange();
308 SemaRef.Diag(Field->getLocation(),
309 diag::note_uninit_reference_member);
310 hadError = true;
311 return;
312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000313
Douglas Gregord6d37de2009-12-22 00:05:34 +0000314 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
315 true);
316 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
317 if (!InitSeq) {
318 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
319 hadError = true;
320 return;
321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000322
John McCall60d7b3a2010-08-24 06:29:42 +0000323 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000324 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregord6d37de2009-12-22 00:05:34 +0000330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000334 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000335 // Value-initialization requires a constructor call, so
336 // extend the initializer list to include the constructor
337 // call and make a note that we'll need to take another pass
338 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000339 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 RequiresSecondPass = true;
341 }
342 } else if (InitListExpr *InnerILE
343 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000344 FillInValueInitializations(MemberEntity, InnerILE,
345 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000346}
347
Douglas Gregor4c678342009-01-28 21:54:33 +0000348/// Recursively replaces NULL values within the given initializer list
349/// with expressions that perform value-initialization of the
350/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000351void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000352InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
353 InitListExpr *ILE,
354 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000355 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000356 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357 SourceLocation Loc = ILE->getSourceRange().getBegin();
358 if (ILE->getSyntacticForm())
359 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Ted Kremenek6217b802009-07-29 21:53:49 +0000361 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000362 if (RType->getDecl()->isUnion() &&
363 ILE->getInitializedFieldInUnion())
364 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
365 Entity, ILE, RequiresSecondPass);
366 else {
367 unsigned Init = 0;
368 for (RecordDecl::field_iterator
369 Field = RType->getDecl()->field_begin(),
370 FieldEnd = RType->getDecl()->field_end();
371 Field != FieldEnd; ++Field) {
372 if (Field->isUnnamedBitfield())
373 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000374
Douglas Gregord6d37de2009-12-22 00:05:34 +0000375 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000377
378 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
379 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000381
Douglas Gregord6d37de2009-12-22 00:05:34 +0000382 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000383
Douglas Gregord6d37de2009-12-22 00:05:34 +0000384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
387 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000388 }
389
390 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000391 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000392
393 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000396 unsigned NumInits = ILE->getNumInits();
397 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000398 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000399 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000400 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
401 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000402 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000403 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000404 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000405 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000406 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000407 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000408 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000409 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000411
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000412
Douglas Gregor87fd7032009-02-02 17:43:21 +0000413 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000414 if (hadError)
415 return;
416
Anders Carlssond3d824d2010-01-23 04:34:47 +0000417 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
418 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000419 ElementEntity.setElementIndex(Init);
420
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000421 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
422 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
John McCall60d7b3a2010-08-24 06:29:42 +0000432 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000433 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000434 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000435 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000436 return;
437 }
438
439 if (hadError) {
440 // Do nothing
441 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000442 // For arrays, just set the expression used for value-initialization
443 // of the "holes" in the array.
444 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
445 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
446 else
447 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000448 } else {
449 // For arrays, just set the expression used for value-initialization
450 // of the rest of elements and exit.
451 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
452 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
453 return;
454 }
455
Sebastian Redl7491c492011-06-05 13:59:11 +0000456 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000457 // Value-initialization requires a constructor call, so
458 // extend the initializer list to include the constructor
459 // call and make a note that we'll need to take another pass
460 // through the initializer list.
461 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
462 RequiresSecondPass = true;
463 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000464 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000465 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000466 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000467 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000468 }
469}
470
Chris Lattner68355a52009-01-29 05:10:57 +0000471
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000472InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000473 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000474 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000475 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000476 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000477
Eli Friedmanb85f7072008-05-19 19:16:24 +0000478 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000480 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000481 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000482 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000483 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000484 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000485
Sebastian Redl14b0c192011-09-24 17:48:00 +0000486 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000487 bool RequiresSecondPass = false;
488 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000489 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000490 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000491 RequiresSecondPass);
492 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000493}
494
495int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000496 // FIXME: use a proper constant
497 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000498 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000499 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000500 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
501 }
502 return maxElements;
503}
504
505int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000507 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000508 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000509 Field = structDecl->field_begin(),
510 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000511 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000512 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000513 ++InitializableMembers;
514 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000515 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000516 return std::min(InitializableMembers, 1);
517 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000518}
519
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000520void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000521 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 QualType T, unsigned &Index,
523 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000524 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000525 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Steve Naroff0cca7492008-05-01 22:18:59 +0000527 if (T->isArrayType())
528 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000529 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000530 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000531 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000532 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000533 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000534 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000535
Eli Friedman402256f2008-05-25 13:49:22 +0000536 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000537 if (!VerifyOnly)
538 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
539 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000540 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000541 hadError = true;
542 return;
543 }
544
Douglas Gregor4c678342009-01-28 21:54:33 +0000545 // Build a structured initializer list corresponding to this subobject.
546 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000547 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
548 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000549 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
550 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000551 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000552
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000554 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000555 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000556 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000557 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000558 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000559
560 if (VerifyOnly) {
561 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
562 hadError = true;
563 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000564 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000565
Sebastian Redlc2235182011-10-16 18:19:28 +0000566 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000567 // Update the structured sub-object initializer so that it's ending
568 // range corresponds with the end of the last initializer it used.
569 if (EndIndex < ParentIList->getNumInits()) {
570 SourceLocation EndLoc
571 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
572 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
573 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574
Sebastian Redlc2235182011-10-16 18:19:28 +0000575 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000576 if (T->isArrayType() || T->isRecordType()) {
577 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000578 AllowBraceElision ? diag::warn_missing_braces :
579 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000580 << StructuredSubobjectInitList->getSourceRange()
581 << FixItHint::CreateInsertion(
582 StructuredSubobjectInitList->getLocStart(), "{")
583 << FixItHint::CreateInsertion(
584 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000585 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000586 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000587 if (!AllowBraceElision)
588 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000589 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000590 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000591}
592
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000593void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000594 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 unsigned &Index,
596 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000597 unsigned &StructuredIndex,
598 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000599 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000600 if (!VerifyOnly) {
601 SyntacticToSemantic[IList] = StructuredList;
602 StructuredList->setSyntacticForm(IList);
603 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000605 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000606 if (!VerifyOnly) {
607 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
608 IList->setType(ExprTy);
609 StructuredList->setType(ExprTy);
610 }
Eli Friedman638e1442008-05-25 13:22:35 +0000611 if (hadError)
612 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000613
Eli Friedman638e1442008-05-25 13:22:35 +0000614 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000615 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000616 if (VerifyOnly) {
617 if (SemaRef.getLangOptions().CPlusPlus ||
618 (SemaRef.getLangOptions().OpenCL &&
619 IList->getType()->isVectorType())) {
620 hadError = true;
621 }
622 return;
623 }
624
Eli Friedmane5408582009-05-29 20:20:05 +0000625 if (StructuredIndex == 1 &&
626 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000627 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000629 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000630 hadError = true;
631 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000632 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000633 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000634 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000635 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000636 // Don't complain for incomplete types, since we'll get an error
637 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000638 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000639 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000640 CurrentObjectType->isArrayType()? 0 :
641 CurrentObjectType->isVectorType()? 1 :
642 CurrentObjectType->isScalarType()? 2 :
643 CurrentObjectType->isUnionType()? 3 :
644 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000645
646 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000647 if (SemaRef.getLangOptions().CPlusPlus) {
648 DK = diag::err_excess_initializers;
649 hadError = true;
650 }
Nate Begeman08634522009-07-07 21:53:06 +0000651 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
652 DK = diag::err_excess_initializers;
653 hadError = true;
654 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000655
Chris Lattner08202542009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000657 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000658 }
659 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000660
Sebastian Redl14b0c192011-09-24 17:48:00 +0000661 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
662 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000664 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000665 << FixItHint::CreateRemoval(IList->getLocStart())
666 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000667}
668
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000669void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000670 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000671 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000672 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000673 unsigned &Index,
674 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000675 unsigned &StructuredIndex,
676 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000677 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
678 // Explicitly braced initializer for complex type can be real+imaginary
679 // parts.
680 CheckComplexType(Entity, IList, DeclType, Index,
681 StructuredList, StructuredIndex);
682 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000683 CheckScalarType(Entity, IList, DeclType, Index,
684 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000685 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000686 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000687 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000688 } else if (DeclType->isAggregateType()) {
689 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000690 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000691 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000692 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000693 StructuredList, StructuredIndex,
694 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000695 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000696 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000697 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000698 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000699 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000700 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000701 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000702 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000703 llvm_unreachable("Aggregate that isn't a structure or array?!");
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->isRecordType()) {
712 // C++ [dcl.init]p14:
713 // [...] If the class is an aggregate (8.5.1), and the initializer
714 // is a brace-enclosed list, see 8.5.1.
715 //
716 // Note: 8.5.1 is handled below; here, we diagnose the case where
717 // we have an initializer list and a destination type that is not
718 // an aggregate.
719 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
722 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000723 hadError = true;
724 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000725 CheckReferenceType(Entity, IList, DeclType, Index,
726 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000727 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000728 if (!VerifyOnly)
729 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
730 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000731 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000732 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000733 if (!VerifyOnly)
734 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
735 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000736 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000737 }
738}
739
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000740void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000741 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000742 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000746 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000747 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
748 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000749 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000750 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000751 = getStructuredSubobjectInit(IList, Index, ElemType,
752 StructuredList, StructuredIndex,
753 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000754 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000755 newStructuredList, newStructuredIndex);
756 ++StructuredIndex;
757 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000758 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000759 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000760 return CheckScalarType(Entity, IList, ElemType, Index,
761 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000762 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000763 return CheckReferenceType(Entity, IList, ElemType, Index,
764 StructuredList, StructuredIndex);
765 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000766
John McCallfef8b342011-02-21 07:57:55 +0000767 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
768 // arrayType can be incomplete if we're initializing a flexible
769 // array member. There's nothing we can do with the completed
770 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000771
John McCallfef8b342011-02-21 07:57:55 +0000772 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000773 if (!VerifyOnly) {
774 CheckStringInit(Str, ElemType, arrayType, SemaRef);
775 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
776 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000777 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000778 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000779 }
John McCallfef8b342011-02-21 07:57:55 +0000780
781 // Fall through for subaggregate initialization.
782
783 } else if (SemaRef.getLangOptions().CPlusPlus) {
784 // C++ [dcl.init.aggr]p12:
785 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000786 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000787 // an initializer-list. If the initializer can initialize a
788 // member, the member is initialized. [...]
789
790 // FIXME: Better EqualLoc?
791 InitializationKind Kind =
792 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
793 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
794
795 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000796 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000797 ExprResult Result =
798 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
799 if (Result.isInvalid())
800 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000801
Sebastian Redl14b0c192011-09-24 17:48:00 +0000802 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000803 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000804 }
John McCallfef8b342011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 } else {
811 // C99 6.7.8p13:
812 //
813 // The initializer for a structure or union object that has
814 // automatic storage duration shall be either an initializer
815 // list as described below, or a single expression that has
816 // compatible structure or union type. In the latter case, the
817 // initial value of the object, including unnamed members, is
818 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000819 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000820 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000821 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
822 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000823 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000824 if (ExprRes.isInvalid())
825 hadError = true;
826 else {
827 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
828 if (ExprRes.isInvalid())
829 hadError = true;
830 }
831 UpdateStructuredListElement(StructuredList, StructuredIndex,
832 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000833 ++Index;
834 return;
835 }
John Wiegley429bb272011-04-08 18:41:53 +0000836 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000837 // Fall through for subaggregate initialization
838 }
839
840 // C++ [dcl.init.aggr]p12:
841 //
842 // [...] Otherwise, if the member is itself a non-empty
843 // subaggregate, brace elision is assumed and the initializer is
844 // considered for the initialization of the first member of
845 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000846 if (!SemaRef.getLangOptions().OpenCL &&
847 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000848 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
849 StructuredIndex);
850 ++StructuredIndex;
851 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000852 if (!VerifyOnly) {
853 // We cannot initialize this element, so let
854 // PerformCopyInitialization produce the appropriate diagnostic.
855 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
856 SemaRef.Owned(expr),
857 /*TopLevelOfInitList=*/true);
858 }
John McCallfef8b342011-02-21 07:57:55 +0000859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000862 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000863}
864
Eli Friedman0c706c22011-09-19 23:17:44 +0000865void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
866 InitListExpr *IList, QualType DeclType,
867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
870 assert(Index == 0 && "Index in explicit init list must be zero");
871
872 // As an extension, clang supports complex initializers, which initialize
873 // a complex number component-wise. When an explicit initializer list for
874 // a complex number contains two two initializers, this extension kicks in:
875 // it exepcts the initializer list to contain two elements convertible to
876 // the element type of the complex type. The first element initializes
877 // the real part, and the second element intitializes the imaginary part.
878
879 if (IList->getNumInits() != 2)
880 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
881 StructuredIndex);
882
883 // This is an extension in C. (The builtin _Complex type does not exist
884 // in the C++ standard.)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000885 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000886 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
887 << IList->getSourceRange();
888
889 // Initialize the complex number.
890 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
891 InitializedEntity ElementEntity =
892 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
893
894 for (unsigned i = 0; i < 2; ++i) {
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899}
900
901
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000902void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000903 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000904 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000905 InitListExpr *StructuredList,
906 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000907 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000908 if (!VerifyOnly)
909 SemaRef.Diag(IList->getLocStart(),
910 SemaRef.getLangOptions().CPlusPlus0x ?
911 diag::warn_cxx98_compat_empty_scalar_initializer :
912 diag::err_empty_scalar_initializer)
913 << IList->getSourceRange();
914 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor4c678342009-01-28 21:54:33 +0000915 ++Index;
916 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000917 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000918 }
John McCallb934c2d2010-11-11 00:46:36 +0000919
920 Expr *expr = IList->getInit(Index);
921 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000922 if (!VerifyOnly)
923 SemaRef.Diag(SubIList->getLocStart(),
924 diag::warn_many_braces_around_scalar_init)
925 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000926
927 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
928 StructuredIndex);
929 return;
930 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000931 if (!VerifyOnly)
932 SemaRef.Diag(expr->getSourceRange().getBegin(),
933 diag::err_designator_for_scalar_init)
934 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000935 hadError = true;
936 ++Index;
937 ++StructuredIndex;
938 return;
939 }
940
Sebastian Redl14b0c192011-09-24 17:48:00 +0000941 if (VerifyOnly) {
942 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
943 hadError = true;
944 ++Index;
945 return;
946 }
947
John McCallb934c2d2010-11-11 00:46:36 +0000948 ExprResult Result =
949 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000950 SemaRef.Owned(expr),
951 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000952
953 Expr *ResultExpr = 0;
954
955 if (Result.isInvalid())
956 hadError = true; // types weren't compatible.
957 else {
958 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000959
John McCallb934c2d2010-11-11 00:46:36 +0000960 if (ResultExpr != expr) {
961 // The type was promoted, update initializer list.
962 IList->setInit(Index, ResultExpr);
963 }
964 }
965 if (hadError)
966 ++StructuredIndex;
967 else
968 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
969 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000970}
971
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000972void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
973 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000974 unsigned &Index,
975 InitListExpr *StructuredList,
976 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000977 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000978 // FIXME: It would be wonderful if we could point at the actual member. In
979 // general, it would be useful to pass location information down the stack,
980 // so that we know the location (or decl) of the "current object" being
981 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000982 if (!VerifyOnly)
983 SemaRef.Diag(IList->getLocStart(),
984 diag::err_init_reference_member_uninitialized)
985 << DeclType
986 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000987 hadError = true;
988 ++Index;
989 ++StructuredIndex;
990 return;
991 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000992
993 Expr *expr = IList->getInit(Index);
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000994 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000995 if (!VerifyOnly)
996 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
997 << DeclType << IList->getSourceRange();
998 hadError = true;
999 ++Index;
1000 ++StructuredIndex;
1001 return;
1002 }
1003
1004 if (VerifyOnly) {
1005 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1006 hadError = true;
1007 ++Index;
1008 return;
1009 }
1010
1011 ExprResult Result =
1012 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1013 SemaRef.Owned(expr),
1014 /*TopLevelOfInitList=*/true);
1015
1016 if (Result.isInvalid())
1017 hadError = true;
1018
1019 expr = Result.takeAs<Expr>();
1020 IList->setInit(Index, expr);
1021
1022 if (hadError)
1023 ++StructuredIndex;
1024 else
1025 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1026 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001027}
1028
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001029void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001030 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001031 unsigned &Index,
1032 InitListExpr *StructuredList,
1033 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001034 const VectorType *VT = DeclType->getAs<VectorType>();
1035 unsigned maxElements = VT->getNumElements();
1036 unsigned numEltsInit = 0;
1037 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001038
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001039 if (Index >= IList->getNumInits()) {
1040 // Make sure the element type can be value-initialized.
1041 if (VerifyOnly)
1042 CheckValueInitializable(
1043 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1044 return;
1045 }
1046
John McCall20e047a2010-10-30 00:11:39 +00001047 if (!SemaRef.getLangOptions().OpenCL) {
1048 // If the initializing element is a vector, try to copy-initialize
1049 // instead of breaking it apart (which is doomed to failure anyway).
1050 Expr *Init = IList->getInit(Index);
1051 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001052 if (VerifyOnly) {
1053 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1054 hadError = true;
1055 ++Index;
1056 return;
1057 }
1058
John McCall20e047a2010-10-30 00:11:39 +00001059 ExprResult Result =
1060 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001061 SemaRef.Owned(Init),
1062 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001063
1064 Expr *ResultExpr = 0;
1065 if (Result.isInvalid())
1066 hadError = true; // types weren't compatible.
1067 else {
1068 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001069
John McCall20e047a2010-10-30 00:11:39 +00001070 if (ResultExpr != Init) {
1071 // The type was promoted, update initializer list.
1072 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001073 }
1074 }
John McCall20e047a2010-10-30 00:11:39 +00001075 if (hadError)
1076 ++StructuredIndex;
1077 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001078 UpdateStructuredListElement(StructuredList, StructuredIndex,
1079 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001080 ++Index;
1081 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001082 }
Mike Stump1eb44332009-09-09 15:08:12 +00001083
John McCall20e047a2010-10-30 00:11:39 +00001084 InitializedEntity ElementEntity =
1085 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001086
John McCall20e047a2010-10-30 00:11:39 +00001087 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1088 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001089 if (Index >= IList->getNumInits()) {
1090 if (VerifyOnly)
1091 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001092 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001093 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001094
John McCall20e047a2010-10-30 00:11:39 +00001095 ElementEntity.setElementIndex(Index);
1096 CheckSubElementType(ElementEntity, IList, elementType, Index,
1097 StructuredList, StructuredIndex);
1098 }
1099 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001100 }
John McCall20e047a2010-10-30 00:11:39 +00001101
1102 InitializedEntity ElementEntity =
1103 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001104
John McCall20e047a2010-10-30 00:11:39 +00001105 // OpenCL initializers allows vectors to be constructed from vectors.
1106 for (unsigned i = 0; i < maxElements; ++i) {
1107 // Don't attempt to go past the end of the init list
1108 if (Index >= IList->getNumInits())
1109 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001110
John McCall20e047a2010-10-30 00:11:39 +00001111 ElementEntity.setElementIndex(Index);
1112
1113 QualType IType = IList->getInit(Index)->getType();
1114 if (!IType->isVectorType()) {
1115 CheckSubElementType(ElementEntity, IList, elementType, Index,
1116 StructuredList, StructuredIndex);
1117 ++numEltsInit;
1118 } else {
1119 QualType VecType;
1120 const VectorType *IVT = IType->getAs<VectorType>();
1121 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001122
John McCall20e047a2010-10-30 00:11:39 +00001123 if (IType->isExtVectorType())
1124 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1125 else
1126 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001127 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001128 CheckSubElementType(ElementEntity, IList, VecType, Index,
1129 StructuredList, StructuredIndex);
1130 numEltsInit += numIElts;
1131 }
1132 }
1133
1134 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001135 if (numEltsInit != maxElements) {
1136 if (!VerifyOnly)
1137 SemaRef.Diag(IList->getSourceRange().getBegin(),
1138 diag::err_vector_incorrect_num_initializers)
1139 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1140 hadError = true;
1141 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001142}
1143
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001145 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001146 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001147 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001148 unsigned &Index,
1149 InitListExpr *StructuredList,
1150 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1152
Steve Naroff0cca7492008-05-01 22:18:59 +00001153 // Check for the special-case of initializing an array with a string.
1154 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001155 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001156 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001157 // We place the string literal directly into the resulting
1158 // initializer list. This is the only place where the structure
1159 // of the structured initializer list doesn't match exactly,
1160 // because doing so would involve allocating one character
1161 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001162 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001163 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1165 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1166 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001167 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001168 return;
1169 }
1170 }
John McCallce6c9b72011-02-21 07:22:22 +00001171 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001172 // Check for VLAs; in standard C it would be possible to check this
1173 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1174 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001175 if (!VerifyOnly)
1176 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1177 diag::err_variable_object_no_init)
1178 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001179 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001180 ++Index;
1181 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001182 return;
1183 }
1184
Douglas Gregor05c13a32009-01-22 00:58:24 +00001185 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001186 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1187 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001188 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001189 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001190 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001191 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001192 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001193 maxElementsKnown = true;
1194 }
1195
John McCallce6c9b72011-02-21 07:22:22 +00001196 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001197 while (Index < IList->getNumInits()) {
1198 Expr *Init = IList->getInit(Index);
1199 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001200 // If we're not the subobject that matches up with the '{' for
1201 // the designator, we shouldn't be handling the
1202 // designator. Return immediately.
1203 if (!SubobjectIsDesignatorContext)
1204 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001205
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001206 // Handle this designated initializer. elementIndex will be
1207 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001208 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001209 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001210 StructuredList, StructuredIndex, true,
1211 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001212 hadError = true;
1213 continue;
1214 }
1215
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001216 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001217 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001218 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001219 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001221
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001222 // If the array is of incomplete type, keep track of the number of
1223 // elements in the initializer.
1224 if (!maxElementsKnown && elementIndex > maxElements)
1225 maxElements = elementIndex;
1226
Douglas Gregor05c13a32009-01-22 00:58:24 +00001227 continue;
1228 }
1229
1230 // If we know the maximum number of elements, and we've already
1231 // hit it, stop consuming elements in the initializer list.
1232 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001233 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001234
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001235 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001237 Entity);
1238 // Check this element.
1239 CheckSubElementType(ElementEntity, IList, elementType, Index,
1240 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001241 ++elementIndex;
1242
1243 // If the array is of incomplete type, keep track of the number of
1244 // elements in the initializer.
1245 if (!maxElementsKnown && elementIndex > maxElements)
1246 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001247 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001248 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001249 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001250 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001251 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001252 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001253 // Sizing an array implicitly to zero is not allowed by ISO C,
1254 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001255 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001256 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001257 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001258
Mike Stump1eb44332009-09-09 15:08:12 +00001259 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001260 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001261 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001262 if (!hadError && VerifyOnly) {
1263 // Check if there are any members of the array that get value-initialized.
1264 // If so, check if doing that is possible.
1265 // FIXME: This needs to detect holes left by designated initializers too.
1266 if (maxElementsKnown && elementIndex < maxElements)
1267 CheckValueInitializable(InitializedEntity::InitializeElement(
1268 SemaRef.Context, 0, Entity));
1269 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001270}
1271
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001272bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1273 Expr *InitExpr,
1274 FieldDecl *Field,
1275 bool TopLevelObject) {
1276 // Handle GNU flexible array initializers.
1277 unsigned FlexArrayDiag;
1278 if (isa<InitListExpr>(InitExpr) &&
1279 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1280 // Empty flexible array init always allowed as an extension
1281 FlexArrayDiag = diag::ext_flexible_array_init;
1282 } else if (SemaRef.getLangOptions().CPlusPlus) {
1283 // Disallow flexible array init in C++; it is not required for gcc
1284 // compatibility, and it needs work to IRGen correctly in general.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (!TopLevelObject) {
1287 // Disallow flexible array init on non-top-level object
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1290 // Disallow flexible array init on anything which is not a variable.
1291 FlexArrayDiag = diag::err_flexible_array_init;
1292 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1293 // Disallow flexible array init on local variables.
1294 FlexArrayDiag = diag::err_flexible_array_init;
1295 } else {
1296 // Allow other cases.
1297 FlexArrayDiag = diag::ext_flexible_array_init;
1298 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001299
1300 if (!VerifyOnly) {
1301 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1302 FlexArrayDiag)
1303 << InitExpr->getSourceRange().getBegin();
1304 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1305 << Field;
1306 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001307
1308 return FlexArrayDiag != diag::ext_flexible_array_init;
1309}
1310
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001311void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001312 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001313 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001314 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001315 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001316 unsigned &Index,
1317 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001318 unsigned &StructuredIndex,
1319 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001320 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Eli Friedmanb85f7072008-05-19 19:16:24 +00001322 // If the record is invalid, some of it's members are invalid. To avoid
1323 // confusion, we forgo checking the intializer for the entire record.
1324 if (structDecl->isInvalidDecl()) {
1325 hadError = true;
1326 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001327 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001328
1329 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001330 // Value-initialize the first named member of the union.
1331 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1332 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1333 Field != FieldEnd; ++Field) {
1334 if (Field->getDeclName()) {
1335 if (VerifyOnly)
1336 CheckValueInitializable(
1337 InitializedEntity::InitializeMember(*Field, &Entity));
1338 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001339 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001340 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001341 }
1342 }
1343 return;
1344 }
1345
Douglas Gregor05c13a32009-01-22 00:58:24 +00001346 // If structDecl is a forward declaration, this loop won't do
1347 // anything except look at designated initializers; That's okay,
1348 // because an error should get printed out elsewhere. It might be
1349 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001350 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001351 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001352 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001353 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001354 while (Index < IList->getNumInits()) {
1355 Expr *Init = IList->getInit(Index);
1356
1357 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001358 // If we're not the subobject that matches up with the '{' for
1359 // the designator, we shouldn't be handling the
1360 // designator. Return immediately.
1361 if (!SubobjectIsDesignatorContext)
1362 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001363
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001364 // Handle this designated initializer. Field will be updated to
1365 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001366 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001367 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001368 StructuredList, StructuredIndex,
1369 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001370 hadError = true;
1371
Douglas Gregordfb5e592009-02-12 19:00:39 +00001372 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001373
1374 // Disable check for missing fields when designators are used.
1375 // This matches gcc behaviour.
1376 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001377 continue;
1378 }
1379
1380 if (Field == FieldEnd) {
1381 // We've run out of fields. We're done.
1382 break;
1383 }
1384
Douglas Gregordfb5e592009-02-12 19:00:39 +00001385 // We've already initialized a member of a union. We're done.
1386 if (InitializedSomething && DeclType->isUnionType())
1387 break;
1388
Douglas Gregor44b43212008-12-11 16:49:14 +00001389 // If we've hit the flexible array member at the end, we're done.
1390 if (Field->getType()->isIncompleteArrayType())
1391 break;
1392
Douglas Gregor0bb76892009-01-29 16:53:55 +00001393 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001395 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001396 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001397 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001398
Douglas Gregor54001c12011-06-29 21:51:31 +00001399 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001400 bool InvalidUse;
1401 if (VerifyOnly)
1402 InvalidUse = !SemaRef.CanUseDecl(*Field);
1403 else
1404 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1405 IList->getInit(Index)->getLocStart());
1406 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001407 ++Index;
1408 ++Field;
1409 hadError = true;
1410 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001411 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001412
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001413 InitializedEntity MemberEntity =
1414 InitializedEntity::InitializeMember(*Field, &Entity);
1415 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1416 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001417 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001418
Sebastian Redl14b0c192011-09-24 17:48:00 +00001419 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001420 // Initialize the first field within the union.
1421 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001422 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001423
1424 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001425 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001426
John McCall80639de2010-03-11 19:32:38 +00001427 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001428 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1429 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1430 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001431 // It is possible we have one or more unnamed bitfields remaining.
1432 // Find first (if any) named field and emit warning.
1433 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1434 it != end; ++it) {
1435 if (!it->isUnnamedBitfield()) {
1436 SemaRef.Diag(IList->getSourceRange().getEnd(),
1437 diag::warn_missing_field_initializers) << it->getName();
1438 break;
1439 }
1440 }
1441 }
1442
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001443 // Check that any remaining fields can be value-initialized.
1444 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1445 !Field->getType()->isIncompleteArrayType()) {
1446 // FIXME: Should check for holes left by designated initializers too.
1447 for (; Field != FieldEnd && !hadError; ++Field) {
1448 if (!Field->isUnnamedBitfield())
1449 CheckValueInitializable(
1450 InitializedEntity::InitializeMember(*Field, &Entity));
1451 }
1452 }
1453
Mike Stump1eb44332009-09-09 15:08:12 +00001454 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001455 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 return;
1457
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001458 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1459 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001461 ++Index;
1462 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001463 }
1464
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001465 InitializedEntity MemberEntity =
1466 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001467
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001468 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001469 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001470 StructuredList, StructuredIndex);
1471 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001472 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001473 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001474}
Steve Naroff0cca7492008-05-01 22:18:59 +00001475
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001476/// \brief Expand a field designator that refers to a member of an
1477/// anonymous struct or union into a series of field designators that
1478/// refers to the field within the appropriate subobject.
1479///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001480static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001481 DesignatedInitExpr *DIE,
1482 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001483 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001484 typedef DesignatedInitExpr::Designator Designator;
1485
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001486 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001487 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001488 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1489 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1490 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001491 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001492 DIE->getDesignator(DesigIdx)->getDotLoc(),
1493 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1494 else
1495 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1496 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001497 assert(isa<FieldDecl>(*PI));
1498 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001499 }
1500
1501 // Expand the current designator into the set of replacement
1502 // designators, so we have a full subobject path down to where the
1503 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001504 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001505 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001506}
Mike Stump1eb44332009-09-09 15:08:12 +00001507
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001508/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001509/// corresponds to FieldName.
1510static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1511 IdentifierInfo *FieldName) {
1512 assert(AnonField->isAnonymousStructOrUnion());
1513 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001514 while (IndirectFieldDecl *IF =
1515 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Francois Picheta0e27f02010-12-22 03:46:10 +00001516 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1517 return IF;
1518 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001519 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001520 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001521}
1522
Sebastian Redl14b0c192011-09-24 17:48:00 +00001523static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1524 DesignatedInitExpr *DIE) {
1525 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1526 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1527 for (unsigned I = 0; I < NumIndexExprs; ++I)
1528 IndexExprs[I] = DIE->getSubExpr(I + 1);
1529 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1530 DIE->size(), IndexExprs.data(),
1531 NumIndexExprs, DIE->getEqualOrColonLoc(),
1532 DIE->usesGNUSyntax(), DIE->getInit());
1533}
1534
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001535namespace {
1536
1537// Callback to only accept typo corrections that are for field members of
1538// the given struct or union.
1539class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1540 public:
1541 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1542 : Record(RD) {}
1543
1544 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1545 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1546 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1547 }
1548
1549 private:
1550 RecordDecl *Record;
1551};
1552
1553}
1554
Douglas Gregor05c13a32009-01-22 00:58:24 +00001555/// @brief Check the well-formedness of a C99 designated initializer.
1556///
1557/// Determines whether the designated initializer @p DIE, which
1558/// resides at the given @p Index within the initializer list @p
1559/// IList, is well-formed for a current object of type @p DeclType
1560/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001561/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001562/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001563///
1564/// @param IList The initializer list in which this designated
1565/// initializer occurs.
1566///
Douglas Gregor71199712009-04-15 04:56:10 +00001567/// @param DIE The designated initializer expression.
1568///
1569/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001570///
1571/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1572/// into which the designation in @p DIE should refer.
1573///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574/// @param NextField If non-NULL and the first designator in @p DIE is
1575/// a field, this will be set to the field declaration corresponding
1576/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001577///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001578/// @param NextElementIndex If non-NULL and the first designator in @p
1579/// DIE is an array designator or GNU array-range designator, this
1580/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001581///
1582/// @param Index Index into @p IList where the designated initializer
1583/// @p DIE occurs.
1584///
Douglas Gregor4c678342009-01-28 21:54:33 +00001585/// @param StructuredList The initializer list expression that
1586/// describes all of the subobject initializers in the order they'll
1587/// actually be initialized.
1588///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001589/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001590bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001591InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001592 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001593 DesignatedInitExpr *DIE,
1594 unsigned DesigIdx,
1595 QualType &CurrentObjectType,
1596 RecordDecl::field_iterator *NextField,
1597 llvm::APSInt *NextElementIndex,
1598 unsigned &Index,
1599 InitListExpr *StructuredList,
1600 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001601 bool FinishSubobjectInit,
1602 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001603 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001604 // Check the actual initialization for the designated object type.
1605 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001606
1607 // Temporarily remove the designator expression from the
1608 // initializer list that the child calls see, so that we don't try
1609 // to re-process the designator.
1610 unsigned OldIndex = Index;
1611 IList->setInit(OldIndex, DIE->getInit());
1612
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001613 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001614 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001615
1616 // Restore the designated initializer expression in the syntactic
1617 // form of the initializer list.
1618 if (IList->getInit(OldIndex) != DIE->getInit())
1619 DIE->setInit(IList->getInit(OldIndex));
1620 IList->setInit(OldIndex, DIE);
1621
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001622 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001623 }
1624
Douglas Gregor71199712009-04-15 04:56:10 +00001625 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001626 bool IsFirstDesignator = (DesigIdx == 0);
1627 if (!VerifyOnly) {
1628 assert((IsFirstDesignator || StructuredList) &&
1629 "Need a non-designated initializer list to start from");
1630
1631 // Determine the structural initializer list that corresponds to the
1632 // current subobject.
1633 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1634 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1635 StructuredList, StructuredIndex,
1636 SourceRange(D->getStartLocation(),
1637 DIE->getSourceRange().getEnd()));
1638 assert(StructuredList && "Expected a structured initializer list");
1639 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001640
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001641 if (D->isFieldDesignator()) {
1642 // C99 6.7.8p7:
1643 //
1644 // If a designator has the form
1645 //
1646 // . identifier
1647 //
1648 // then the current object (defined below) shall have
1649 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001650 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001651 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001652 if (!RT) {
1653 SourceLocation Loc = D->getDotLoc();
1654 if (Loc.isInvalid())
1655 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001656 if (!VerifyOnly)
1657 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1658 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001659 ++Index;
1660 return true;
1661 }
1662
Douglas Gregor4c678342009-01-28 21:54:33 +00001663 // Note: we perform a linear search of the fields here, despite
1664 // the fact that we have a faster lookup method, because we always
1665 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001666 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001667 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001668 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001669 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001670 Field = RT->getDecl()->field_begin(),
1671 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001672 for (; Field != FieldEnd; ++Field) {
1673 if (Field->isUnnamedBitfield())
1674 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675
Francois Picheta0e27f02010-12-22 03:46:10 +00001676 // If we find a field representing an anonymous field, look in the
1677 // IndirectFieldDecl that follow for the designated initializer.
1678 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1679 if (IndirectFieldDecl *IF =
1680 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001681 // In verify mode, don't modify the original.
1682 if (VerifyOnly)
1683 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001684 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1685 D = DIE->getDesignator(DesigIdx);
1686 break;
1687 }
1688 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001689 if (KnownField && KnownField == *Field)
1690 break;
1691 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001692 break;
1693
1694 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001695 }
1696
Douglas Gregor4c678342009-01-28 21:54:33 +00001697 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001698 if (VerifyOnly) {
1699 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001700 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001701 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001702
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001703 // There was no normal field in the struct with the designated
1704 // name. Perform another lookup for this name, which may find
1705 // something that we can't designate (e.g., a member function),
1706 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001707 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001708 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001709 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001710 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001711 // Name lookup didn't find anything. Determine whether this
1712 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001713 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001714 TypoCorrection Corrected = SemaRef.CorrectTypo(
1715 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001716 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001717 RT->getDecl());
1718 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001719 std::string CorrectedStr(
1720 Corrected.getAsString(SemaRef.getLangOptions()));
1721 std::string CorrectedQuotedStr(
1722 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001723 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001724 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001725 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001726 << FieldName << CurrentObjectType << CorrectedQuotedStr
1727 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001728 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001729 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001730 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001731 } else {
1732 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1733 << FieldName << CurrentObjectType;
1734 ++Index;
1735 return true;
1736 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001738
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001739 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001740 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001741 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001742 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001743 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001744 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001745 ++Index;
1746 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001747 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001748
Francois Picheta0e27f02010-12-22 03:46:10 +00001749 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001750 // The replacement field comes from typo correction; find it
1751 // in the list of fields.
1752 FieldIndex = 0;
1753 Field = RT->getDecl()->field_begin();
1754 for (; Field != FieldEnd; ++Field) {
1755 if (Field->isUnnamedBitfield())
1756 continue;
1757
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001758 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001759 Field->getIdentifier() == ReplacementField->getIdentifier())
1760 break;
1761
1762 ++FieldIndex;
1763 }
1764 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001765 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001766
1767 // All of the fields of a union are located at the same place in
1768 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001769 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001770 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001771 if (!VerifyOnly)
1772 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001773 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001774
Douglas Gregor54001c12011-06-29 21:51:31 +00001775 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001776 bool InvalidUse;
1777 if (VerifyOnly)
1778 InvalidUse = !SemaRef.CanUseDecl(*Field);
1779 else
1780 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1781 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001782 ++Index;
1783 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001784 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001785
Sebastian Redl14b0c192011-09-24 17:48:00 +00001786 if (!VerifyOnly) {
1787 // Update the designator with the field declaration.
1788 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Sebastian Redl14b0c192011-09-24 17:48:00 +00001790 // Make sure that our non-designated initializer list has space
1791 // for a subobject corresponding to this field.
1792 if (FieldIndex >= StructuredList->getNumInits())
1793 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1794 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001795
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001796 // This designator names a flexible array member.
1797 if (Field->getType()->isIncompleteArrayType()) {
1798 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001799 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001800 // We can't designate an object within the flexible array
1801 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001802 if (!VerifyOnly) {
1803 DesignatedInitExpr::Designator *NextD
1804 = DIE->getDesignator(DesigIdx + 1);
1805 SemaRef.Diag(NextD->getStartLocation(),
1806 diag::err_designator_into_flexible_array_member)
1807 << SourceRange(NextD->getStartLocation(),
1808 DIE->getSourceRange().getEnd());
1809 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1810 << *Field;
1811 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001812 Invalid = true;
1813 }
1814
Chris Lattner9046c222010-10-10 17:49:49 +00001815 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1816 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001817 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001818 if (!VerifyOnly) {
1819 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1820 diag::err_flexible_array_init_needs_braces)
1821 << DIE->getInit()->getSourceRange();
1822 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1823 << *Field;
1824 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001825 Invalid = true;
1826 }
1827
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001828 // Check GNU flexible array initializer.
1829 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1830 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001831 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001832
1833 if (Invalid) {
1834 ++Index;
1835 return true;
1836 }
1837
1838 // Initialize the array.
1839 bool prevHadError = hadError;
1840 unsigned newStructuredIndex = FieldIndex;
1841 unsigned OldIndex = Index;
1842 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001843
1844 InitializedEntity MemberEntity =
1845 InitializedEntity::InitializeMember(*Field, &Entity);
1846 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001847 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001848
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001849 IList->setInit(OldIndex, DIE);
1850 if (hadError && !prevHadError) {
1851 ++Field;
1852 ++FieldIndex;
1853 if (NextField)
1854 *NextField = Field;
1855 StructuredIndex = FieldIndex;
1856 return true;
1857 }
1858 } else {
1859 // Recurse to check later designated subobjects.
1860 QualType FieldType = (*Field)->getType();
1861 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001863 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001864 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001865 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1866 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001867 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001868 true, false))
1869 return true;
1870 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001871
1872 // Find the position of the next field to be initialized in this
1873 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001874 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001875 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001876
1877 // If this the first designator, our caller will continue checking
1878 // the rest of this struct/class/union subobject.
1879 if (IsFirstDesignator) {
1880 if (NextField)
1881 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001882 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001883 return false;
1884 }
1885
Douglas Gregor34e79462009-01-28 23:36:17 +00001886 if (!FinishSubobjectInit)
1887 return false;
1888
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001889 // We've already initialized something in the union; we're done.
1890 if (RT->getDecl()->isUnion())
1891 return hadError;
1892
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001893 // Check the remaining fields within this class/struct/union subobject.
1894 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001895
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001896 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001897 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001898 return hadError && !prevHadError;
1899 }
1900
1901 // C99 6.7.8p6:
1902 //
1903 // If a designator has the form
1904 //
1905 // [ constant-expression ]
1906 //
1907 // then the current object (defined below) shall have array
1908 // type and the expression shall be an integer constant
1909 // expression. If the array is of unknown size, any
1910 // nonnegative value is valid.
1911 //
1912 // Additionally, cope with the GNU extension that permits
1913 // designators of the form
1914 //
1915 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001916 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001917 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001918 if (!VerifyOnly)
1919 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1920 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001921 ++Index;
1922 return true;
1923 }
1924
1925 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001926 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1927 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001928 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001929 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001930 DesignatedEndIndex = DesignatedStartIndex;
1931 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001932 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001933
Mike Stump1eb44332009-09-09 15:08:12 +00001934 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001935 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001936 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001937 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001938 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001939
Chris Lattnere0fd8322011-02-19 22:28:58 +00001940 // Codegen can't handle evaluating array range designators that have side
1941 // effects, because we replicate the AST value for each initialized element.
1942 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1943 // elements with something that has a side effect, so codegen can emit an
1944 // "error unsupported" error instead of miscompiling the app.
1945 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001946 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001947 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001948 }
1949
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001950 if (isa<ConstantArrayType>(AT)) {
1951 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001952 DesignatedStartIndex
1953 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001954 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001955 DesignatedEndIndex
1956 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001957 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1958 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001959 if (!VerifyOnly)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001960 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1961 diag::err_array_designator_too_large)
1962 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1963 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001964 ++Index;
1965 return true;
1966 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001967 } else {
1968 // Make sure the bit-widths and signedness match.
1969 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001970 DesignatedEndIndex
1971 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001972 else if (DesignatedStartIndex.getBitWidth() <
1973 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001974 DesignatedStartIndex
1975 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001976 DesignatedStartIndex.setIsUnsigned(true);
1977 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregor4c678342009-01-28 21:54:33 +00001980 // Make sure that our non-designated initializer list has space
1981 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001982 if (!VerifyOnly &&
1983 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001984 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001985 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001986
Douglas Gregor34e79462009-01-28 23:36:17 +00001987 // Repeatedly perform subobject initializations in the range
1988 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001989
Douglas Gregor34e79462009-01-28 23:36:17 +00001990 // Move to the next designator
1991 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1992 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001993
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001994 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001995 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001996
Douglas Gregor34e79462009-01-28 23:36:17 +00001997 while (DesignatedStartIndex <= DesignatedEndIndex) {
1998 // Recurse to check later designated subobjects.
1999 QualType ElementType = AT->getElementType();
2000 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002001
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002002 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002003 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2004 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002005 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002006 (DesignatedStartIndex == DesignatedEndIndex),
2007 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002008 return true;
2009
2010 // Move to the next index in the array that we'll be initializing.
2011 ++DesignatedStartIndex;
2012 ElementIndex = DesignatedStartIndex.getZExtValue();
2013 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002014
2015 // If this the first designator, our caller will continue checking
2016 // the rest of this array subobject.
2017 if (IsFirstDesignator) {
2018 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002019 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002020 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002021 return false;
2022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Douglas Gregor34e79462009-01-28 23:36:17 +00002024 if (!FinishSubobjectInit)
2025 return false;
2026
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002027 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002028 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002029 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002030 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002031 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002032 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002033}
2034
Douglas Gregor4c678342009-01-28 21:54:33 +00002035// Get the structured initializer list for a subobject of type
2036// @p CurrentObjectType.
2037InitListExpr *
2038InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2039 QualType CurrentObjectType,
2040 InitListExpr *StructuredList,
2041 unsigned StructuredIndex,
2042 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002043 if (VerifyOnly)
2044 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002045 Expr *ExistingInit = 0;
2046 if (!StructuredList)
2047 ExistingInit = SyntacticToSemantic[IList];
2048 else if (StructuredIndex < StructuredList->getNumInits())
2049 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Douglas Gregor4c678342009-01-28 21:54:33 +00002051 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2052 return Result;
2053
2054 if (ExistingInit) {
2055 // We are creating an initializer list that initializes the
2056 // subobjects of the current object, but there was already an
2057 // initialization that completely initialized the current
2058 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002059 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002060 // struct X { int a, b; };
2061 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002062 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002063 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2064 // designated initializer re-initializes the whole
2065 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002066 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002067 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002068 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00002069 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002071 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002072 << ExistingInit->getSourceRange();
2073 }
2074
Mike Stump1eb44332009-09-09 15:08:12 +00002075 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002076 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2077 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002078 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002079
Douglas Gregor63982352010-07-13 18:40:04 +00002080 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
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.
Mike Stump1eb44332009-09-09 15:08:12 +00002142 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002143 diag::warn_initializer_overrides)
2144 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002145 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
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) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002163 SourceLocation Loc = Index->getSourceRange().getBegin();
2164
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(),
2267 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002268 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002269
Richard Smithd7c56e12011-12-29 21:57:33 +00002270 if (!getLangOptions().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:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002463 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002464
Douglas Gregorb70cf442010-03-26 20:14:36 +00002465 case FK_ReferenceInitOverloadFailed:
2466 case FK_UserConversionOverloadFailed:
2467 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002468 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002469 return FailedOverloadResult == OR_Ambiguous;
2470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
David Blaikie7530c032012-01-17 06:56:22 +00002472 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002473}
2474
Douglas Gregord6e44a32010-04-16 22:09:46 +00002475bool InitializationSequence::isConstructorInitialization() const {
2476 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2477}
2478
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002479void
2480InitializationSequence
2481::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2482 DeclAccessPair Found,
2483 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002484 Step S;
2485 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2486 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002487 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002488 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002489 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002490 Steps.push_back(S);
2491}
2492
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002493void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002494 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002495 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002496 switch (VK) {
2497 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2498 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2499 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002500 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002501 S.Type = BaseType;
2502 Steps.push_back(S);
2503}
2504
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002505void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002506 bool BindingTemporary) {
2507 Step S;
2508 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2509 S.Type = T;
2510 Steps.push_back(S);
2511}
2512
Douglas Gregor523d46a2010-04-18 07:40:54 +00002513void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2514 Step S;
2515 S.Kind = SK_ExtraneousCopyToTemporary;
2516 S.Type = T;
2517 Steps.push_back(S);
2518}
2519
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002520void
2521InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2522 DeclAccessPair FoundDecl,
2523 QualType T,
2524 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002525 Step S;
2526 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002527 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002528 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002529 S.Function.Function = Function;
2530 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002531 Steps.push_back(S);
2532}
2533
2534void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002535 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002537 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002538 switch (VK) {
2539 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002540 S.Kind = SK_QualificationConversionRValue;
2541 break;
John McCall5baba9d2010-08-25 10:28:54 +00002542 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002543 S.Kind = SK_QualificationConversionXValue;
2544 break;
John McCall5baba9d2010-08-25 10:28:54 +00002545 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002546 S.Kind = SK_QualificationConversionLValue;
2547 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002548 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002549 S.Type = Ty;
2550 Steps.push_back(S);
2551}
2552
2553void InitializationSequence::AddConversionSequenceStep(
2554 const ImplicitConversionSequence &ICS,
2555 QualType T) {
2556 Step S;
2557 S.Kind = SK_ConversionSequence;
2558 S.Type = T;
2559 S.ICS = new ImplicitConversionSequence(ICS);
2560 Steps.push_back(S);
2561}
2562
Douglas Gregord87b61f2009-12-10 17:56:55 +00002563void InitializationSequence::AddListInitializationStep(QualType T) {
2564 Step S;
2565 S.Kind = SK_ListInitialization;
2566 S.Type = T;
2567 Steps.push_back(S);
2568}
2569
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002570void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002571InitializationSequence
2572::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2573 AccessSpecifier Access,
2574 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002575 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002576 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002577 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002578 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2579 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002580 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002581 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002582 S.Function.Function = Constructor;
2583 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002584 Steps.push_back(S);
2585}
2586
Douglas Gregor71d17402009-12-15 00:01:57 +00002587void InitializationSequence::AddZeroInitializationStep(QualType T) {
2588 Step S;
2589 S.Kind = SK_ZeroInitialization;
2590 S.Type = T;
2591 Steps.push_back(S);
2592}
2593
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002594void InitializationSequence::AddCAssignmentStep(QualType T) {
2595 Step S;
2596 S.Kind = SK_CAssignment;
2597 S.Type = T;
2598 Steps.push_back(S);
2599}
2600
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002601void InitializationSequence::AddStringInitStep(QualType T) {
2602 Step S;
2603 S.Kind = SK_StringInit;
2604 S.Type = T;
2605 Steps.push_back(S);
2606}
2607
Douglas Gregor569c3162010-08-07 11:51:51 +00002608void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2609 Step S;
2610 S.Kind = SK_ObjCObjectConversion;
2611 S.Type = T;
2612 Steps.push_back(S);
2613}
2614
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002615void InitializationSequence::AddArrayInitStep(QualType T) {
2616 Step S;
2617 S.Kind = SK_ArrayInit;
2618 S.Type = T;
2619 Steps.push_back(S);
2620}
2621
Richard Smith0f163e92012-02-15 22:38:09 +00002622void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2623 Step S;
2624 S.Kind = SK_ParenthesizedArrayInit;
2625 S.Type = T;
2626 Steps.push_back(S);
2627}
2628
John McCallf85e1932011-06-15 23:02:42 +00002629void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2630 bool shouldCopy) {
2631 Step s;
2632 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2633 : SK_PassByIndirectRestore);
2634 s.Type = type;
2635 Steps.push_back(s);
2636}
2637
2638void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2639 Step S;
2640 S.Kind = SK_ProduceObjCObject;
2641 S.Type = T;
2642 Steps.push_back(S);
2643}
2644
Sebastian Redl2b916b82012-01-17 22:49:42 +00002645void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2646 Step S;
2647 S.Kind = SK_StdInitializerList;
2648 S.Type = T;
2649 Steps.push_back(S);
2650}
2651
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002652void InitializationSequence::RewrapReferenceInitList(QualType T,
2653 InitListExpr *Syntactic) {
2654 assert(Syntactic->getNumInits() == 1 &&
2655 "Can only rewrap trivial init lists.");
2656 Step S;
2657 S.Kind = SK_UnwrapInitList;
2658 S.Type = Syntactic->getInit(0)->getType();
2659 Steps.insert(Steps.begin(), S);
2660
2661 S.Kind = SK_RewrapInitList;
2662 S.Type = T;
2663 S.WrappingSyntacticList = Syntactic;
2664 Steps.push_back(S);
2665}
2666
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002668 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002669 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002670 this->Failure = Failure;
2671 this->FailedOverloadResult = Result;
2672}
2673
2674//===----------------------------------------------------------------------===//
2675// Attempt initialization
2676//===----------------------------------------------------------------------===//
2677
John McCallf85e1932011-06-15 23:02:42 +00002678static void MaybeProduceObjCObject(Sema &S,
2679 InitializationSequence &Sequence,
2680 const InitializedEntity &Entity) {
2681 if (!S.getLangOptions().ObjCAutoRefCount) return;
2682
2683 /// When initializing a parameter, produce the value if it's marked
2684 /// __attribute__((ns_consumed)).
2685 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2686 if (!Entity.isParameterConsumed())
2687 return;
2688
2689 assert(Entity.getType()->isObjCRetainableType() &&
2690 "consuming an object of unretainable type?");
2691 Sequence.AddProduceObjCObjectStep(Entity.getType());
2692
2693 /// When initializing a return value, if the return type is a
2694 /// retainable type, then returns need to immediately retain the
2695 /// object. If an autorelease is required, it will be done at the
2696 /// last instant.
2697 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2698 if (!Entity.getType()->isObjCRetainableType())
2699 return;
2700
2701 Sequence.AddProduceObjCObjectStep(Entity.getType());
2702 }
2703}
2704
Sebastian Redl10f04a62011-12-22 14:44:04 +00002705/// \brief When initializing from init list via constructor, deal with the
2706/// empty init list and std::initializer_list special cases.
2707///
2708/// \return True if this was a special case, false otherwise.
2709static bool TryListConstructionSpecialCases(Sema &S,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002710 InitListExpr *List,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002711 CXXRecordDecl *DestRecordDecl,
2712 QualType DestType,
2713 InitializationSequence &Sequence) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002714 // C++11 [dcl.init.list]p3:
Richard Smith1d0c9a82012-02-14 21:14:13 +00002715 // List-initialization of an object or reference of type T is defined as
2716 // follows:
2717 // - If T is an aggregate, aggregate initialization is performed.
2718 if (DestType->isAggregateType())
2719 return false;
2720
2721 // - Otherwise, if the initializer list has no elements and T is a class
2722 // type with a default constructor, the object is value-initialized.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002723 if (List->getNumInits() == 0) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002724 if (CXXConstructorDecl *DefaultConstructor =
2725 S.LookupDefaultConstructor(DestRecordDecl)) {
2726 if (DefaultConstructor->isDeleted() ||
2727 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2728 // Fake an overload resolution failure.
2729 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2730 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2731 DefaultConstructor->getAccess());
2732 if (FunctionTemplateDecl *ConstructorTmpl =
2733 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2734 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2735 /*ExplicitArgs*/ 0,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002736 0, 0, CandidateSet,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002737 /*SuppressUserConversions*/ false);
2738 else
2739 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002740 0, 0, CandidateSet,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002741 /*SuppressUserConversions*/ false);
2742 Sequence.SetOverloadFailure(
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002743 InitializationSequence::FK_ListConstructorOverloadFailed,
2744 OR_Deleted);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002745 } else
2746 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2747 DefaultConstructor->getAccess(),
2748 DestType,
2749 /*MultipleCandidates=*/false,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002750 /*FromInitList=*/true,
2751 /*AsInitList=*/false);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002752 return true;
2753 }
2754 }
2755
2756 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redl2b916b82012-01-17 22:49:42 +00002757 QualType E;
2758 if (S.isStdInitializerList(DestType, &E)) {
2759 // Check that each individual element can be copy-constructed. But since we
2760 // have no place to store further information, we'll recalculate everything
2761 // later.
2762 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2763 S.Context.getConstantArrayType(E,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002764 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2765 List->getNumInits()),
Sebastian Redl2b916b82012-01-17 22:49:42 +00002766 ArrayType::Normal, 0));
2767 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2768 0, HiddenArray);
Sebastian Redl08ae3692012-02-04 21:27:33 +00002769 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002770 Element.setElementIndex(i);
Sebastian Redl08ae3692012-02-04 21:27:33 +00002771 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002772 Sequence.SetFailed(
2773 InitializationSequence::FK_InitListElementCopyFailure);
2774 return true;
2775 }
2776 }
2777 Sequence.AddStdInitializerListConstructionStep(DestType);
2778 return true;
2779 }
Sebastian Redl10f04a62011-12-22 14:44:04 +00002780
2781 // Not a special case.
2782 return false;
2783}
2784
Sebastian Redl96715b22012-02-04 21:27:39 +00002785static OverloadingResult
2786ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2787 Expr **Args, unsigned NumArgs,
2788 OverloadCandidateSet &CandidateSet,
2789 DeclContext::lookup_iterator Con,
2790 DeclContext::lookup_iterator ConEnd,
2791 OverloadCandidateSet::iterator &Best,
2792 bool CopyInitializing, bool AllowExplicit,
2793 bool OnlyListConstructors) {
2794 CandidateSet.clear();
2795
2796 for (; Con != ConEnd; ++Con) {
2797 NamedDecl *D = *Con;
2798 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2799 bool SuppressUserConversions = false;
2800
2801 // Find the constructor (which may be a template).
2802 CXXConstructorDecl *Constructor = 0;
2803 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2804 if (ConstructorTmpl)
2805 Constructor = cast<CXXConstructorDecl>(
2806 ConstructorTmpl->getTemplatedDecl());
2807 else {
2808 Constructor = cast<CXXConstructorDecl>(D);
2809
2810 // If we're performing copy initialization using a copy constructor, we
2811 // suppress user-defined conversions on the arguments.
2812 // FIXME: Move constructors?
2813 if (CopyInitializing && Constructor->isCopyConstructor())
2814 SuppressUserConversions = true;
2815 }
2816
2817 if (!Constructor->isInvalidDecl() &&
2818 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002819 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002820 if (ConstructorTmpl)
2821 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2822 /*ExplicitArgs*/ 0,
2823 Args, NumArgs, CandidateSet,
2824 SuppressUserConversions);
2825 else
2826 S.AddOverloadCandidate(Constructor, FoundDecl,
2827 Args, NumArgs, CandidateSet,
2828 SuppressUserConversions);
2829 }
2830 }
2831
2832 // Perform overload resolution and return the result.
2833 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2834}
2835
Sebastian Redl10f04a62011-12-22 14:44:04 +00002836/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2837/// enumerates the constructors of the initialized entity and performs overload
2838/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002839/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002840/// class type.
2841static void TryConstructorInitialization(Sema &S,
2842 const InitializedEntity &Entity,
2843 const InitializationKind &Kind,
2844 Expr **Args, unsigned NumArgs,
2845 QualType DestType,
2846 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002847 bool InitListSyntax = false) {
2848 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2849 "InitListSyntax must come with a single initializer list argument.");
2850
Sebastian Redl10f04a62011-12-22 14:44:04 +00002851 // Check constructor arguments for self reference.
2852 if (DeclaratorDecl *DD = Entity.getDecl())
2853 // Parameters arguments are occassionially constructed with itself,
2854 // for instance, in recursive functions. Skip them.
2855 if (!isa<ParmVarDecl>(DD))
2856 for (unsigned i = 0; i < NumArgs; ++i)
2857 S.CheckSelfReference(DD, Args[i]);
2858
Sebastian Redl10f04a62011-12-22 14:44:04 +00002859 // The type we're constructing needs to be complete.
2860 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2861 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Sebastian Redl96715b22012-02-04 21:27:39 +00002862 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002863 }
2864
2865 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2866 assert(DestRecordType && "Constructor initialization requires record type");
2867 CXXRecordDecl *DestRecordDecl
2868 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2869
Sebastian Redl08ae3692012-02-04 21:27:33 +00002870 if (InitListSyntax &&
2871 TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
2872 DestRecordDecl, DestType, Sequence))
Sebastian Redl10f04a62011-12-22 14:44:04 +00002873 return;
2874
Sebastian Redl96715b22012-02-04 21:27:39 +00002875 // Build the candidate set directly in the initialization sequence
2876 // structure, so that it will persist if we fail.
2877 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2878
2879 // Determine whether we are allowed to call explicit constructors or
2880 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00002881 bool AllowExplicit = Kind.AllowExplicit();
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002882 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002883
Sebastian Redl10f04a62011-12-22 14:44:04 +00002884 // - Otherwise, if T is a class type, constructors are considered. The
2885 // applicable constructors are enumerated, and the best one is chosen
2886 // through overload resolution.
Sebastian Redl96715b22012-02-04 21:27:39 +00002887 DeclContext::lookup_iterator ConStart, ConEnd;
2888 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002889
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002890 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002891 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002892 bool AsInitializerList = false;
2893
2894 // C++11 [over.match.list]p1:
2895 // When objects of non-aggregate type T are list-initialized, overload
2896 // resolution selects the constructor in two phases:
2897 // - Initially, the candidate functions are the initializer-list
2898 // constructors of the class T and the argument list consists of the
2899 // initializer list as a single argument.
2900 if (InitListSyntax) {
2901 AsInitializerList = true;
2902 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2903 CandidateSet, ConStart, ConEnd, Best,
2904 CopyInitialization, AllowExplicit,
2905 /*OnlyListConstructor=*/true);
2906
2907 // Time to unwrap the init list.
2908 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2909 Args = ILE->getInits();
2910 NumArgs = ILE->getNumInits();
2911 }
2912
2913 // C++11 [over.match.list]p1:
2914 // - If no viable initializer-list constructor is found, overload resolution
2915 // is performed again, where the candidate functions are all the
2916 // constructors of the class T nad the argument list consists of the
2917 // elements of the initializer list.
2918 if (Result == OR_No_Viable_Function) {
2919 AsInitializerList = false;
2920 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2921 CandidateSet, ConStart, ConEnd, Best,
2922 CopyInitialization, AllowExplicit,
2923 /*OnlyListConstructors=*/false);
2924 }
2925 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002926 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002927 InitializationSequence::FK_ListConstructorOverloadFailed :
2928 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002929 Result);
2930 return;
2931 }
2932
2933 // C++0x [dcl.init]p6:
2934 // If a program calls for the default initialization of an object
2935 // of a const-qualified type T, T shall be a class type with a
2936 // user-provided default constructor.
2937 if (Kind.getKind() == InitializationKind::IK_Default &&
2938 Entity.getType().isConstQualified() &&
2939 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2940 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2941 return;
2942 }
2943
2944 // Add the constructor initialization step. Any cv-qualification conversion is
2945 // subsumed by the initialization.
2946 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2947 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2948 Sequence.AddConstructorInitializationStep(CtorDecl,
2949 Best->FoundDecl.getAccess(),
2950 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002951 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002952}
2953
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002954static bool
2955ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2956 Expr *Initializer,
2957 QualType &SourceType,
2958 QualType &UnqualifiedSourceType,
2959 QualType UnqualifiedTargetType,
2960 InitializationSequence &Sequence) {
2961 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2962 S.Context.OverloadTy) {
2963 DeclAccessPair Found;
2964 bool HadMultipleCandidates = false;
2965 if (FunctionDecl *Fn
2966 = S.ResolveAddressOfOverloadedFunction(Initializer,
2967 UnqualifiedTargetType,
2968 false, Found,
2969 &HadMultipleCandidates)) {
2970 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2971 HadMultipleCandidates);
2972 SourceType = Fn->getType();
2973 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2974 } else if (!UnqualifiedTargetType->isRecordType()) {
2975 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2976 return true;
2977 }
2978 }
2979 return false;
2980}
2981
2982static void TryReferenceInitializationCore(Sema &S,
2983 const InitializedEntity &Entity,
2984 const InitializationKind &Kind,
2985 Expr *Initializer,
2986 QualType cv1T1, QualType T1,
2987 Qualifiers T1Quals,
2988 QualType cv2T2, QualType T2,
2989 Qualifiers T2Quals,
2990 InitializationSequence &Sequence);
2991
2992static void TryListInitialization(Sema &S,
2993 const InitializedEntity &Entity,
2994 const InitializationKind &Kind,
2995 InitListExpr *InitList,
2996 InitializationSequence &Sequence);
2997
2998/// \brief Attempt list initialization of a reference.
2999static void TryReferenceListInitialization(Sema &S,
3000 const InitializedEntity &Entity,
3001 const InitializationKind &Kind,
3002 InitListExpr *InitList,
3003 InitializationSequence &Sequence)
3004{
3005 // First, catch C++03 where this isn't possible.
3006 if (!S.getLangOptions().CPlusPlus0x) {
3007 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3008 return;
3009 }
3010
3011 QualType DestType = Entity.getType();
3012 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3013 Qualifiers T1Quals;
3014 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3015
3016 // Reference initialization via an initializer list works thus:
3017 // If the initializer list consists of a single element that is
3018 // reference-related to the referenced type, bind directly to that element
3019 // (possibly creating temporaries).
3020 // Otherwise, initialize a temporary with the initializer list and
3021 // bind to that.
3022 if (InitList->getNumInits() == 1) {
3023 Expr *Initializer = InitList->getInit(0);
3024 QualType cv2T2 = Initializer->getType();
3025 Qualifiers T2Quals;
3026 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3027
3028 // If this fails, creating a temporary wouldn't work either.
3029 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3030 T1, Sequence))
3031 return;
3032
3033 SourceLocation DeclLoc = Initializer->getLocStart();
3034 bool dummy1, dummy2, dummy3;
3035 Sema::ReferenceCompareResult RefRelationship
3036 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3037 dummy2, dummy3);
3038 if (RefRelationship >= Sema::Ref_Related) {
3039 // Try to bind the reference here.
3040 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3041 T1Quals, cv2T2, T2, T2Quals, Sequence);
3042 if (Sequence)
3043 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3044 return;
3045 }
3046 }
3047
3048 // Not reference-related. Create a temporary and bind to that.
3049 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3050
3051 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3052 if (Sequence) {
3053 if (DestType->isRValueReferenceType() ||
3054 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3055 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3056 else
3057 Sequence.SetFailed(
3058 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3059 }
3060}
3061
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003062/// \brief Attempt list initialization (C++0x [dcl.init.list])
3063static void TryListInitialization(Sema &S,
3064 const InitializedEntity &Entity,
3065 const InitializationKind &Kind,
3066 InitListExpr *InitList,
3067 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003068 QualType DestType = Entity.getType();
3069
Sebastian Redl14b0c192011-09-24 17:48:00 +00003070 // C++ doesn't allow scalar initialization with more than one argument.
3071 // But C99 complex numbers are scalars and it makes sense there.
3072 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3073 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3074 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3075 return;
3076 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003077 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003078 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003079 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003080 }
3081 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003082 if (S.getLangOptions().CPlusPlus0x) {
3083 Expr *Arg = InitList;
Sebastian Redl168319c2012-02-12 16:37:24 +00003084 // A direct-initializer is not list-syntax, i.e. there's no special
3085 // treatment of "A a({1, 2});".
Sebastian Redl08ae3692012-02-04 21:27:33 +00003086 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
Sebastian Redl168319c2012-02-12 16:37:24 +00003087 Sequence, Kind.getKind() != InitializationKind::IK_Direct);
Sebastian Redl08ae3692012-02-04 21:27:33 +00003088 } else
Sebastian Redl10f04a62011-12-22 14:44:04 +00003089 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003090 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003091 }
3092
Sebastian Redl14b0c192011-09-24 17:48:00 +00003093 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003094 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003095 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redlc2235182011-10-16 18:19:28 +00003096 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003097 if (CheckInitList.HadError()) {
3098 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3099 return;
3100 }
3101
3102 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003103 Sequence.AddListInitializationStep(DestType);
3104}
Douglas Gregor20093b42009-12-09 23:02:17 +00003105
3106/// \brief Try a reference initialization that involves calling a conversion
3107/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003108static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3109 const InitializedEntity &Entity,
3110 const InitializationKind &Kind,
3111 Expr *Initializer,
3112 bool AllowRValues,
3113 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003114 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003115 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3116 QualType T1 = cv1T1.getUnqualifiedType();
3117 QualType cv2T2 = Initializer->getType();
3118 QualType T2 = cv2T2.getUnqualifiedType();
3119
3120 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003121 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003122 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003124 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003125 ObjCConversion,
3126 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003127 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003128 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003129 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003130 (void)ObjCLifetimeConversion;
3131
Douglas Gregor20093b42009-12-09 23:02:17 +00003132 // Build the candidate set directly in the initialization sequence
3133 // structure, so that it will persist if we fail.
3134 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3135 CandidateSet.clear();
3136
3137 // Determine whether we are allowed to call explicit constructors or
3138 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003139 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003140
Douglas Gregor20093b42009-12-09 23:02:17 +00003141 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003142 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3143 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003144 // The type we're converting to is a class type. Enumerate its constructors
3145 // to see if there is a suitable conversion.
3146 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003147
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003149 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00003150 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003151 NamedDecl *D = *Con;
3152 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3153
Douglas Gregor20093b42009-12-09 23:02:17 +00003154 // Find the constructor (which may be a template).
3155 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003156 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003157 if (ConstructorTmpl)
3158 Constructor = cast<CXXConstructorDecl>(
3159 ConstructorTmpl->getTemplatedDecl());
3160 else
John McCall9aa472c2010-03-19 07:35:19 +00003161 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003162
Douglas Gregor20093b42009-12-09 23:02:17 +00003163 if (!Constructor->isInvalidDecl() &&
3164 Constructor->isConvertingConstructor(AllowExplicit)) {
3165 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003166 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003167 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003168 &Initializer, 1, CandidateSet,
3169 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003170 else
John McCall9aa472c2010-03-19 07:35:19 +00003171 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003172 &Initializer, 1, CandidateSet,
3173 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003176 }
John McCall572fc622010-08-17 07:23:57 +00003177 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3178 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003179
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003180 const RecordType *T2RecordType = 0;
3181 if ((T2RecordType = T2->getAs<RecordType>()) &&
3182 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003183 // The type we're converting from is a class type, enumerate its conversion
3184 // functions.
3185 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3186
John McCalleec51cf2010-01-20 00:46:10 +00003187 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00003188 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003189 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3190 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003191 NamedDecl *D = *I;
3192 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3193 if (isa<UsingShadowDecl>(D))
3194 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195
Douglas Gregor20093b42009-12-09 23:02:17 +00003196 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3197 CXXConversionDecl *Conv;
3198 if (ConvTemplate)
3199 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3200 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003201 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202
Douglas Gregor20093b42009-12-09 23:02:17 +00003203 // If the conversion function doesn't return a reference type,
3204 // it can't be considered for this conversion unless we're allowed to
3205 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003206 // FIXME: Do we need to make sure that we only consider conversion
3207 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003208 // break recursion.
3209 if ((AllowExplicit || !Conv->isExplicit()) &&
3210 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3211 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003212 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003213 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003214 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003215 else
John McCall9aa472c2010-03-19 07:35:19 +00003216 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003217 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003218 }
3219 }
3220 }
John McCall572fc622010-08-17 07:23:57 +00003221 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3222 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223
Douglas Gregor20093b42009-12-09 23:02:17 +00003224 SourceLocation DeclLoc = Initializer->getLocStart();
3225
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003227 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003228 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003229 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003230 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003231
Douglas Gregor20093b42009-12-09 23:02:17 +00003232 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003233
Chandler Carruth25ca4212011-02-25 19:41:05 +00003234 // This is the overload that will actually be used for the initialization, so
3235 // mark it as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +00003236 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003237
Eli Friedman03981012009-12-11 02:42:07 +00003238 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003239 if (isa<CXXConversionDecl>(Function))
3240 T2 = Function->getResultType();
3241 else
3242 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003243
3244 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003245 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003246 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003247 T2.getNonLValueExprType(S.Context),
3248 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003249
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003251 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003252 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003253 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003254 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003255 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003256 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003257
Douglas Gregor20093b42009-12-09 23:02:17 +00003258 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003259 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003260 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003261 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003262 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003263 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003264 NewDerivedToBase, NewObjCConversion,
3265 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003266 if (NewRefRelationship == Sema::Ref_Incompatible) {
3267 // If the type we've converted to is not reference-related to the
3268 // type we're looking for, then there is another conversion step
3269 // we need to perform to produce a temporary of the right type
3270 // that we'll be binding to.
3271 ImplicitConversionSequence ICS;
3272 ICS.setStandard();
3273 ICS.Standard = Best->FinalConversion;
3274 T2 = ICS.Standard.getToType(2);
3275 Sequence.AddConversionSequenceStep(ICS, T2);
3276 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003277 Sequence.AddDerivedToBaseCastStep(
3278 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003280 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003281 else if (NewObjCConversion)
3282 Sequence.AddObjCObjectConversionStep(
3283 S.Context.getQualifiedType(T1,
3284 T2.getNonReferenceType().getQualifiers()));
3285
Douglas Gregor20093b42009-12-09 23:02:17 +00003286 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003287 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288
Douglas Gregor20093b42009-12-09 23:02:17 +00003289 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3290 return OR_Success;
3291}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003292
Richard Smith83da2e72011-10-19 16:55:56 +00003293static void CheckCXX98CompatAccessibleCopy(Sema &S,
3294 const InitializedEntity &Entity,
3295 Expr *CurInitExpr);
3296
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3298static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003299 const InitializedEntity &Entity,
3300 const InitializationKind &Kind,
3301 Expr *Initializer,
3302 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003303 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003304 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003305 Qualifiers T1Quals;
3306 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003307 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003308 Qualifiers T2Quals;
3309 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003310
Douglas Gregor20093b42009-12-09 23:02:17 +00003311 // If the initializer is the address of an overloaded function, try
3312 // to resolve the overloaded function. If all goes well, T2 is the
3313 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003314 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3315 T1, Sequence))
3316 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003317
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003318 // Delegate everything else to a subfunction.
3319 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3320 T1Quals, cv2T2, T2, T2Quals, Sequence);
3321}
3322
3323/// \brief Reference initialization without resolving overloaded functions.
3324static void TryReferenceInitializationCore(Sema &S,
3325 const InitializedEntity &Entity,
3326 const InitializationKind &Kind,
3327 Expr *Initializer,
3328 QualType cv1T1, QualType T1,
3329 Qualifiers T1Quals,
3330 QualType cv2T2, QualType T2,
3331 Qualifiers T2Quals,
3332 InitializationSequence &Sequence) {
3333 QualType DestType = Entity.getType();
3334 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003335 // Compute some basic properties of the types and the initializer.
3336 bool isLValueRef = DestType->isLValueReferenceType();
3337 bool isRValueRef = !isLValueRef;
3338 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003339 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003340 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003341 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003342 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003343 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003344 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003345
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003348 // "cv2 T2" as follows:
3349 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003350 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003351 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003352 // Note the analogous bullet points for rvlaue refs to functions. Because
3353 // there are no function rvalues in C++, rvalue refs to functions are treated
3354 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003355 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003356 bool T1Function = T1->isFunctionType();
3357 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003359 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003361 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003363 // reference-compatible with "cv2 T2," or
3364 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003366 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003367 // can occur. However, we do pay attention to whether it is a bit-field
3368 // to decide whether we're actually binding to a temporary created from
3369 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 if (DerivedToBase)
3371 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003372 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003373 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003374 else if (ObjCConversion)
3375 Sequence.AddObjCObjectConversionStep(
3376 S.Context.getQualifiedType(T1, T2Quals));
3377
Chandler Carruth5535c382010-01-12 20:32:25 +00003378 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003379 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003380 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003381 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003382 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 return;
3384 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
3386 // - has a class type (i.e., T2 is a class type), where T1 is not
3387 // reference-related to T2, and can be implicitly converted to an
3388 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3389 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003390 // applicable conversion functions (13.3.1.6) and choosing the best
3391 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003392 // If we have an rvalue ref to function type here, the rhs must be
3393 // an rvalue.
3394 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3395 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003397 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003398 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003399 Sequence);
3400 if (ConvOvlResult == OR_Success)
3401 return;
John McCall1d318332010-01-12 00:44:57 +00003402 if (ConvOvlResult != OR_No_Viable_Function) {
3403 Sequence.SetOverloadFailure(
3404 InitializationSequence::FK_ReferenceInitOverloadFailed,
3405 ConvOvlResult);
3406 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003407 }
3408 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003409
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003411 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003412 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003413 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003414 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3415 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3416 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003417 Sequence.SetOverloadFailure(
3418 InitializationSequence::FK_ReferenceInitOverloadFailed,
3419 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003420 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003421 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003422 ? (RefRelationship == Sema::Ref_Related
3423 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3424 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3425 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003426
Douglas Gregor20093b42009-12-09 23:02:17 +00003427 return;
3428 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003429
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003430 // - If the initializer expression
3431 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3432 // "cv1 T1" is reference-compatible with "cv2 T2"
3433 // Note: functions are handled below.
3434 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003435 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003436 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003437 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003438 (InitCategory.isXValue() ||
3439 (InitCategory.isPRValue() && T2->isRecordType()) ||
3440 (InitCategory.isPRValue() && T2->isArrayType()))) {
3441 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3442 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003443 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3444 // compiler the freedom to perform a copy here or bind to the
3445 // object, while C++0x requires that we bind directly to the
3446 // object. Hence, we always bind to the object without making an
3447 // extra copy. However, in C++03 requires that we check for the
3448 // presence of a suitable copy constructor:
3449 //
3450 // The constructor that would be used to make the copy shall
3451 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003452 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003453 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith83da2e72011-10-19 16:55:56 +00003454 else if (S.getLangOptions().CPlusPlus0x)
3455 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003456 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003457
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003458 if (DerivedToBase)
3459 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3460 ValueKind);
3461 else if (ObjCConversion)
3462 Sequence.AddObjCObjectConversionStep(
3463 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003465 if (T1Quals != T2Quals)
3466 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003468 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003469 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003471
3472 // - has a class type (i.e., T2 is a class type), where T1 is not
3473 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003474 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3475 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003476 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003477 if (RefRelationship == Sema::Ref_Incompatible) {
3478 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3479 Kind, Initializer,
3480 /*AllowRValues=*/true,
3481 Sequence);
3482 if (ConvOvlResult)
3483 Sequence.SetOverloadFailure(
3484 InitializationSequence::FK_ReferenceInitOverloadFailed,
3485 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486
Douglas Gregor20093b42009-12-09 23:02:17 +00003487 return;
3488 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489
Douglas Gregor20093b42009-12-09 23:02:17 +00003490 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3491 return;
3492 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003493
3494 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003495 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003497 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003498
Douglas Gregor20093b42009-12-09 23:02:17 +00003499 // Determine whether we are allowed to call explicit constructors or
3500 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003501 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003502
3503 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3504
John McCallf85e1932011-06-15 23:02:42 +00003505 ImplicitConversionSequence ICS
3506 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003507 /*SuppressUserConversions*/ false,
3508 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003509 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003510 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3511 /*AllowObjCWritebackConversion=*/false);
3512
3513 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003514 // FIXME: Use the conversion function set stored in ICS to turn
3515 // this into an overloading ambiguity diagnostic. However, we need
3516 // to keep that set as an OverloadCandidateSet rather than as some
3517 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003518 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3519 Sequence.SetOverloadFailure(
3520 InitializationSequence::FK_ReferenceInitOverloadFailed,
3521 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003522 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3523 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003524 else
3525 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003526 return;
John McCallf85e1932011-06-15 23:02:42 +00003527 } else {
3528 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003529 }
3530
3531 // [...] If T1 is reference-related to T2, cv1 must be the
3532 // same cv-qualification as, or greater cv-qualification
3533 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003534 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3535 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003537 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003538 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3539 return;
3540 }
3541
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003542 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003543 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003544 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003545 InitCategory.isLValue()) {
3546 Sequence.SetFailed(
3547 InitializationSequence::FK_RValueReferenceBindingToLValue);
3548 return;
3549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550
Douglas Gregor20093b42009-12-09 23:02:17 +00003551 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3552 return;
3553}
3554
3555/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556/// (C++ [dcl.init.string], C99 6.7.8).
3557static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003558 const InitializedEntity &Entity,
3559 const InitializationKind &Kind,
3560 Expr *Initializer,
3561 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003562 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003563}
3564
Douglas Gregor71d17402009-12-15 00:01:57 +00003565/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003566static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003567 const InitializedEntity &Entity,
3568 const InitializationKind &Kind,
3569 InitializationSequence &Sequence) {
Richard Smith1d0c9a82012-02-14 21:14:13 +00003570 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003571 //
3572 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003573 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003574
Douglas Gregor71d17402009-12-15 00:01:57 +00003575 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003576 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577
Douglas Gregor71d17402009-12-15 00:01:57 +00003578 if (const RecordType *RT = T->getAs<RecordType>()) {
3579 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smith1d0c9a82012-02-14 21:14:13 +00003580 // C++98:
Douglas Gregor71d17402009-12-15 00:01:57 +00003581 // -- if T is a class type (clause 9) with a user-declared
3582 // constructor (12.1), then the default constructor for T is
3583 // called (and the initialization is ill-formed if T has no
3584 // accessible default constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003585 if (!S.getLangOptions().CPlusPlus0x) {
3586 if (ClassDecl->hasUserDeclaredConstructor())
3587 // FIXME: we really want to refer to a single subobject of the array,
3588 // but Entity doesn't have a way to capture that (yet).
3589 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3590 T, Sequence);
3591 } else {
3592 // C++11:
3593 // -- if T is a class type (clause 9) with either no default constructor
3594 // (12.1 [class.ctor]) or a default constructor that is user-provided
3595 // or deleted, then the object is default-initialized;
3596 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3597 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3598 return TryConstructorInitialization(S, Entity, Kind, 0, 0,
3599 T, Sequence);
3600 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003601
Richard Smith1d0c9a82012-02-14 21:14:13 +00003602 // -- if T is a (possibly cv-qualified) non-union class type without a
3603 // user-provided or deleted default constructor, then the object is
3604 // zero-initialized and, if T has a non-trivial default constructor,
3605 // default-initialized;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003606 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003607 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003608 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003609 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003610 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003611 }
3612 }
3613
Douglas Gregord6542d82009-12-22 15:35:07 +00003614 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003615}
3616
Douglas Gregor99a2e602009-12-16 01:38:02 +00003617/// \brief Attempt default initialization (C++ [dcl.init]p6).
3618static void TryDefaultInitialization(Sema &S,
3619 const InitializedEntity &Entity,
3620 const InitializationKind &Kind,
3621 InitializationSequence &Sequence) {
3622 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003623
Douglas Gregor99a2e602009-12-16 01:38:02 +00003624 // C++ [dcl.init]p6:
3625 // To default-initialize an object of type T means:
3626 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003627 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3628
Douglas Gregor99a2e602009-12-16 01:38:02 +00003629 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3630 // constructor for T is called (and the initialization is ill-formed if
3631 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003632 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003633 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3634 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003635 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003636
Douglas Gregor99a2e602009-12-16 01:38:02 +00003637 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003638
Douglas Gregor99a2e602009-12-16 01:38:02 +00003639 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003640 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003641 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003642 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003643 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003644 return;
3645 }
3646
3647 // If the destination type has a lifetime property, zero-initialize it.
3648 if (DestType.getQualifiers().hasObjCLifetime()) {
3649 Sequence.AddZeroInitializationStep(Entity.getType());
3650 return;
3651 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003652}
3653
Douglas Gregor20093b42009-12-09 23:02:17 +00003654/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3655/// which enumerates all conversion functions and performs overload resolution
3656/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003657static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 const InitializedEntity &Entity,
3659 const InitializationKind &Kind,
3660 Expr *Initializer,
3661 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003662 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003663 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3664 QualType SourceType = Initializer->getType();
3665 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3666 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003667
Douglas Gregor4a520a22009-12-14 17:27:33 +00003668 // Build the candidate set directly in the initialization sequence
3669 // structure, so that it will persist if we fail.
3670 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3671 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003672
Douglas Gregor4a520a22009-12-14 17:27:33 +00003673 // Determine whether we are allowed to call explicit constructors or
3674 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003675 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003676
Douglas Gregor4a520a22009-12-14 17:27:33 +00003677 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3678 // The type we're converting to is a class type. Enumerate its constructors
3679 // to see if there is a suitable conversion.
3680 CXXRecordDecl *DestRecordDecl
3681 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003682
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003683 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003685 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003686 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003687 Con != ConEnd; ++Con) {
3688 NamedDecl *D = *Con;
3689 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003691 // Find the constructor (which may be a template).
3692 CXXConstructorDecl *Constructor = 0;
3693 FunctionTemplateDecl *ConstructorTmpl
3694 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003695 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003696 Constructor = cast<CXXConstructorDecl>(
3697 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003698 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003699 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003700
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003701 if (!Constructor->isInvalidDecl() &&
3702 Constructor->isConvertingConstructor(AllowExplicit)) {
3703 if (ConstructorTmpl)
3704 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3705 /*ExplicitArgs*/ 0,
3706 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003707 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003708 else
3709 S.AddOverloadCandidate(Constructor, FoundDecl,
3710 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003711 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003712 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003713 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003714 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003715 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003716
3717 SourceLocation DeclLoc = Initializer->getLocStart();
3718
Douglas Gregor4a520a22009-12-14 17:27:33 +00003719 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3720 // The type we're converting from is a class type, enumerate its conversion
3721 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003722
Eli Friedman33c2da92009-12-20 22:12:03 +00003723 // We can only enumerate the conversion functions for a complete type; if
3724 // the type isn't complete, simply skip this step.
3725 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3726 CXXRecordDecl *SourceRecordDecl
3727 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728
John McCalleec51cf2010-01-20 00:46:10 +00003729 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003730 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003731 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003732 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003733 I != E; ++I) {
3734 NamedDecl *D = *I;
3735 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3736 if (isa<UsingShadowDecl>(D))
3737 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003738
Eli Friedman33c2da92009-12-20 22:12:03 +00003739 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3740 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003741 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003742 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003743 else
John McCall32daa422010-03-31 01:36:47 +00003744 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003745
Eli Friedman33c2da92009-12-20 22:12:03 +00003746 if (AllowExplicit || !Conv->isExplicit()) {
3747 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003748 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003749 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003750 CandidateSet);
3751 else
John McCall9aa472c2010-03-19 07:35:19 +00003752 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003753 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003754 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003755 }
3756 }
3757 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003758
3759 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003760 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003761 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003762 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003763 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003764 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003765 Result);
3766 return;
3767 }
John McCall1d318332010-01-12 00:44:57 +00003768
Douglas Gregor4a520a22009-12-14 17:27:33 +00003769 FunctionDecl *Function = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00003770 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003771 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
Douglas Gregor4a520a22009-12-14 17:27:33 +00003773 if (isa<CXXConstructorDecl>(Function)) {
3774 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003775 // subsumed by the initialization. Per DR5, the created temporary is of the
3776 // cv-unqualified type of the destination.
3777 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3778 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003779 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003780 return;
3781 }
3782
3783 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003784 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003785 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003786 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003787 // the resulting temporary object (possible to create an object of
3788 // a base class type). That copy is not a separate conversion, so
3789 // we just make a note of the actual destination type (possibly a
3790 // base class of the type returned by the conversion function) and
3791 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003792 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3793 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003794 return;
3795 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003796
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003797 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3798 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003799
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003800 // If the conversion following the call to the conversion function
3801 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003802 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3803 Best->FinalConversion.Third) {
3804 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003805 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003806 ICS.Standard = Best->FinalConversion;
3807 Sequence.AddConversionSequenceStep(ICS, DestType);
3808 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003809}
3810
John McCallf85e1932011-06-15 23:02:42 +00003811/// The non-zero enum values here are indexes into diagnostic alternatives.
3812enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3813
3814/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003815static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3816 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003817 // Skip parens.
3818 e = e->IgnoreParens();
3819
3820 // Skip address-of nodes.
3821 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3822 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003823 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003824
3825 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003826 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3827 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003828 case CK_Dependent:
3829 case CK_BitCast:
3830 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003831 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003832 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003833
3834 case CK_ArrayToPointerDecay:
3835 return IIK_nonscalar;
3836
3837 case CK_NullToPointer:
3838 return IIK_okay;
3839
3840 default:
3841 break;
3842 }
3843
3844 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003845 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3846 if (!isAddressOf) return IIK_nonlocal;
3847
3848 VarDecl *var;
3849 if (isa<DeclRefExpr>(e)) {
3850 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3851 if (!var) return IIK_nonlocal;
3852 } else {
3853 var = cast<BlockDeclRefExpr>(e)->getDecl();
3854 }
3855
3856 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003857
3858 // If we have a conditional operator, check both sides.
3859 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003860 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003861 return iik;
3862
John McCallc03fa492011-06-27 23:59:58 +00003863 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003864
3865 // These are never scalar.
3866 } else if (isa<ArraySubscriptExpr>(e)) {
3867 return IIK_nonscalar;
3868
3869 // Otherwise, it needs to be a null pointer constant.
3870 } else {
3871 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3872 ? IIK_okay : IIK_nonlocal);
3873 }
3874
3875 return IIK_nonlocal;
3876}
3877
3878/// Check whether the given expression is a valid operand for an
3879/// indirect copy/restore.
3880static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3881 assert(src->isRValue());
3882
John McCallc03fa492011-06-27 23:59:58 +00003883 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003884 if (iik == IIK_okay) return;
3885
3886 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3887 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3888 << src->getSourceRange();
3889}
3890
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003891/// \brief Determine whether we have compatible array types for the
3892/// purposes of GNU by-copy array initialization.
3893static bool hasCompatibleArrayTypes(ASTContext &Context,
3894 const ArrayType *Dest,
3895 const ArrayType *Source) {
3896 // If the source and destination array types are equivalent, we're
3897 // done.
3898 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3899 return true;
3900
3901 // Make sure that the element types are the same.
3902 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3903 return false;
3904
3905 // The only mismatch we allow is when the destination is an
3906 // incomplete array type and the source is a constant array type.
3907 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3908}
3909
John McCallf85e1932011-06-15 23:02:42 +00003910static bool tryObjCWritebackConversion(Sema &S,
3911 InitializationSequence &Sequence,
3912 const InitializedEntity &Entity,
3913 Expr *Initializer) {
3914 bool ArrayDecay = false;
3915 QualType ArgType = Initializer->getType();
3916 QualType ArgPointee;
3917 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3918 ArrayDecay = true;
3919 ArgPointee = ArgArrayType->getElementType();
3920 ArgType = S.Context.getPointerType(ArgPointee);
3921 }
3922
3923 // Handle write-back conversion.
3924 QualType ConvertedArgType;
3925 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3926 ConvertedArgType))
3927 return false;
3928
3929 // We should copy unless we're passing to an argument explicitly
3930 // marked 'out'.
3931 bool ShouldCopy = true;
3932 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3933 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3934
3935 // Do we need an lvalue conversion?
3936 if (ArrayDecay || Initializer->isGLValue()) {
3937 ImplicitConversionSequence ICS;
3938 ICS.setStandard();
3939 ICS.Standard.setAsIdentityConversion();
3940
3941 QualType ResultType;
3942 if (ArrayDecay) {
3943 ICS.Standard.First = ICK_Array_To_Pointer;
3944 ResultType = S.Context.getPointerType(ArgPointee);
3945 } else {
3946 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3947 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3948 }
3949
3950 Sequence.AddConversionSequenceStep(ICS, ResultType);
3951 }
3952
3953 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3954 return true;
3955}
3956
Douglas Gregor20093b42009-12-09 23:02:17 +00003957InitializationSequence::InitializationSequence(Sema &S,
3958 const InitializedEntity &Entity,
3959 const InitializationKind &Kind,
3960 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003961 unsigned NumArgs)
3962 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003963 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964
Douglas Gregor20093b42009-12-09 23:02:17 +00003965 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003966 // The semantics of initializers are as follows. The destination type is
3967 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003968 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003969 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003970 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003971 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003972
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003973 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003974 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3975 SequenceKind = DependentSequence;
3976 return;
3977 }
3978
Sebastian Redl7491c492011-06-05 13:59:11 +00003979 // Almost everything is a normal sequence.
3980 setSequenceKind(NormalSequence);
3981
John McCall241d5582010-12-07 22:54:16 +00003982 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00003983 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00003984 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00003985 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
3986 if (result.isInvalid()) {
3987 SetFailed(FK_PlaceholderType);
3988 return;
John McCall5acb0c92011-10-17 18:40:02 +00003989 }
John McCall32509f12011-11-15 01:35:18 +00003990 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00003991 }
John McCall241d5582010-12-07 22:54:16 +00003992
John McCall5acb0c92011-10-17 18:40:02 +00003993
Douglas Gregor20093b42009-12-09 23:02:17 +00003994 QualType SourceType;
3995 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003996 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003997 Initializer = Args[0];
3998 if (!isa<InitListExpr>(Initializer))
3999 SourceType = Initializer->getType();
4000 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004001
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004002 // - If the initializer is a (non-parenthesized) braced-init-list, the
4003 // object is list-initialized (8.5.4).
4004 if (Kind.getKind() != InitializationKind::IK_Direct) {
4005 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4006 TryListInitialization(S, Entity, Kind, InitList, *this);
4007 return;
4008 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004010
Douglas Gregor20093b42009-12-09 23:02:17 +00004011 // - If the destination type is a reference type, see 8.5.3.
4012 if (DestType->isReferenceType()) {
4013 // C++0x [dcl.init.ref]p1:
4014 // A variable declared to be a T& or T&&, that is, "reference to type T"
4015 // (8.3.2), shall be initialized by an object, or function, of type T or
4016 // by an object that can be converted into a T.
4017 // (Therefore, multiple arguments are not permitted.)
4018 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004019 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004020 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004021 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004022 return;
4023 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024
Douglas Gregor20093b42009-12-09 23:02:17 +00004025 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004026 if (Kind.getKind() == InitializationKind::IK_Value ||
4027 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004028 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004029 return;
4030 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004031
Douglas Gregor99a2e602009-12-16 01:38:02 +00004032 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004033 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004034 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004035 return;
4036 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004037
John McCallce6c9b72011-02-21 07:22:22 +00004038 // - If the destination type is an array of characters, an array of
4039 // char16_t, an array of char32_t, or an array of wchar_t, and the
4040 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004041 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004042 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004043 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004044 if (Initializer && isa<VariableArrayType>(DestAT)) {
4045 SetFailed(FK_VariableLengthArrayHasInitializer);
4046 return;
4047 }
4048
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004049 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004050 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004051 return;
4052 }
4053
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004054 // Note: as an GNU C extension, we allow initialization of an
4055 // array from a compound literal that creates an array of the same
4056 // type, so long as the initializer has no side effects.
4057 if (!S.getLangOptions().CPlusPlus && Initializer &&
4058 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4059 Initializer->getType()->isArrayType()) {
4060 const ArrayType *SourceAT
4061 = Context.getAsArrayType(Initializer->getType());
4062 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004063 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004064 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004065 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004066 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004067 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004068 }
Richard Smith0f163e92012-02-15 22:38:09 +00004069 }
4070 // Note: as a GNU C++ extension, we allow initialization of a
4071 // class member from a parenthesized initializer list.
4072 else if (S.getLangOptions().CPlusPlus &&
4073 Entity.getKind() == InitializedEntity::EK_Member &&
4074 Initializer && isa<InitListExpr>(Initializer)) {
4075 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4076 *this);
4077 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004078 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004079 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004080 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004081 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004082
Douglas Gregor20093b42009-12-09 23:02:17 +00004083 return;
4084 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004085
John McCallf85e1932011-06-15 23:02:42 +00004086 // Determine whether we should consider writeback conversions for
4087 // Objective-C ARC.
4088 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4089 Entity.getKind() == InitializedEntity::EK_Parameter;
4090
4091 // We're at the end of the line for C: it's either a write-back conversion
4092 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004093 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004094 // If allowed, check whether this is an Objective-C writeback conversion.
4095 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004096 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004097 return;
4098 }
4099
4100 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004101 AddCAssignmentStep(DestType);
4102 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004103 return;
4104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004105
John McCallf85e1932011-06-15 23:02:42 +00004106 assert(S.getLangOptions().CPlusPlus);
4107
Douglas Gregor20093b42009-12-09 23:02:17 +00004108 // - If the destination type is a (possibly cv-qualified) class type:
4109 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110 // - If the initialization is direct-initialization, or if it is
4111 // copy-initialization where the cv-unqualified version of the
4112 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004113 // class of the destination, constructors are considered. [...]
4114 if (Kind.getKind() == InitializationKind::IK_Direct ||
4115 (Kind.getKind() == InitializationKind::IK_Copy &&
4116 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4117 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004118 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004119 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004120 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004121 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004122 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004123 // used) to a derived class thereof are enumerated as described in
4124 // 13.3.1.4, and the best one is chosen through overload resolution
4125 // (13.3).
4126 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004127 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004128 return;
4129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004130
Douglas Gregor99a2e602009-12-16 01:38:02 +00004131 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004132 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004133 return;
4134 }
4135 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136
4137 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004138 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004139 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004140 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4141 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004142 return;
4143 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144
Douglas Gregor20093b42009-12-09 23:02:17 +00004145 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004146 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004147 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004148 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004149 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004150
4151 ImplicitConversionSequence ICS
4152 = S.TryImplicitConversion(Initializer, Entity.getType(),
4153 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004154 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004155 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004156 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4157 allowObjCWritebackConversion);
4158
4159 if (ICS.isStandard() &&
4160 ICS.Standard.Second == ICK_Writeback_Conversion) {
4161 // Objective-C ARC writeback conversion.
4162
4163 // We should copy unless we're passing to an argument explicitly
4164 // marked 'out'.
4165 bool ShouldCopy = true;
4166 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4167 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4168
4169 // If there was an lvalue adjustment, add it as a separate conversion.
4170 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4171 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4172 ImplicitConversionSequence LvalueICS;
4173 LvalueICS.setStandard();
4174 LvalueICS.Standard.setAsIdentityConversion();
4175 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4176 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004177 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004178 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004179
4180 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004181 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004182 DeclAccessPair dap;
4183 if (Initializer->getType() == Context.OverloadTy &&
4184 !S.ResolveAddressOfOverloadedFunction(Initializer
4185 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004186 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004187 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004188 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004189 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004190 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004191
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004192 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004193 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004194}
4195
4196InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004197 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004198 StepEnd = Steps.end();
4199 Step != StepEnd; ++Step)
4200 Step->Destroy();
4201}
4202
4203//===----------------------------------------------------------------------===//
4204// Perform initialization
4205//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004206static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004207getAssignmentAction(const InitializedEntity &Entity) {
4208 switch(Entity.getKind()) {
4209 case InitializedEntity::EK_Variable:
4210 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004211 case InitializedEntity::EK_Exception:
4212 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004213 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004214 return Sema::AA_Initializing;
4215
4216 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004218 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4219 return Sema::AA_Sending;
4220
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004221 return Sema::AA_Passing;
4222
4223 case InitializedEntity::EK_Result:
4224 return Sema::AA_Returning;
4225
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004226 case InitializedEntity::EK_Temporary:
4227 // FIXME: Can we tell apart casting vs. converting?
4228 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004229
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004230 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004231 case InitializedEntity::EK_ArrayElement:
4232 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004233 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004234 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004235 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004236 return Sema::AA_Initializing;
4237 }
4238
David Blaikie7530c032012-01-17 06:56:22 +00004239 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004240}
4241
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004242/// \brief Whether we should binding a created object as a temporary when
4243/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004244static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004245 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004246 case InitializedEntity::EK_ArrayElement:
4247 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004248 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004249 case InitializedEntity::EK_New:
4250 case InitializedEntity::EK_Variable:
4251 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004252 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004253 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004254 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004255 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004256 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004257 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004258 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004259
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004260 case InitializedEntity::EK_Parameter:
4261 case InitializedEntity::EK_Temporary:
4262 return true;
4263 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004264
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004265 llvm_unreachable("missed an InitializedEntity kind?");
4266}
4267
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004268/// \brief Whether the given entity, when initialized with an object
4269/// created for that initialization, requires destruction.
4270static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4271 switch (Entity.getKind()) {
4272 case InitializedEntity::EK_Member:
4273 case InitializedEntity::EK_Result:
4274 case InitializedEntity::EK_New:
4275 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004276 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004277 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004278 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004279 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004280 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004281 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004282
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004283 case InitializedEntity::EK_Variable:
4284 case InitializedEntity::EK_Parameter:
4285 case InitializedEntity::EK_Temporary:
4286 case InitializedEntity::EK_ArrayElement:
4287 case InitializedEntity::EK_Exception:
4288 return true;
4289 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290
4291 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004292}
4293
Richard Smith83da2e72011-10-19 16:55:56 +00004294/// \brief Look for copy and move constructors and constructor templates, for
4295/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4296static void LookupCopyAndMoveConstructors(Sema &S,
4297 OverloadCandidateSet &CandidateSet,
4298 CXXRecordDecl *Class,
4299 Expr *CurInitExpr) {
4300 DeclContext::lookup_iterator Con, ConEnd;
4301 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4302 Con != ConEnd; ++Con) {
4303 CXXConstructorDecl *Constructor = 0;
4304
4305 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4306 // Handle copy/moveconstructors, only.
4307 if (!Constructor || Constructor->isInvalidDecl() ||
4308 !Constructor->isCopyOrMoveConstructor() ||
4309 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4310 continue;
4311
4312 DeclAccessPair FoundDecl
4313 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4314 S.AddOverloadCandidate(Constructor, FoundDecl,
4315 &CurInitExpr, 1, CandidateSet);
4316 continue;
4317 }
4318
4319 // Handle constructor templates.
4320 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4321 if (ConstructorTmpl->isInvalidDecl())
4322 continue;
4323
4324 Constructor = cast<CXXConstructorDecl>(
4325 ConstructorTmpl->getTemplatedDecl());
4326 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4327 continue;
4328
4329 // FIXME: Do we need to limit this to copy-constructor-like
4330 // candidates?
4331 DeclAccessPair FoundDecl
4332 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4333 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4334 &CurInitExpr, 1, CandidateSet, true);
4335 }
4336}
4337
4338/// \brief Get the location at which initialization diagnostics should appear.
4339static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4340 Expr *Initializer) {
4341 switch (Entity.getKind()) {
4342 case InitializedEntity::EK_Result:
4343 return Entity.getReturnLoc();
4344
4345 case InitializedEntity::EK_Exception:
4346 return Entity.getThrowLoc();
4347
4348 case InitializedEntity::EK_Variable:
4349 return Entity.getDecl()->getLocation();
4350
Douglas Gregor47736542012-02-15 16:57:26 +00004351 case InitializedEntity::EK_LambdaCapture:
4352 return Entity.getCaptureLoc();
4353
Richard Smith83da2e72011-10-19 16:55:56 +00004354 case InitializedEntity::EK_ArrayElement:
4355 case InitializedEntity::EK_Member:
4356 case InitializedEntity::EK_Parameter:
4357 case InitializedEntity::EK_Temporary:
4358 case InitializedEntity::EK_New:
4359 case InitializedEntity::EK_Base:
4360 case InitializedEntity::EK_Delegating:
4361 case InitializedEntity::EK_VectorElement:
4362 case InitializedEntity::EK_ComplexElement:
4363 case InitializedEntity::EK_BlockElement:
4364 return Initializer->getLocStart();
4365 }
4366 llvm_unreachable("missed an InitializedEntity kind?");
4367}
4368
Douglas Gregor523d46a2010-04-18 07:40:54 +00004369/// \brief Make a (potentially elidable) temporary copy of the object
4370/// provided by the given initializer by calling the appropriate copy
4371/// constructor.
4372///
4373/// \param S The Sema object used for type-checking.
4374///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004375/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004376/// the type of the initializer expression or a superclass thereof.
4377///
4378/// \param Enter The entity being initialized.
4379///
4380/// \param CurInit The initializer expression.
4381///
4382/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4383/// is permitted in C++03 (but not C++0x) when binding a reference to
4384/// an rvalue.
4385///
4386/// \returns An expression that copies the initializer expression into
4387/// a temporary object, or an error expression if a copy could not be
4388/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004389static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004390 QualType T,
4391 const InitializedEntity &Entity,
4392 ExprResult CurInit,
4393 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004394 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004395 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004396 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004397 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004398 Class = cast<CXXRecordDecl>(Record->getDecl());
4399 if (!Class)
4400 return move(CurInit);
4401
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004402 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004403 // When certain criteria are met, an implementation is allowed to
4404 // omit the copy/move construction of a class object, even if the
4405 // copy/move constructor and/or destructor for the object have
4406 // side effects. [...]
4407 // - when a temporary class object that has not been bound to a
4408 // reference (12.2) would be copied/moved to a class object
4409 // with the same cv-unqualified type, the copy/move operation
4410 // can be omitted by constructing the temporary object
4411 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004412 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004413 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004414 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004415 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004416 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004417 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004418 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004419
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004420 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004421 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4422 return move(CurInit);
4423
Douglas Gregorcc15f012011-01-21 19:38:21 +00004424 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004425 // Only consider constructors and constructor templates. Per
4426 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4427 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004428 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004429 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004430
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004431 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4432
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004433 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004434 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004435 case OR_Success:
4436 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004437
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004438 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004439 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4440 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4441 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004442 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004443 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004444 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004445 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004446 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004447 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004448
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004449 case OR_Ambiguous:
4450 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004451 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004452 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004453 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004454 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004456 case OR_Deleted:
4457 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004458 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004459 << CurInitExpr->getSourceRange();
4460 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004461 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004462 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004463 }
4464
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004465 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004466 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004467 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004468
Anders Carlsson9a68a672010-04-21 18:47:17 +00004469 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004470 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004471
4472 if (IsExtraneousCopy) {
4473 // If this is a totally extraneous copy for C++03 reference
4474 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004475 // expression. We don't generate an (elided) copy operation here
4476 // because doing so would require us to pass down a flag to avoid
4477 // infinite recursion, where each step adds another extraneous,
4478 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004479
Douglas Gregor2559a702010-04-18 07:57:34 +00004480 // Instantiate the default arguments of any extra parameters in
4481 // the selected copy constructor, as if we were going to create a
4482 // proper call to the copy constructor.
4483 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4484 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4485 if (S.RequireCompleteType(Loc, Parm->getType(),
4486 S.PDiag(diag::err_call_incomplete_argument)))
4487 break;
4488
4489 // Build the default argument expression; we don't actually care
4490 // if this succeeds or not, because this routine will complain
4491 // if there was a problem.
4492 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4493 }
4494
Douglas Gregor523d46a2010-04-18 07:40:54 +00004495 return S.Owned(CurInitExpr);
4496 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497
Eli Friedman5f2987c2012-02-02 03:46:19 +00004498 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00004499
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004500 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004501 // constructor call (we might have derived-to-base conversions, or
4502 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004503 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004504 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004505 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004506
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004507 // Actually perform the constructor call.
4508 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004509 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004510 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004511 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004512 CXXConstructExpr::CK_Complete,
4513 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004515 // If we're supposed to bind temporaries, do so.
4516 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4517 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4518 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004519}
Douglas Gregor20093b42009-12-09 23:02:17 +00004520
Richard Smith83da2e72011-10-19 16:55:56 +00004521/// \brief Check whether elidable copy construction for binding a reference to
4522/// a temporary would have succeeded if we were building in C++98 mode, for
4523/// -Wc++98-compat.
4524static void CheckCXX98CompatAccessibleCopy(Sema &S,
4525 const InitializedEntity &Entity,
4526 Expr *CurInitExpr) {
4527 assert(S.getLangOptions().CPlusPlus0x);
4528
4529 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4530 if (!Record)
4531 return;
4532
4533 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4534 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4535 == DiagnosticsEngine::Ignored)
4536 return;
4537
4538 // Find constructors which would have been considered.
4539 OverloadCandidateSet CandidateSet(Loc);
4540 LookupCopyAndMoveConstructors(
4541 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4542
4543 // Perform overload resolution.
4544 OverloadCandidateSet::iterator Best;
4545 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4546
4547 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4548 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4549 << CurInitExpr->getSourceRange();
4550
4551 switch (OR) {
4552 case OR_Success:
4553 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4554 Best->FoundDecl.getAccess(), Diag);
4555 // FIXME: Check default arguments as far as that's possible.
4556 break;
4557
4558 case OR_No_Viable_Function:
4559 S.Diag(Loc, Diag);
4560 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4561 break;
4562
4563 case OR_Ambiguous:
4564 S.Diag(Loc, Diag);
4565 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4566 break;
4567
4568 case OR_Deleted:
4569 S.Diag(Loc, Diag);
4570 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4571 << 1 << Best->Function->isDeleted();
4572 break;
4573 }
4574}
4575
Douglas Gregora41a8c52010-04-22 00:20:18 +00004576void InitializationSequence::PrintInitLocationNote(Sema &S,
4577 const InitializedEntity &Entity) {
4578 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4579 if (Entity.getDecl()->getLocation().isInvalid())
4580 return;
4581
4582 if (Entity.getDecl()->getDeclName())
4583 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4584 << Entity.getDecl()->getDeclName();
4585 else
4586 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4587 }
4588}
4589
Sebastian Redl3b802322011-07-14 19:07:55 +00004590static bool isReferenceBinding(const InitializationSequence::Step &s) {
4591 return s.Kind == InitializationSequence::SK_BindReference ||
4592 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4593}
4594
Sebastian Redl10f04a62011-12-22 14:44:04 +00004595static ExprResult
4596PerformConstructorInitialization(Sema &S,
4597 const InitializedEntity &Entity,
4598 const InitializationKind &Kind,
4599 MultiExprArg Args,
4600 const InitializationSequence::Step& Step,
4601 bool &ConstructorInitRequiresZeroInit) {
4602 unsigned NumArgs = Args.size();
4603 CXXConstructorDecl *Constructor
4604 = cast<CXXConstructorDecl>(Step.Function.Function);
4605 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4606
4607 // Build a call to the selected constructor.
4608 ASTOwningVector<Expr*> ConstructorArgs(S);
4609 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4610 ? Kind.getEqualLoc()
4611 : Kind.getLocation();
4612
4613 if (Kind.getKind() == InitializationKind::IK_Default) {
4614 // Force even a trivial, implicit default constructor to be
4615 // semantically checked. We do this explicitly because we don't build
4616 // the definition for completely trivial constructors.
4617 CXXRecordDecl *ClassDecl = Constructor->getParent();
4618 assert(ClassDecl && "No parent class for constructor.");
4619 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4620 ClassDecl->hasTrivialDefaultConstructor() &&
4621 !Constructor->isUsed(false))
4622 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4623 }
4624
4625 ExprResult CurInit = S.Owned((Expr *)0);
4626
4627 // Determine the arguments required to actually perform the constructor
4628 // call.
4629 if (S.CompleteConstructorCall(Constructor, move(Args),
4630 Loc, ConstructorArgs))
4631 return ExprError();
4632
4633
4634 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4635 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4636 (Kind.getKind() == InitializationKind::IK_Direct ||
4637 Kind.getKind() == InitializationKind::IK_Value)) {
4638 // An explicitly-constructed temporary, e.g., X(1, 2).
4639 unsigned NumExprs = ConstructorArgs.size();
4640 Expr **Exprs = (Expr **)ConstructorArgs.take();
Eli Friedman5f2987c2012-02-02 03:46:19 +00004641 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redl10f04a62011-12-22 14:44:04 +00004642 S.DiagnoseUseOfDecl(Constructor, Loc);
4643
4644 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4645 if (!TSInfo)
4646 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4647
4648 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4649 Constructor,
4650 TSInfo,
4651 Exprs,
4652 NumExprs,
4653 Kind.getParenRange(),
4654 HadMultipleCandidates,
4655 ConstructorInitRequiresZeroInit));
4656 } else {
4657 CXXConstructExpr::ConstructionKind ConstructKind =
4658 CXXConstructExpr::CK_Complete;
4659
4660 if (Entity.getKind() == InitializedEntity::EK_Base) {
4661 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4662 CXXConstructExpr::CK_VirtualBase :
4663 CXXConstructExpr::CK_NonVirtualBase;
4664 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4665 ConstructKind = CXXConstructExpr::CK_Delegating;
4666 }
4667
4668 // Only get the parenthesis range if it is a direct construction.
4669 SourceRange parenRange =
4670 Kind.getKind() == InitializationKind::IK_Direct ?
4671 Kind.getParenRange() : SourceRange();
4672
4673 // If the entity allows NRVO, mark the construction as elidable
4674 // unconditionally.
4675 if (Entity.allowsNRVO())
4676 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4677 Constructor, /*Elidable=*/true,
4678 move_arg(ConstructorArgs),
4679 HadMultipleCandidates,
4680 ConstructorInitRequiresZeroInit,
4681 ConstructKind,
4682 parenRange);
4683 else
4684 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4685 Constructor,
4686 move_arg(ConstructorArgs),
4687 HadMultipleCandidates,
4688 ConstructorInitRequiresZeroInit,
4689 ConstructKind,
4690 parenRange);
4691 }
4692 if (CurInit.isInvalid())
4693 return ExprError();
4694
4695 // Only check access if all of that succeeded.
4696 S.CheckConstructorAccess(Loc, Constructor, Entity,
4697 Step.Function.FoundDecl.getAccess());
4698 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4699
4700 if (shouldBindAsTemporary(Entity))
4701 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4702
4703 return move(CurInit);
4704}
4705
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004706ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004707InitializationSequence::Perform(Sema &S,
4708 const InitializedEntity &Entity,
4709 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004710 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004711 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004712 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004713 unsigned NumArgs = Args.size();
4714 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004715 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004716 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717
Sebastian Redl7491c492011-06-05 13:59:11 +00004718 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004719 // If the declaration is a non-dependent, incomplete array type
4720 // that has an initializer, then its type will be completed once
4721 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004722 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004723 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004724 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004725 if (const IncompleteArrayType *ArrayT
4726 = S.Context.getAsIncompleteArrayType(DeclType)) {
4727 // FIXME: We don't currently have the ability to accurately
4728 // compute the length of an initializer list without
4729 // performing full type-checking of the initializer list
4730 // (since we have to determine where braces are implicitly
4731 // introduced and such). So, we fall back to making the array
4732 // type a dependently-sized array type with no specified
4733 // bound.
4734 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4735 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004736
Douglas Gregord87b61f2009-12-10 17:56:55 +00004737 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004738 if (DeclaratorDecl *DD = Entity.getDecl()) {
4739 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4740 TypeLoc TL = TInfo->getTypeLoc();
4741 if (IncompleteArrayTypeLoc *ArrayLoc
4742 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4743 Brackets = ArrayLoc->getBracketsRange();
4744 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004745 }
4746
4747 *ResultType
4748 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4749 /*NumElts=*/0,
4750 ArrayT->getSizeModifier(),
4751 ArrayT->getIndexTypeCVRQualifiers(),
4752 Brackets);
4753 }
4754
4755 }
4756 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004757 if (Kind.getKind() == InitializationKind::IK_Direct &&
4758 !Kind.isExplicitCast()) {
4759 // Rebuild the ParenListExpr.
4760 SourceRange ParenRange = Kind.getParenRange();
4761 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
4762 move(Args));
4763 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004764 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4765 Kind.isExplicitCast());
4766 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004767 }
4768
Sebastian Redl7491c492011-06-05 13:59:11 +00004769 // No steps means no initialization.
4770 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004771 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004772
Douglas Gregord6542d82009-12-22 15:35:07 +00004773 QualType DestType = Entity.getType().getNonReferenceType();
4774 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004775 // the same as Entity.getDecl()->getType() in cases involving type merging,
4776 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004777 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004778 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004779 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004780
John McCall60d7b3a2010-08-24 06:29:42 +00004781 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004782
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004783 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004784 // grab the only argument out the Args and place it into the "current"
4785 // initializer.
4786 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004787 case SK_ResolveAddressOfOverloadedFunction:
4788 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004789 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004790 case SK_CastDerivedToBaseLValue:
4791 case SK_BindReference:
4792 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004793 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004794 case SK_UserConversion:
4795 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004796 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004797 case SK_QualificationConversionRValue:
4798 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004799 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004800 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004801 case SK_UnwrapInitList:
4802 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004803 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004804 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004805 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004806 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00004807 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00004808 case SK_PassByIndirectCopyRestore:
4809 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00004810 case SK_ProduceObjCObject:
4811 case SK_StdInitializerList: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004812 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004813 CurInit = Args.get()[0];
4814 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004815 break;
John McCallf6a16482010-12-04 03:47:34 +00004816 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004817
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004818 case SK_ConstructorInitialization:
4819 case SK_ZeroInitialization:
4820 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004822
4823 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004824 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004825 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004826 for (step_iterator Step = step_begin(), StepEnd = step_end();
4827 Step != StepEnd; ++Step) {
4828 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004829 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004830
John Wiegley429bb272011-04-08 18:41:53 +00004831 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004832
Douglas Gregor20093b42009-12-09 23:02:17 +00004833 switch (Step->Kind) {
4834 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004835 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004836 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004837 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004838 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004839 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004840 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004841 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004842 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004843
Douglas Gregor20093b42009-12-09 23:02:17 +00004844 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004845 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004846 case SK_CastDerivedToBaseLValue: {
4847 // We have a derived-to-base cast that produces either an rvalue or an
4848 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004849
John McCallf871d0c2010-08-07 06:22:56 +00004850 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004851
Douglas Gregor20093b42009-12-09 23:02:17 +00004852 // Casts to inaccessible base classes are allowed with C-style casts.
4853 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4854 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004855 CurInit.get()->getLocStart(),
4856 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004857 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004858 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004859
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004860 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4861 QualType T = SourceType;
4862 if (const PointerType *Pointer = T->getAs<PointerType>())
4863 T = Pointer->getPointeeType();
4864 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004865 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004866 cast<CXXRecordDecl>(RecordTy->getDecl()));
4867 }
4868
John McCall5baba9d2010-08-25 10:28:54 +00004869 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004870 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004871 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004872 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004873 VK_XValue :
4874 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004875 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4876 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004877 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004878 CurInit.get(),
4879 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004880 break;
4881 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004882
Douglas Gregor20093b42009-12-09 23:02:17 +00004883 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004884 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004885 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4886 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004887 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004888 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004889 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004890 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004891 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004892 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004893
John Wiegley429bb272011-04-08 18:41:53 +00004894 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004895 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004896 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4897 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004898 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004899 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004900 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004901 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004902
Douglas Gregor20093b42009-12-09 23:02:17 +00004903 // Reference binding does not have any corresponding ASTs.
4904
4905 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004906 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004907 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004908
Douglas Gregor20093b42009-12-09 23:02:17 +00004909 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004910
Douglas Gregor20093b42009-12-09 23:02:17 +00004911 case SK_BindReferenceToTemporary:
4912 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004913 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004914 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004915
Douglas Gregor03e80032011-06-21 17:03:29 +00004916 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004917 CurInit = new (S.Context) MaterializeTemporaryExpr(
4918 Entity.getType().getNonReferenceType(),
4919 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004920 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004921
4922 // If we're binding to an Objective-C object that has lifetime, we
4923 // need cleanups.
4924 if (S.getLangOptions().ObjCAutoRefCount &&
4925 CurInit.get()->getType()->isObjCLifetimeType())
4926 S.ExprNeedsCleanups = true;
4927
Douglas Gregor20093b42009-12-09 23:02:17 +00004928 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004929
Douglas Gregor523d46a2010-04-18 07:40:54 +00004930 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004931 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004932 /*IsExtraneousCopy=*/true);
4933 break;
4934
Douglas Gregor20093b42009-12-09 23:02:17 +00004935 case SK_UserConversion: {
4936 // We have a user-defined conversion that invokes either a constructor
4937 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004938 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004939 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004940 FunctionDecl *Fn = Step->Function.Function;
4941 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004942 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004943 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004944 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004945 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004946 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004947 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004948 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004949
Douglas Gregor20093b42009-12-09 23:02:17 +00004950 // Determine the arguments required to actually perform the constructor
4951 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004952 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004953 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004954 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004955 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004956 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004957
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004958 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004959 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004960 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004961 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004962 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004963 CXXConstructExpr::CK_Complete,
4964 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004965 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004966 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004967
Anders Carlsson9a68a672010-04-21 18:47:17 +00004968 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004969 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004970 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004971
John McCall2de56d12010-08-25 11:45:40 +00004972 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004973 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4974 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4975 S.IsDerivedFrom(SourceType, Class))
4976 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004977
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004978 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004979 } else {
4980 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004981 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00004982 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004983 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004984 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004985
4986 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004987 // derived-to-base conversion? I believe the answer is "no", because
4988 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004989 ExprResult CurInitExprRes =
4990 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4991 FoundFn, Conversion);
4992 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004993 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004994 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004995
Douglas Gregor20093b42009-12-09 23:02:17 +00004996 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004997 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4998 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00004999 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005000 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005001
John McCall2de56d12010-08-25 11:45:40 +00005002 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005004 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005005 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005006
Sebastian Redl3b802322011-07-14 19:07:55 +00005007 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005008 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5009
5010 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005011 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005012 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005013 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005014 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005015 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005016 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005017 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley429bb272011-04-08 18:41:53 +00005018 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005019 }
5020 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005021
John McCallf871d0c2010-08-07 06:22:56 +00005022 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005023 CurInit.get()->getType(),
5024 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005025 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005026 if (MaybeBindToTemp)
5027 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005028 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005029 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5030 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005031 break;
5032 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005033
Douglas Gregor20093b42009-12-09 23:02:17 +00005034 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005035 case SK_QualificationConversionXValue:
5036 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005037 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005038 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005039 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005040 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005041 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005042 VK_XValue :
5043 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005044 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005045 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005046 }
5047
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005048 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005049 Sema::CheckedConversionKind CCK
5050 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5051 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005052 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005053 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005054 ExprResult CurInitExprRes =
5055 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005056 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005057 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005058 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005059 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00005060 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005061 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005062
Douglas Gregord87b61f2009-12-10 17:56:55 +00005063 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005064 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005065 // Hack: We must pass *ResultType if available in order to set the type
5066 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5067 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5068 // temporary, not a reference, so we should pass Ty.
5069 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5070 // Since this step is never used for a reference directly, we explicitly
5071 // unwrap references here and rewrap them afterwards.
5072 // We also need to create a InitializeTemporary entity for this.
5073 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5074 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5075 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5076 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5077 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005078 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redlc2235182011-10-16 18:19:28 +00005079 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005080 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005081 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005082
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005083 if (ResultType) {
5084 if ((*ResultType)->isRValueReferenceType())
5085 Ty = S.Context.getRValueReferenceType(Ty);
5086 else if ((*ResultType)->isLValueReferenceType())
5087 Ty = S.Context.getLValueReferenceType(Ty,
5088 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5089 *ResultType = Ty;
5090 }
5091
5092 InitListExpr *StructuredInitList =
5093 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005094 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005095 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005096 break;
5097 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005098
Sebastian Redl10f04a62011-12-22 14:44:04 +00005099 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005100 // When an initializer list is passed for a parameter of type "reference
5101 // to object", we don't get an EK_Temporary entity, but instead an
5102 // EK_Parameter entity with reference type.
5103 // FIXME: This is a hack. Why is this necessary here, but not in other
5104 // places where implicit temporaries are created?
5105 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5106 Entity.getType().getNonReferenceType());
5107 bool UseTemporary = Entity.getType()->isReferenceType();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005108 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5109 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005110 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5111 Entity,
5112 Kind, move(Arg), *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005113 ConstructorInitRequiresZeroInit);
5114 break;
5115 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005116
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005117 case SK_UnwrapInitList:
5118 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5119 break;
5120
5121 case SK_RewrapInitList: {
5122 Expr *E = CurInit.take();
5123 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5124 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5125 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5126 ILE->setSyntacticForm(Syntactic);
5127 ILE->setType(E->getType());
5128 ILE->setValueKind(E->getValueKind());
5129 CurInit = S.Owned(ILE);
5130 break;
5131 }
5132
Sebastian Redl10f04a62011-12-22 14:44:04 +00005133 case SK_ConstructorInitialization:
5134 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5135 *Step,
5136 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005137 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005138
Douglas Gregor71d17402009-12-15 00:01:57 +00005139 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005140 step_iterator NextStep = Step;
5141 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005142 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005143 NextStep->Kind == SK_ConstructorInitialization) {
5144 // The need for zero-initialization is recorded directly into
5145 // the call to the object's constructor within the next step.
5146 ConstructorInitRequiresZeroInit = true;
5147 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5148 S.getLangOptions().CPlusPlus &&
5149 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005150 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5151 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005152 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005153 Kind.getRange().getBegin());
5154
5155 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5156 TSInfo->getType().getNonLValueExprType(S.Context),
5157 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005158 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005159 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005160 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005161 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005162 break;
5163 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005164
5165 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005166 QualType SourceType = CurInit.get()->getType();
5167 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005168 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005169 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5170 if (Result.isInvalid())
5171 return ExprError();
5172 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00005173
5174 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005175 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00005176 if (ConvTy != Sema::Compatible &&
5177 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005178 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005179 == Sema::Compatible)
5180 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005181 if (CurInitExprRes.isInvalid())
5182 return ExprError();
5183 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00005184
Douglas Gregora41a8c52010-04-22 00:20:18 +00005185 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005186 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5187 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005188 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005189 getAssignmentAction(Entity),
5190 &Complained)) {
5191 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005192 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005193 } else if (Complained)
5194 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005195 break;
5196 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005197
5198 case SK_StringInit: {
5199 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005200 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005201 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005202 break;
5203 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005204
5205 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005206 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005207 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005208 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005209 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005210
5211 case SK_ArrayInit:
5212 // Okay: we checked everything before creating this step. Note that
5213 // this is a GNU extension.
5214 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005215 << Step->Type << CurInit.get()->getType()
5216 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005217
5218 // If the destination type is an incomplete array type, update the
5219 // type accordingly.
5220 if (ResultType) {
5221 if (const IncompleteArrayType *IncompleteDest
5222 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5223 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005224 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005225 *ResultType = S.Context.getConstantArrayType(
5226 IncompleteDest->getElementType(),
5227 ConstantSource->getSize(),
5228 ArrayType::Normal, 0);
5229 }
5230 }
5231 }
John McCallf85e1932011-06-15 23:02:42 +00005232 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005233
Richard Smith0f163e92012-02-15 22:38:09 +00005234 case SK_ParenthesizedArrayInit:
5235 // Okay: we checked everything before creating this step. Note that
5236 // this is a GNU extension.
5237 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5238 << CurInit.get()->getSourceRange();
5239 break;
5240
John McCallf85e1932011-06-15 23:02:42 +00005241 case SK_PassByIndirectCopyRestore:
5242 case SK_PassByIndirectRestore:
5243 checkIndirectCopyRestoreSource(S, CurInit.get());
5244 CurInit = S.Owned(new (S.Context)
5245 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5246 Step->Kind == SK_PassByIndirectCopyRestore));
5247 break;
5248
5249 case SK_ProduceObjCObject:
5250 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005251 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005252 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005253 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005254
5255 case SK_StdInitializerList: {
5256 QualType Dest = Step->Type;
5257 QualType E;
5258 bool Success = S.isStdInitializerList(Dest, &E);
5259 (void)Success;
5260 assert(Success && "Destination type changed?");
5261 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5262 unsigned NumInits = ILE->getNumInits();
5263 SmallVector<Expr*, 16> Converted(NumInits);
5264 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5265 S.Context.getConstantArrayType(E,
5266 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5267 NumInits),
5268 ArrayType::Normal, 0));
5269 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5270 0, HiddenArray);
5271 for (unsigned i = 0; i < NumInits; ++i) {
5272 Element.setElementIndex(i);
5273 ExprResult Init = S.Owned(ILE->getInit(i));
5274 ExprResult Res = S.PerformCopyInitialization(Element,
5275 Init.get()->getExprLoc(),
5276 Init);
5277 assert(!Res.isInvalid() && "Result changed since try phase.");
5278 Converted[i] = Res.take();
5279 }
5280 InitListExpr *Semantic = new (S.Context)
5281 InitListExpr(S.Context, ILE->getLBraceLoc(),
5282 Converted.data(), NumInits, ILE->getRBraceLoc());
5283 Semantic->setSyntacticForm(ILE);
5284 Semantic->setType(Dest);
5285 CurInit = S.Owned(Semantic);
5286 break;
5287 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005288 }
5289 }
John McCall15d7d122010-11-11 03:21:53 +00005290
5291 // Diagnose non-fatal problems with the completed initialization.
5292 if (Entity.getKind() == InitializedEntity::EK_Member &&
5293 cast<FieldDecl>(Entity.getDecl())->isBitField())
5294 S.CheckBitFieldInitialization(Kind.getLocation(),
5295 cast<FieldDecl>(Entity.getDecl()),
5296 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005297
Douglas Gregor20093b42009-12-09 23:02:17 +00005298 return move(CurInit);
5299}
5300
Douglas Gregore4e68d42012-02-15 19:33:52 +00005301/// \brief Provide some notes that detail why a function was implicitly
5302/// deleted.
5303static void diagnoseImplicitlyDeletedFunction(Sema &S, CXXMethodDecl *Method) {
5304 // FIXME: This is a work in progress. It should dig deeper to figure out
5305 // why the function was deleted (e.g., because one of its members doesn't
5306 // have a copy constructor, for the copy-constructor case).
5307 if (!Method->isImplicit()) {
5308 S.Diag(Method->getLocation(), diag::note_callee_decl)
5309 << Method->getDeclName();
5310 }
5311
5312 if (Method->getParent()->isLambda()) {
5313 S.Diag(Method->getParent()->getLocation(), diag::note_lambda_decl);
5314 return;
5315 }
5316
5317 S.Diag(Method->getParent()->getLocation(), diag::note_defined_here)
5318 << Method->getParent();
5319}
5320
Douglas Gregor20093b42009-12-09 23:02:17 +00005321//===----------------------------------------------------------------------===//
5322// Diagnose initialization failures
5323//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005324bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005325 const InitializedEntity &Entity,
5326 const InitializationKind &Kind,
5327 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005328 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005329 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005330
Douglas Gregord6542d82009-12-22 15:35:07 +00005331 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005332 switch (Failure) {
5333 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005334 // FIXME: Customize for the initialized entity?
5335 if (NumArgs == 0)
5336 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5337 << DestType.getNonReferenceType();
5338 else // FIXME: diagnostic below could be better!
5339 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5340 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005341 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005342
Douglas Gregor20093b42009-12-09 23:02:17 +00005343 case FK_ArrayNeedsInitList:
5344 case FK_ArrayNeedsInitListOrStringLiteral:
5345 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5346 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5347 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005348
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005349 case FK_ArrayTypeMismatch:
5350 case FK_NonConstantArrayInit:
5351 S.Diag(Kind.getLocation(),
5352 (Failure == FK_ArrayTypeMismatch
5353 ? diag::err_array_init_different_type
5354 : diag::err_array_init_non_constant_array))
5355 << DestType.getNonReferenceType()
5356 << Args[0]->getType()
5357 << Args[0]->getSourceRange();
5358 break;
5359
John McCall73076432012-01-05 00:13:19 +00005360 case FK_VariableLengthArrayHasInitializer:
5361 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5362 << Args[0]->getSourceRange();
5363 break;
5364
John McCall6bb80172010-03-30 21:47:33 +00005365 case FK_AddressOfOverloadFailed: {
5366 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005367 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005368 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005369 true,
5370 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005371 break;
John McCall6bb80172010-03-30 21:47:33 +00005372 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005373
Douglas Gregor20093b42009-12-09 23:02:17 +00005374 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005375 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005376 switch (FailedOverloadResult) {
5377 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005378 if (Failure == FK_UserConversionOverloadFailed)
5379 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5380 << Args[0]->getType() << DestType
5381 << Args[0]->getSourceRange();
5382 else
5383 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5384 << DestType << Args[0]->getType()
5385 << Args[0]->getSourceRange();
5386
John McCall120d63c2010-08-24 20:38:10 +00005387 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005388 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005389
Douglas Gregor20093b42009-12-09 23:02:17 +00005390 case OR_No_Viable_Function:
5391 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5392 << Args[0]->getType() << DestType.getNonReferenceType()
5393 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00005394 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005395 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005396
Douglas Gregor20093b42009-12-09 23:02:17 +00005397 case OR_Deleted: {
5398 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5399 << Args[0]->getType() << DestType.getNonReferenceType()
5400 << Args[0]->getSourceRange();
5401 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005402 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005403 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5404 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005405 if (Ovl == OR_Deleted) {
5406 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005407 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00005408 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005409 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005410 }
5411 break;
5412 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005413
Douglas Gregor20093b42009-12-09 23:02:17 +00005414 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005415 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005416 }
5417 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005418
Douglas Gregor20093b42009-12-09 23:02:17 +00005419 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005420 if (isa<InitListExpr>(Args[0])) {
5421 S.Diag(Kind.getLocation(),
5422 diag::err_lvalue_reference_bind_to_initlist)
5423 << DestType.getNonReferenceType().isVolatileQualified()
5424 << DestType.getNonReferenceType()
5425 << Args[0]->getSourceRange();
5426 break;
5427 }
5428 // Intentional fallthrough
5429
Douglas Gregor20093b42009-12-09 23:02:17 +00005430 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005431 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005432 Failure == FK_NonConstLValueReferenceBindingToTemporary
5433 ? diag::err_lvalue_reference_bind_to_temporary
5434 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005435 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005436 << DestType.getNonReferenceType()
5437 << Args[0]->getType()
5438 << Args[0]->getSourceRange();
5439 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005440
Douglas Gregor20093b42009-12-09 23:02:17 +00005441 case FK_RValueReferenceBindingToLValue:
5442 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005443 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005444 << Args[0]->getSourceRange();
5445 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005446
Douglas Gregor20093b42009-12-09 23:02:17 +00005447 case FK_ReferenceInitDropsQualifiers:
5448 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5449 << DestType.getNonReferenceType()
5450 << Args[0]->getType()
5451 << Args[0]->getSourceRange();
5452 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005453
Douglas Gregor20093b42009-12-09 23:02:17 +00005454 case FK_ReferenceInitFailed:
5455 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5456 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005457 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005458 << Args[0]->getType()
5459 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005460 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5461 Args[0]->getType()->isObjCObjectPointerType())
5462 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005463 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005464
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005465 case FK_ConversionFailed: {
5466 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005467 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005468 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005469 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005470 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005471 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005472 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005473 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5474 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005475 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5476 Args[0]->getType()->isObjCObjectPointerType())
5477 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005478 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005479 }
John Wiegley429bb272011-04-08 18:41:53 +00005480
5481 case FK_ConversionFromPropertyFailed:
5482 // No-op. This error has already been reported.
5483 break;
5484
Douglas Gregord87b61f2009-12-10 17:56:55 +00005485 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005486 SourceRange R;
5487
5488 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005489 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005490 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005491 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005492 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005493
Douglas Gregor19311e72010-09-08 21:40:08 +00005494 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5495 if (Kind.isCStyleOrFunctionalCast())
5496 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5497 << R;
5498 else
5499 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5500 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005501 break;
5502 }
5503
5504 case FK_ReferenceBindingToInitList:
5505 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5506 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5507 break;
5508
5509 case FK_InitListBadDestinationType:
5510 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5511 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5512 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005513
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005514 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005515 case FK_ConstructorOverloadFailed: {
5516 SourceRange ArgsRange;
5517 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005518 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005519 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005520
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005521 if (Failure == FK_ListConstructorOverloadFailed) {
5522 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5523 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5524 Args = InitList->getInits();
5525 NumArgs = InitList->getNumInits();
5526 }
5527
Douglas Gregor51c56d62009-12-14 20:49:26 +00005528 // FIXME: Using "DestType" for the entity we're printing is probably
5529 // bad.
5530 switch (FailedOverloadResult) {
5531 case OR_Ambiguous:
5532 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5533 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005534 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5535 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005536 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005537
Douglas Gregor51c56d62009-12-14 20:49:26 +00005538 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005539 if (Kind.getKind() == InitializationKind::IK_Default &&
5540 (Entity.getKind() == InitializedEntity::EK_Base ||
5541 Entity.getKind() == InitializedEntity::EK_Member) &&
5542 isa<CXXConstructorDecl>(S.CurContext)) {
5543 // This is implicit default initialization of a member or
5544 // base within a constructor. If no viable function was
5545 // found, notify the user that she needs to explicitly
5546 // initialize this base/member.
5547 CXXConstructorDecl *Constructor
5548 = cast<CXXConstructorDecl>(S.CurContext);
5549 if (Entity.getKind() == InitializedEntity::EK_Base) {
5550 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5551 << Constructor->isImplicit()
5552 << S.Context.getTypeDeclType(Constructor->getParent())
5553 << /*base=*/0
5554 << Entity.getType();
5555
5556 RecordDecl *BaseDecl
5557 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5558 ->getDecl();
5559 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5560 << S.Context.getTagDeclType(BaseDecl);
5561 } else {
5562 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5563 << Constructor->isImplicit()
5564 << S.Context.getTypeDeclType(Constructor->getParent())
5565 << /*member=*/1
5566 << Entity.getName();
5567 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5568
5569 if (const RecordType *Record
5570 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005571 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005572 diag::note_previous_decl)
5573 << S.Context.getTagDeclType(Record->getDecl());
5574 }
5575 break;
5576 }
5577
Douglas Gregor51c56d62009-12-14 20:49:26 +00005578 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5579 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005580 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005581 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005582
Douglas Gregor51c56d62009-12-14 20:49:26 +00005583 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00005584 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005585 OverloadingResult Ovl
5586 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00005587 if (Ovl != OR_Deleted) {
5588 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5589 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005590 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00005591 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005592 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00005593
5594 // If this is a defaulted or implicitly-declared function, then
5595 // it was implicitly deleted. Make it clear that the deletion was
5596 // implicit.
5597 if (S.isImplicitlyDeleted(Best->Function)) {
5598 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
5599 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
5600 << DestType << ArgsRange;
5601
5602 diagnoseImplicitlyDeletedFunction(S,
5603 cast<CXXMethodDecl>(Best->Function));
5604 break;
5605 }
5606
5607 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5608 << true << DestType << ArgsRange;
5609 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
5610 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005611 break;
5612 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005613
Douglas Gregor51c56d62009-12-14 20:49:26 +00005614 case OR_Success:
5615 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00005616 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005617 }
David Blaikie9fdefb32012-01-17 08:24:58 +00005618 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005619
Douglas Gregor99a2e602009-12-16 01:38:02 +00005620 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005621 if (Entity.getKind() == InitializedEntity::EK_Member &&
5622 isa<CXXConstructorDecl>(S.CurContext)) {
5623 // This is implicit default-initialization of a const member in
5624 // a constructor. Complain that it needs to be explicitly
5625 // initialized.
5626 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5627 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5628 << Constructor->isImplicit()
5629 << S.Context.getTypeDeclType(Constructor->getParent())
5630 << /*const=*/1
5631 << Entity.getName();
5632 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5633 << Entity.getName();
5634 } else {
5635 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5636 << DestType << (bool)DestType->getAs<RecordType>();
5637 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005639
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005640 case FK_Incomplete:
5641 S.RequireCompleteType(Kind.getLocation(), DestType,
5642 diag::err_init_incomplete_type);
5643 break;
5644
Sebastian Redl14b0c192011-09-24 17:48:00 +00005645 case FK_ListInitializationFailed: {
5646 // Run the init list checker again to emit diagnostics.
5647 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5648 QualType DestType = Entity.getType();
5649 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005650 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005651 Kind.getKind() != InitializationKind::IK_DirectList ||
Sebastian Redlc2235182011-10-16 18:19:28 +00005652 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005653 assert(DiagnoseInitList.HadError() &&
5654 "Inconsistent init list check result.");
5655 break;
5656 }
John McCall5acb0c92011-10-17 18:40:02 +00005657
5658 case FK_PlaceholderType: {
5659 // FIXME: Already diagnosed!
5660 break;
5661 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00005662
5663 case FK_InitListElementCopyFailure: {
5664 // Try to perform all copies again.
5665 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5666 unsigned NumInits = InitList->getNumInits();
5667 QualType DestType = Entity.getType();
5668 QualType E;
5669 bool Success = S.isStdInitializerList(DestType, &E);
5670 (void)Success;
5671 assert(Success && "Where did the std::initializer_list go?");
5672 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5673 S.Context.getConstantArrayType(E,
5674 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5675 NumInits),
5676 ArrayType::Normal, 0));
5677 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5678 0, HiddenArray);
5679 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5680 // where the init list type is wrong, e.g.
5681 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5682 // FIXME: Emit a note if we hit the limit?
5683 int ErrorCount = 0;
5684 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5685 Element.setElementIndex(i);
5686 ExprResult Init = S.Owned(InitList->getInit(i));
5687 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5688 .isInvalid())
5689 ++ErrorCount;
5690 }
5691 break;
5692 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005694
Douglas Gregora41a8c52010-04-22 00:20:18 +00005695 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005696 return true;
5697}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005698
Chris Lattner5f9e2722011-07-23 10:55:15 +00005699void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005700 switch (SequenceKind) {
5701 case FailedSequence: {
5702 OS << "Failed sequence: ";
5703 switch (Failure) {
5704 case FK_TooManyInitsForReference:
5705 OS << "too many initializers for reference";
5706 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005707
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005708 case FK_ArrayNeedsInitList:
5709 OS << "array requires initializer list";
5710 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005711
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005712 case FK_ArrayNeedsInitListOrStringLiteral:
5713 OS << "array requires initializer list or string literal";
5714 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005715
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005716 case FK_ArrayTypeMismatch:
5717 OS << "array type mismatch";
5718 break;
5719
5720 case FK_NonConstantArrayInit:
5721 OS << "non-constant array initializer";
5722 break;
5723
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005724 case FK_AddressOfOverloadFailed:
5725 OS << "address of overloaded function failed";
5726 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005727
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005728 case FK_ReferenceInitOverloadFailed:
5729 OS << "overload resolution for reference initialization failed";
5730 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005731
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005732 case FK_NonConstLValueReferenceBindingToTemporary:
5733 OS << "non-const lvalue reference bound to temporary";
5734 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005735
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005736 case FK_NonConstLValueReferenceBindingToUnrelated:
5737 OS << "non-const lvalue reference bound to unrelated type";
5738 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005739
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005740 case FK_RValueReferenceBindingToLValue:
5741 OS << "rvalue reference bound to an lvalue";
5742 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005743
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005744 case FK_ReferenceInitDropsQualifiers:
5745 OS << "reference initialization drops qualifiers";
5746 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005747
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005748 case FK_ReferenceInitFailed:
5749 OS << "reference initialization failed";
5750 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005752 case FK_ConversionFailed:
5753 OS << "conversion failed";
5754 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005755
John Wiegley429bb272011-04-08 18:41:53 +00005756 case FK_ConversionFromPropertyFailed:
5757 OS << "conversion from property failed";
5758 break;
5759
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005760 case FK_TooManyInitsForScalar:
5761 OS << "too many initializers for scalar";
5762 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005763
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005764 case FK_ReferenceBindingToInitList:
5765 OS << "referencing binding to initializer list";
5766 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005767
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005768 case FK_InitListBadDestinationType:
5769 OS << "initializer list for non-aggregate, non-scalar type";
5770 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005771
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005772 case FK_UserConversionOverloadFailed:
5773 OS << "overloading failed for user-defined conversion";
5774 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005775
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005776 case FK_ConstructorOverloadFailed:
5777 OS << "constructor overloading failed";
5778 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005779
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005780 case FK_DefaultInitOfConst:
5781 OS << "default initialization of a const variable";
5782 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005783
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005784 case FK_Incomplete:
5785 OS << "initialization of incomplete type";
5786 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005787
5788 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005789 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005790 break;
5791
John McCall73076432012-01-05 00:13:19 +00005792 case FK_VariableLengthArrayHasInitializer:
5793 OS << "variable length array has an initializer";
5794 break;
5795
John McCall5acb0c92011-10-17 18:40:02 +00005796 case FK_PlaceholderType:
5797 OS << "initializer expression isn't contextually valid";
5798 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005799
5800 case FK_ListConstructorOverloadFailed:
5801 OS << "list constructor overloading failed";
5802 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005803
5804 case FK_InitListElementCopyFailure:
5805 OS << "copy construction of initializer list element failed";
5806 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005807 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005808 OS << '\n';
5809 return;
5810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005811
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005812 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005813 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005814 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005815
Sebastian Redl7491c492011-06-05 13:59:11 +00005816 case NormalSequence:
5817 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005818 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005819 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005820
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005821 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5822 if (S != step_begin()) {
5823 OS << " -> ";
5824 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005825
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005826 switch (S->Kind) {
5827 case SK_ResolveAddressOfOverloadedFunction:
5828 OS << "resolve address of overloaded function";
5829 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005830
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005831 case SK_CastDerivedToBaseRValue:
5832 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5833 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005834
Sebastian Redl906082e2010-07-20 04:20:21 +00005835 case SK_CastDerivedToBaseXValue:
5836 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5837 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005838
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005839 case SK_CastDerivedToBaseLValue:
5840 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5841 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005842
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005843 case SK_BindReference:
5844 OS << "bind reference to lvalue";
5845 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005846
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005847 case SK_BindReferenceToTemporary:
5848 OS << "bind reference to a temporary";
5849 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005850
Douglas Gregor523d46a2010-04-18 07:40:54 +00005851 case SK_ExtraneousCopyToTemporary:
5852 OS << "extraneous C++03 copy to temporary";
5853 break;
5854
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005855 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005856 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005857 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005858
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005859 case SK_QualificationConversionRValue:
5860 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005861 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005862
Sebastian Redl906082e2010-07-20 04:20:21 +00005863 case SK_QualificationConversionXValue:
5864 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005865 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005866
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005867 case SK_QualificationConversionLValue:
5868 OS << "qualification conversion (lvalue)";
5869 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005870
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005871 case SK_ConversionSequence:
5872 OS << "implicit conversion sequence (";
5873 S->ICS->DebugPrint(); // FIXME: use OS
5874 OS << ")";
5875 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005876
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005877 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005878 OS << "list aggregate initialization";
5879 break;
5880
5881 case SK_ListConstructorCall:
5882 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005883 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005884
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005885 case SK_UnwrapInitList:
5886 OS << "unwrap reference initializer list";
5887 break;
5888
5889 case SK_RewrapInitList:
5890 OS << "rewrap reference initializer list";
5891 break;
5892
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005893 case SK_ConstructorInitialization:
5894 OS << "constructor initialization";
5895 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005896
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005897 case SK_ZeroInitialization:
5898 OS << "zero initialization";
5899 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005900
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005901 case SK_CAssignment:
5902 OS << "C assignment";
5903 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005904
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005905 case SK_StringInit:
5906 OS << "string initialization";
5907 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005908
5909 case SK_ObjCObjectConversion:
5910 OS << "Objective-C object conversion";
5911 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005912
5913 case SK_ArrayInit:
5914 OS << "array initialization";
5915 break;
John McCallf85e1932011-06-15 23:02:42 +00005916
Richard Smith0f163e92012-02-15 22:38:09 +00005917 case SK_ParenthesizedArrayInit:
5918 OS << "parenthesized array initialization";
5919 break;
5920
John McCallf85e1932011-06-15 23:02:42 +00005921 case SK_PassByIndirectCopyRestore:
5922 OS << "pass by indirect copy and restore";
5923 break;
5924
5925 case SK_PassByIndirectRestore:
5926 OS << "pass by indirect restore";
5927 break;
5928
5929 case SK_ProduceObjCObject:
5930 OS << "Objective-C object retension";
5931 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005932
5933 case SK_StdInitializerList:
5934 OS << "std::initializer_list from initializer list";
5935 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005936 }
5937 }
5938}
5939
5940void InitializationSequence::dump() const {
5941 dump(llvm::errs());
5942}
5943
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005944static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
5945 QualType EntityType,
5946 const Expr *PreInit,
5947 const Expr *PostInit) {
5948 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
5949 return;
5950
5951 // A narrowing conversion can only appear as the final implicit conversion in
5952 // an initialization sequence.
5953 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
5954 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
5955 return;
5956
5957 const ImplicitConversionSequence &ICS = *LastStep.ICS;
5958 const StandardConversionSequence *SCS = 0;
5959 switch (ICS.getKind()) {
5960 case ImplicitConversionSequence::StandardConversion:
5961 SCS = &ICS.Standard;
5962 break;
5963 case ImplicitConversionSequence::UserDefinedConversion:
5964 SCS = &ICS.UserDefined.After;
5965 break;
5966 case ImplicitConversionSequence::AmbiguousConversion:
5967 case ImplicitConversionSequence::EllipsisConversion:
5968 case ImplicitConversionSequence::BadConversion:
5969 return;
5970 }
5971
5972 // Determine the type prior to the narrowing conversion. If a conversion
5973 // operator was used, this may be different from both the type of the entity
5974 // and of the pre-initialization expression.
5975 QualType PreNarrowingType = PreInit->getType();
5976 if (Seq.step_begin() + 1 != Seq.step_end())
5977 PreNarrowingType = Seq.step_end()[-2].Type;
5978
5979 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
5980 APValue ConstantValue;
Richard Smith8ef7b202012-01-18 23:55:52 +00005981 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005982 case NK_Not_Narrowing:
5983 // No narrowing occurred.
5984 return;
5985
5986 case NK_Type_Narrowing:
5987 // This was a floating-to-integer conversion, which is always considered a
5988 // narrowing conversion even if the value is a constant and can be
5989 // represented exactly as an integer.
5990 S.Diag(PostInit->getLocStart(),
Douglas Gregorf3c82c52012-01-23 15:29:33 +00005991 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
5992 diag::warn_init_list_type_narrowing
5993 : S.isSFINAEContext()?
5994 diag::err_init_list_type_narrowing_sfinae
5995 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00005996 << PostInit->getSourceRange()
5997 << PreNarrowingType.getLocalUnqualifiedType()
5998 << EntityType.getLocalUnqualifiedType();
5999 break;
6000
6001 case NK_Constant_Narrowing:
6002 // A constant value was narrowed.
6003 S.Diag(PostInit->getLocStart(),
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006004 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
6005 diag::warn_init_list_constant_narrowing
6006 : S.isSFINAEContext()?
6007 diag::err_init_list_constant_narrowing_sfinae
6008 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006009 << PostInit->getSourceRange()
Richard Smith08d6e032011-12-16 19:06:07 +00006010 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006011 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006012 break;
6013
6014 case NK_Variable_Narrowing:
6015 // A variable's value may have been narrowed.
6016 S.Diag(PostInit->getLocStart(),
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006017 S.getLangOptions().MicrosoftExt || !S.getLangOptions().CPlusPlus0x?
6018 diag::warn_init_list_variable_narrowing
6019 : S.isSFINAEContext()?
6020 diag::err_init_list_variable_narrowing_sfinae
6021 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006022 << PostInit->getSourceRange()
6023 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006024 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006025 break;
6026 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006027
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006028 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006029 llvm::raw_svector_ostream OS(StaticCast);
6030 OS << "static_cast<";
6031 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6032 // It's important to use the typedef's name if there is one so that the
6033 // fixit doesn't break code using types like int64_t.
6034 //
6035 // FIXME: This will break if the typedef requires qualification. But
6036 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006037 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006038 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6039 OS << BT->getName(S.getLangOptions());
6040 else {
6041 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6042 // with a broken cast.
6043 return;
6044 }
6045 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006046 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6047 << PostInit->getSourceRange()
6048 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006049 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006050 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006051}
6052
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006053//===----------------------------------------------------------------------===//
6054// Initialization helper functions
6055//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006056bool
6057Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6058 ExprResult Init) {
6059 if (Init.isInvalid())
6060 return false;
6061
6062 Expr *InitE = Init.get();
6063 assert(InitE && "No initialization expression");
6064
6065 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
6066 SourceLocation());
6067 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00006068 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006069}
6070
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006071ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006072Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6073 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006074 ExprResult Init,
6075 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006076 if (Init.isInvalid())
6077 return ExprError();
6078
John McCall15d7d122010-11-11 03:21:53 +00006079 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006080 assert(InitE && "No initialization expression?");
6081
6082 if (EqualLoc.isInvalid())
6083 EqualLoc = InitE->getLocStart();
6084
6085 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6086 EqualLoc);
6087 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6088 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006089
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006090 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6091
6092 if (!Result.isInvalid() && TopLevelOfInitList)
6093 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6094 InitE, Result.get());
6095
6096 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006097}