blob: c9b1a694d0135b7e29dd2a08711a2e05363df341 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Ted Kremenek6eb25622012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenek6eb25622012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenek6eb25622012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000096 else
Ted Kremenek6eb25622012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenek6eb25622012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith852265f2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith6f1e2c62012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith852265f2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose28cd12f2012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
146/// variable or function with internal linkage.
147///
148/// This also applies to anonymous-namespaced objects, which are effectively
149/// internal.
150/// This is only a warning because we used to silently accept this code, but
151/// most likely it will not do what the user intends.
152static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
153 const NamedDecl *D,
154 SourceLocation Loc) {
155 // C11 6.7.4p3: An inline definition of a function with external linkage...
156 // shall not contain a reference to an identifier with internal linkage.
157 // C++11 [basic.def.odr]p6: ...in each definition of D, corresponding names,
158 // looked up according to 3.4, shall refer to an entity defined within the
159 // definition of D, or shall refer to the same entity, after overload
160 // resolution (13.3) and after matching of partial template specialization
161 // (14.8.3), except that a name can refer to a const object with internal or
162 // no linkage if the object has the same literal type in all definitions of
163 // D, and the object is initialized with a constant expression (5.19), and
164 // the value (but not the address) of the object is used, and the object has
165 // the same value in all definitions of D; ...
166
167 // Check if this is an inlined function or method.
168 FunctionDecl *Current = S.getCurFunctionDecl();
169 if (!Current)
170 return;
171 if (!Current->isInlined())
172 return;
173 if (Current->getLinkage() != ExternalLinkage)
174 return;
175
176 // Check if the decl has internal linkage.
177 Linkage UsedLinkage = D->getLinkage();
178 switch (UsedLinkage) {
179 case NoLinkage:
180 return;
181 case InternalLinkage:
182 case UniqueExternalLinkage:
183 break;
184 case ExternalLinkage:
185 return;
186 }
187
188 // Check C++'s exception for const variables. This is in the standard
189 // because in C++ const variables have internal linkage unless
190 // explicitly declared extern.
191 // Note that we don't do any of the cross-TU checks, and this code isn't
192 // even particularly careful about checking if the variable "has the
193 // same value in all definitions" of the inline function. It just does a
194 // sanity check to make sure there is an initializer at all.
195 // FIXME: We should still be checking to see if we're using a constant
196 // as a glvalue anywhere, but we don't have the necessary information to
197 // do that here, and as long as this is a warning and not a hard error
198 // it's not appropriate to change the semantics of the program (i.e.
199 // by having BuildDeclRefExpr use VK_RValue for constants like these).
200 const VarDecl *VD = dyn_cast<VarDecl>(D);
201 if (VD && S.getLangOpts().CPlusPlus)
202 if (VD->getType().isConstant(S.getASTContext()) && VD->getAnyInitializer())
203 return;
204
205 // Don't warn unless -pedantic is on if the inline function is in the main
206 // source file. These functions will most likely not be inlined into another
207 // translation unit, so they're effectively internal.
208 bool IsInMainFile = S.getSourceManager().isFromMainFile(Loc);
209 S.Diag(Loc, IsInMainFile ? diag::ext_internal_in_extern_inline
210 : diag::warn_internal_in_extern_inline)
211 << (bool)VD
212 << D
213 << (UsedLinkage == UniqueExternalLinkage)
214 << isa<CXXMethodDecl>(Current);
215
216 // Suggest "static" on the inline function, if possible.
217 if (!isa<CXXMethodDecl>(Current) &&
218 !hasAnyExplicitStorageClass(Current)) {
219 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
220 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
221 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
222 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
223 }
224
225 S.Diag(D->getCanonicalDecl()->getLocation(),
226 diag::note_internal_decl_declared_here)
227 << D;
228}
229
Douglas Gregor171c45a2009-02-18 21:56:37 +0000230/// \brief Determine whether the use of this declaration is valid, and
231/// emit any corresponding diagnostics.
232///
233/// This routine diagnoses various problems with referencing
234/// declarations that can occur when using a declaration. For example,
235/// it might warn if a deprecated or unavailable declaration is being
236/// used, or produce an error (and return true) if a C++0x deleted
237/// function is being used.
238///
239/// \returns true if there was an error (this declaration cannot be
240/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000241///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000242bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000243 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000244 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000245 // If there were any diagnostics suppressed by template argument deduction,
246 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000247 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000248 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
249 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000250 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000251 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
252 Diag(Suppressed[I].first, Suppressed[I].second);
253
254 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000255 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000256 // entry from the table, because we want to avoid ever emitting these
257 // diagnostics again.
258 Suppressed.clear();
259 }
260 }
261
Richard Smith30482bc2011-02-20 03:19:35 +0000262 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000263 if (ParsingInitForAutoVars.count(D)) {
264 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << D->getDeclName();
266 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000267 }
268
Douglas Gregor171c45a2009-02-18 21:56:37 +0000269 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000271 if (FD->isDeleted()) {
272 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000273 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000274 return true;
275 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000276 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000277 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000278
Anders Carlsson73067a02010-10-22 23:37:08 +0000279 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000280 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000281 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose2684c682012-06-15 18:19:48 +0000282
Jordan Rose28cd12f2012-06-18 22:09:19 +0000283 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000284
Douglas Gregor171c45a2009-02-18 21:56:37 +0000285 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000286}
287
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000288/// \brief Retrieve the message suffix that should be added to a
289/// diagnostic complaining about the given function being deleted or
290/// unavailable.
291std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
292 // FIXME: C++0x implicitly-deleted special member functions could be
293 // detected here so that we could improve diagnostics to say, e.g.,
294 // "base class 'A' had a deleted copy constructor".
295 if (FD->isDeleted())
296 return std::string();
297
298 std::string Message;
299 if (FD->getAvailability(&Message))
300 return ": " + Message;
301
302 return std::string();
303}
304
John McCallb46f2872011-09-09 07:56:05 +0000305/// DiagnoseSentinelCalls - This routine checks whether a call or
306/// message-send is to a declaration with the sentinel attribute, and
307/// if so, it checks that the requirements of the sentinel are
308/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000309void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000310 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000311 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000312 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000313 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000314
John McCallb46f2872011-09-09 07:56:05 +0000315 // The number of formal parameters of the declaration.
316 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000317
John McCallb46f2872011-09-09 07:56:05 +0000318 // The kind of declaration. This is also an index into a %select in
319 // the diagnostic.
320 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
321
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000322 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000323 numFormalParams = MD->param_size();
324 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000325 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000326 numFormalParams = FD->param_size();
327 calleeType = CT_Function;
328 } else if (isa<VarDecl>(D)) {
329 QualType type = cast<ValueDecl>(D)->getType();
330 const FunctionType *fn = 0;
331 if (const PointerType *ptr = type->getAs<PointerType>()) {
332 fn = ptr->getPointeeType()->getAs<FunctionType>();
333 if (!fn) return;
334 calleeType = CT_Function;
335 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
336 fn = ptr->getPointeeType()->castAs<FunctionType>();
337 calleeType = CT_Block;
338 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000339 return;
John McCallb46f2872011-09-09 07:56:05 +0000340 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000341
John McCallb46f2872011-09-09 07:56:05 +0000342 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
343 numFormalParams = proto->getNumArgs();
344 } else {
345 numFormalParams = 0;
346 }
347 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000348 return;
349 }
John McCallb46f2872011-09-09 07:56:05 +0000350
351 // "nullPos" is the number of formal parameters at the end which
352 // effectively count as part of the variadic arguments. This is
353 // useful if you would prefer to not have *any* formal parameters,
354 // but the language forces you to have at least one.
355 unsigned nullPos = attr->getNullPos();
356 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
357 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
358
359 // The number of arguments which should follow the sentinel.
360 unsigned numArgsAfterSentinel = attr->getSentinel();
361
362 // If there aren't enough arguments for all the formal parameters,
363 // the sentinel, and the args after the sentinel, complain.
364 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000365 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000366 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000367 return;
368 }
John McCallb46f2872011-09-09 07:56:05 +0000369
370 // Otherwise, find the sentinel expression.
371 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000372 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000373 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000374 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000375
John McCallb46f2872011-09-09 07:56:05 +0000376 // Pick a reasonable string to insert. Optimistically use 'nil' or
377 // 'NULL' if those are actually defined in the context. Only use
378 // 'nil' for ObjC methods, where it's much more likely that the
379 // variadic arguments form a list of object pointers.
380 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000381 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
382 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000383 if (calleeType == CT_Method &&
384 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000385 NullValue = "nil";
386 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
387 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000388 else
John McCallb46f2872011-09-09 07:56:05 +0000389 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000390
391 if (MissingNilLoc.isInvalid())
392 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
393 else
394 Diag(MissingNilLoc, diag::warn_missing_sentinel)
395 << calleeType
396 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000397 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000398}
399
Richard Trieuba63ce62011-09-09 01:45:06 +0000400SourceRange Sema::getExprRange(Expr *E) const {
401 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000402}
403
Chris Lattner513165e2008-07-25 21:10:04 +0000404//===----------------------------------------------------------------------===//
405// Standard Promotions and Conversions
406//===----------------------------------------------------------------------===//
407
Chris Lattner513165e2008-07-25 21:10:04 +0000408/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000409ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000410 // Handle any placeholder expressions which made it here.
411 if (E->getType()->isPlaceholderType()) {
412 ExprResult result = CheckPlaceholderExpr(E);
413 if (result.isInvalid()) return ExprError();
414 E = result.take();
415 }
416
Chris Lattner513165e2008-07-25 21:10:04 +0000417 QualType Ty = E->getType();
418 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
419
Chris Lattner513165e2008-07-25 21:10:04 +0000420 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000421 E = ImpCastExprToType(E, Context.getPointerType(Ty),
422 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000423 else if (Ty->isArrayType()) {
424 // In C90 mode, arrays only promote to pointers if the array expression is
425 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
426 // type 'array of type' is converted to an expression that has type 'pointer
427 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
428 // that has type 'array of type' ...". The relevant change is "an lvalue"
429 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000430 //
431 // C++ 4.2p1:
432 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
433 // T" can be converted to an rvalue of type "pointer to T".
434 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000435 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000436 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
437 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000438 }
John Wiegley01296292011-04-08 18:41:53 +0000439 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000440}
441
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000442static void CheckForNullPointerDereference(Sema &S, Expr *E) {
443 // Check to see if we are dereferencing a null pointer. If so,
444 // and if not volatile-qualified, this is undefined behavior that the
445 // optimizer will delete, so warn about it. People sometimes try to use this
446 // to get a deterministic trap and are surprised by clang's behavior. This
447 // only handles the pattern "*null", which is a very syntactic check.
448 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
449 if (UO->getOpcode() == UO_Deref &&
450 UO->getSubExpr()->IgnoreParenCasts()->
451 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
452 !UO->getType().isVolatileQualified()) {
453 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
454 S.PDiag(diag::warn_indirection_through_null)
455 << UO->getSubExpr()->getSourceRange());
456 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
457 S.PDiag(diag::note_indirection_through_null));
458 }
459}
460
John Wiegley01296292011-04-08 18:41:53 +0000461ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000462 // Handle any placeholder expressions which made it here.
463 if (E->getType()->isPlaceholderType()) {
464 ExprResult result = CheckPlaceholderExpr(E);
465 if (result.isInvalid()) return ExprError();
466 E = result.take();
467 }
468
John McCallf3735e02010-12-01 04:43:34 +0000469 // C++ [conv.lval]p1:
470 // A glvalue of a non-function, non-array type T can be
471 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000472 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000473
John McCall27584242010-12-06 20:48:59 +0000474 QualType T = E->getType();
475 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000476
John McCall27584242010-12-06 20:48:59 +0000477 // We don't want to throw lvalue-to-rvalue casts on top of
478 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000479 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000480 (E->getType() == Context.OverloadTy ||
481 T->isDependentType() ||
482 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000483 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000484
485 // The C standard is actually really unclear on this point, and
486 // DR106 tells us what the result should be but not why. It's
487 // generally best to say that void types just doesn't undergo
488 // lvalue-to-rvalue at all. Note that expressions of unqualified
489 // 'void' type are never l-values, but qualified void can be.
490 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000491 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000492
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000493 CheckForNullPointerDereference(*this, E);
494
John McCall27584242010-12-06 20:48:59 +0000495 // C++ [conv.lval]p1:
496 // [...] If T is a non-class type, the type of the prvalue is the
497 // cv-unqualified version of T. Otherwise, the type of the
498 // rvalue is T.
499 //
500 // C99 6.3.2.1p2:
501 // If the lvalue has qualified type, the value has the unqualified
502 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000503 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000504 if (T.hasQualifiers())
505 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000506
Eli Friedman3bda6b12012-02-02 23:15:15 +0000507 UpdateMarkingForLValueToRValue(E);
508
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000509 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
510 E, 0, VK_RValue));
511
Douglas Gregorc79862f2012-04-12 17:51:55 +0000512 // C11 6.3.2.1p2:
513 // ... if the lvalue has atomic type, the value has the non-atomic version
514 // of the type of the lvalue ...
515 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
516 T = Atomic->getValueType().getUnqualifiedType();
517 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
518 Res.get(), 0, VK_RValue));
519 }
520
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000521 return Res;
John McCall27584242010-12-06 20:48:59 +0000522}
523
John Wiegley01296292011-04-08 18:41:53 +0000524ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
525 ExprResult Res = DefaultFunctionArrayConversion(E);
526 if (Res.isInvalid())
527 return ExprError();
528 Res = DefaultLvalueConversion(Res.take());
529 if (Res.isInvalid())
530 return ExprError();
531 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000532}
533
534
Chris Lattner513165e2008-07-25 21:10:04 +0000535/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000536/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000537/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000538/// apply if the array is an argument to the sizeof or address (&) operators.
539/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000540ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000541 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000542 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
543 if (Res.isInvalid())
544 return Owned(E);
545 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000546
John McCallf3735e02010-12-01 04:43:34 +0000547 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000548 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000549
550 // Half FP is a bit different: it's a storage-only type, meaning that any
551 // "use" of it should be promoted to float.
552 if (Ty->isHalfType())
553 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
554
John McCallf3735e02010-12-01 04:43:34 +0000555 // Try to perform integral promotions if the object has a theoretically
556 // promotable type.
557 if (Ty->isIntegralOrUnscopedEnumerationType()) {
558 // C99 6.3.1.1p2:
559 //
560 // The following may be used in an expression wherever an int or
561 // unsigned int may be used:
562 // - an object or expression with an integer type whose integer
563 // conversion rank is less than or equal to the rank of int
564 // and unsigned int.
565 // - A bit-field of type _Bool, int, signed int, or unsigned int.
566 //
567 // If an int can represent all values of the original type, the
568 // value is converted to an int; otherwise, it is converted to an
569 // unsigned int. These are called the integer promotions. All
570 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000571
John McCallf3735e02010-12-01 04:43:34 +0000572 QualType PTy = Context.isPromotableBitField(E);
573 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
575 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000576 }
577 if (Ty->isPromotableIntegerType()) {
578 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000579 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
580 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000581 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000582 }
John Wiegley01296292011-04-08 18:41:53 +0000583 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000584}
585
Chris Lattner2ce500f2008-07-25 22:25:12 +0000586/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000587/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000588/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000589ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
590 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000591 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000592
John Wiegley01296292011-04-08 18:41:53 +0000593 ExprResult Res = UsualUnaryConversions(E);
594 if (Res.isInvalid())
595 return Owned(E);
596 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000597
Chris Lattner2ce500f2008-07-25 22:25:12 +0000598 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000599 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000600 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
601
John McCall4bb057d2011-08-27 22:06:17 +0000602 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000603 // promotion, even on class types, but note:
604 // C++11 [conv.lval]p2:
605 // When an lvalue-to-rvalue conversion occurs in an unevaluated
606 // operand or a subexpression thereof the value contained in the
607 // referenced object is not accessed. Otherwise, if the glvalue
608 // has a class type, the conversion copy-initializes a temporary
609 // of type T from the glvalue and the result of the conversion
610 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000611 // FIXME: add some way to gate this entire thing for correctness in
612 // potentially potentially evaluated contexts.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman05e28012012-01-17 02:13:45 +0000614 ExprEvalContexts.back().Context != Unevaluated) {
615 ExprResult Temp = PerformCopyInitialization(
616 InitializedEntity::InitializeTemporary(E->getType()),
617 E->getExprLoc(),
618 Owned(E));
619 if (Temp.isInvalid())
620 return ExprError();
621 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000622 }
623
John Wiegley01296292011-04-08 18:41:53 +0000624 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000625}
626
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000627/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
628/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000629/// interfaces passed by value.
630ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000631 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000632 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
633 // Strip the unbridged-cast placeholder expression off, if applicable.
634 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
635 (CT == VariadicMethod ||
636 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
637 E = stripARCUnbridgedCast(E);
638
639 // Otherwise, do normal placeholder checking.
640 } else {
641 ExprResult ExprRes = CheckPlaceholderExpr(E);
642 if (ExprRes.isInvalid())
643 return ExprError();
644 E = ExprRes.take();
645 }
646 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000647
John McCall4124c492011-10-17 18:40:02 +0000648 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000649 if (ExprRes.isInvalid())
650 return ExprError();
651 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000652
Douglas Gregor347e0f22011-05-21 19:26:31 +0000653 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000654 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000655 DiagRuntimeBehavior(E->getLocStart(), 0,
656 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
657 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000658 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000659
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000660 // Complain about passing non-POD types through varargs. However, don't
661 // perform this check for incomplete types, which we can get here when we're
662 // in an unevaluated context.
Benjamin Kramer6a0a2112012-04-28 10:00:42 +0000663 if (!E->getType()->isIncompleteType() &&
664 !E->getType().isCXX98PODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000665 // C++0x [expr.call]p7:
666 // Passing a potentially-evaluated argument of class type (Clause 9)
667 // having a non-trivial copy constructor, a non-trivial move constructor,
668 // or a non-trivial destructor, with no corresponding parameter,
669 // is conditionally-supported with implementation-defined semantics.
670 bool TrivialEnough = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000671 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000672 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
673 if (Record->hasTrivialCopyConstructor() &&
674 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000675 Record->hasTrivialDestructor()) {
676 DiagRuntimeBehavior(E->getLocStart(), 0,
677 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
678 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000679 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000680 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000681 }
682 }
John McCall31168b02011-06-15 23:02:42 +0000683
684 if (!TrivialEnough &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000685 getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000686 E->getType()->isObjCLifetimeType())
687 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000688
689 if (TrivialEnough) {
690 // Nothing to diagnose. This is okay.
691 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000692 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000693 << getLangOpts().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000694 << CT)) {
695 // Turn this into a trap.
696 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000697 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000698 UnqualifiedId Name;
699 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
700 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000701 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
702 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000703 if (TrapFn.isInvalid())
704 return ExprError();
705
706 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
707 MultiExprArg(), E->getLocEnd());
708 if (Call.isInvalid())
709 return ExprError();
710
711 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
712 Call.get(), E);
713 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000714 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000715 E = Comma.get();
716 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000717 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000718 // c++ rules are enforced elsewhere.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000719 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000720 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000721 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000722 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000723
John Wiegley01296292011-04-08 18:41:53 +0000724 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000725}
726
Richard Trieu7aa58f12011-09-02 20:58:51 +0000727/// \brief Converts an integer to complex float type. Helper function of
728/// UsualArithmeticConversions()
729///
730/// \return false if the integer expression is an integer type and is
731/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000732static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
733 ExprResult &ComplexExpr,
734 QualType IntTy,
735 QualType ComplexTy,
736 bool SkipCast) {
737 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
738 if (SkipCast) return false;
739 if (IntTy->isIntegerType()) {
740 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
741 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
742 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000743 CK_FloatingRealToComplex);
744 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000745 assert(IntTy->isComplexIntegerType());
746 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000747 CK_IntegralComplexToFloatingComplex);
748 }
749 return false;
750}
751
752/// \brief Takes two complex float types and converts them to the same type.
753/// Helper function of UsualArithmeticConversions()
754static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000755handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
756 ExprResult &RHS, QualType LHSType,
757 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000758 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000759 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760
761 if (order < 0) {
762 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000763 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000764 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
765 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000766 }
767 if (order > 0)
768 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000769 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
770 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771}
772
773/// \brief Converts otherExpr to complex float and promotes complexExpr if
774/// necessary. Helper function of UsualArithmeticConversions()
775static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000776 ExprResult &ComplexExpr,
777 ExprResult &OtherExpr,
778 QualType ComplexTy,
779 QualType OtherTy,
780 bool ConvertComplexExpr,
781 bool ConvertOtherExpr) {
782 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000783
784 // If just the complexExpr is complex, the otherExpr needs to be converted,
785 // and the complexExpr might need to be promoted.
786 if (order > 0) { // complexExpr is wider
787 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000788 if (ConvertOtherExpr) {
789 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
790 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
791 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000792 CK_FloatingRealToComplex);
793 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000794 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795 }
796
797 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000798 QualType result = (order == 0 ? ComplexTy :
799 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000800
801 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000802 if (ConvertOtherExpr)
803 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 CK_FloatingRealToComplex);
805
806 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000807 if (ConvertComplexExpr && order < 0)
808 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000809 CK_FloatingComplexCast);
810
811 return result;
812}
813
814/// \brief Handle arithmetic conversion with complex types. Helper function of
815/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000816static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
817 ExprResult &RHS, QualType LHSType,
818 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000819 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000820 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000821 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000822 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000823 return LHSType;
824 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000825 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000826 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000827
828 // This handles complex/complex, complex/float, or float/complex.
829 // When both operands are complex, the shorter operand is converted to the
830 // type of the longer, and that is the type of the result. This corresponds
831 // to what is done when combining two real floating-point operands.
832 // The fun begins when size promotion occur across type domains.
833 // From H&S 6.3.4: When one operand is complex and the other is a real
834 // floating-point type, the less precise type is converted, within it's
835 // real or complex domain, to the precision of the other type. For example,
836 // when combining a "long double" with a "double _Complex", the
837 // "double _Complex" is promoted to "long double _Complex".
838
Richard Trieu5065cdd2011-09-06 18:25:09 +0000839 bool LHSComplexFloat = LHSType->isComplexType();
840 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000841
842 // If both are complex, just cast to the more precise type.
843 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000844 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
845 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000846 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000847
848 // If only one operand is complex, promote it if necessary and convert the
849 // other operand to complex.
850 if (LHSComplexFloat)
851 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000852 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853 /*convertOtherExpr*/ true);
854
855 assert(RHSComplexFloat);
856 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000857 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000858 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000859}
860
861/// \brief Hande arithmetic conversion from integer to float. Helper function
862/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000863static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
864 ExprResult &IntExpr,
865 QualType FloatTy, QualType IntTy,
866 bool ConvertFloat, bool ConvertInt) {
867 if (IntTy->isIntegerType()) {
868 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000869 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000870 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000871 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000872 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000873 }
874
875 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000876 assert(IntTy->isComplexIntegerType());
877 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000878
879 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000880 if (ConvertInt)
881 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000882 CK_IntegralComplexToFloatingComplex);
883
884 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000885 if (ConvertFloat)
886 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000887 CK_FloatingRealToComplex);
888
889 return result;
890}
891
892/// \brief Handle arithmethic conversion with floating point types. Helper
893/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000894static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
895 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000896 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000897 bool LHSFloat = LHSType->isRealFloatingType();
898 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000899
900 // If we have two real floating types, convert the smaller operand
901 // to the bigger result.
902 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000903 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000904 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000905 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
906 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000907 }
908
909 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000910 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000911 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
912 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000913 }
914
915 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000916 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000917 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000918 /*convertInt=*/ true);
919 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000920 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000921 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000922 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000923}
924
925/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000926/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000927// FIXME: if the operands are (int, _Complex long), we currently
928// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000929static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
930 ExprResult &RHS, QualType LHSType,
931 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000932 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000933 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
934 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935
Richard Trieucfe3f212011-09-06 18:38:41 +0000936 if (LHSComplexInt && RHSComplexInt) {
937 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
938 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000939 assert(order && "inequal types with equal element ordering");
940 if (order > 0) {
941 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000942 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
943 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000944 }
945
Richard Trieuba63ce62011-09-09 01:45:06 +0000946 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000947 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
948 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000949 }
950
Richard Trieucfe3f212011-09-06 18:38:41 +0000951 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000952 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000953 // FIXME: This needs to take integer ranks into account
954 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
955 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000956 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
957 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000958 }
959
Richard Trieucfe3f212011-09-06 18:38:41 +0000960 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000961 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000962 // FIXME: This needs to take integer ranks into account
963 if (!IsCompAssign) {
964 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
965 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000966 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000967 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000968 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000969}
970
971/// \brief Handle integer arithmetic conversions. Helper function of
972/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000973static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
974 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000975 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000976 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000977 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
978 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
979 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
980 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000981 // Same signedness; use the higher-ranked type
982 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000983 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
984 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000985 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000986 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
987 return RHSType;
988 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000989 // The unsigned type has greater than or equal rank to the
990 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000991 if (RHSSigned) {
992 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
993 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000994 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000995 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
996 return RHSType;
997 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000998 // The two types are different widths; if we are here, that
999 // means the signed type is larger than the unsigned type, so
1000 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001001 if (LHSSigned) {
1002 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1003 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001004 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001005 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1006 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001007 } else {
1008 // The signed type is higher-ranked than the unsigned type,
1009 // but isn't actually any bigger (like unsigned int and long
1010 // on most 32-bit systems). Use the unsigned type corresponding
1011 // to the signed type.
1012 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001013 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1014 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001015 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001016 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001017 return result;
1018 }
1019}
1020
Chris Lattner513165e2008-07-25 21:10:04 +00001021/// UsualArithmeticConversions - Performs various conversions that are common to
1022/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001023/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001024/// responsible for emitting appropriate error diagnostics.
1025/// FIXME: verify the conversion rules for "complex int" are consistent with
1026/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001027QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001028 bool IsCompAssign) {
1029 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001030 LHS = UsualUnaryConversions(LHS.take());
1031 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001032 return QualType();
1033 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001034
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001035 RHS = UsualUnaryConversions(RHS.take());
1036 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001037 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001038
Mike Stump11289f42009-09-09 15:08:12 +00001039 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001040 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001041 QualType LHSType =
1042 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1043 QualType RHSType =
1044 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001045
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001046 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1047 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1048 LHSType = AtomicLHS->getValueType();
1049
Douglas Gregora11693b2008-11-12 17:17:38 +00001050 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001051 if (LHSType == RHSType)
1052 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001053
1054 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1055 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001056 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001057 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001058
John McCalld005ac92010-11-13 08:17:45 +00001059 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001060 QualType LHSUnpromotedType = LHSType;
1061 if (LHSType->isPromotableIntegerType())
1062 LHSType = Context.getPromotedIntegerType(LHSType);
1063 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001064 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001065 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001066 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001067 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001068
John McCalld005ac92010-11-13 08:17:45 +00001069 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001070 if (LHSType == RHSType)
1071 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001072
1073 // At this point, we have two different arithmetic types.
1074
1075 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001076 if (LHSType->isComplexType() || RHSType->isComplexType())
1077 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001078 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001079
1080 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001081 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1082 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001083 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001084
1085 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001086 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001087 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001088 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001089
1090 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001091 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001092 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001093}
1094
Chris Lattner513165e2008-07-25 21:10:04 +00001095//===----------------------------------------------------------------------===//
1096// Semantic Analysis for various Expression Types
1097//===----------------------------------------------------------------------===//
1098
1099
Peter Collingbourne91147592011-04-15 00:35:48 +00001100ExprResult
1101Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1102 SourceLocation DefaultLoc,
1103 SourceLocation RParenLoc,
1104 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001105 MultiTypeArg ArgTypes,
1106 MultiExprArg ArgExprs) {
1107 unsigned NumAssocs = ArgTypes.size();
1108 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001109
Richard Trieuba63ce62011-09-09 01:45:06 +00001110 ParsedType *ParsedTypes = ArgTypes.release();
1111 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +00001112
1113 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1114 for (unsigned i = 0; i < NumAssocs; ++i) {
1115 if (ParsedTypes[i])
1116 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1117 else
1118 Types[i] = 0;
1119 }
1120
1121 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1122 ControllingExpr, Types, Exprs,
1123 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001124 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001125 return ER;
1126}
1127
1128ExprResult
1129Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1130 SourceLocation DefaultLoc,
1131 SourceLocation RParenLoc,
1132 Expr *ControllingExpr,
1133 TypeSourceInfo **Types,
1134 Expr **Exprs,
1135 unsigned NumAssocs) {
1136 bool TypeErrorFound = false,
1137 IsResultDependent = ControllingExpr->isTypeDependent(),
1138 ContainsUnexpandedParameterPack
1139 = ControllingExpr->containsUnexpandedParameterPack();
1140
1141 for (unsigned i = 0; i < NumAssocs; ++i) {
1142 if (Exprs[i]->containsUnexpandedParameterPack())
1143 ContainsUnexpandedParameterPack = true;
1144
1145 if (Types[i]) {
1146 if (Types[i]->getType()->containsUnexpandedParameterPack())
1147 ContainsUnexpandedParameterPack = true;
1148
1149 if (Types[i]->getType()->isDependentType()) {
1150 IsResultDependent = true;
1151 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001152 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001153 // complete object type other than a variably modified type."
1154 unsigned D = 0;
1155 if (Types[i]->getType()->isIncompleteType())
1156 D = diag::err_assoc_type_incomplete;
1157 else if (!Types[i]->getType()->isObjectType())
1158 D = diag::err_assoc_type_nonobject;
1159 else if (Types[i]->getType()->isVariablyModifiedType())
1160 D = diag::err_assoc_type_variably_modified;
1161
1162 if (D != 0) {
1163 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1164 << Types[i]->getTypeLoc().getSourceRange()
1165 << Types[i]->getType();
1166 TypeErrorFound = true;
1167 }
1168
Benjamin Kramere56f3932011-12-23 17:00:35 +00001169 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001170 // selection shall specify compatible types."
1171 for (unsigned j = i+1; j < NumAssocs; ++j)
1172 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1173 Context.typesAreCompatible(Types[i]->getType(),
1174 Types[j]->getType())) {
1175 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1176 diag::err_assoc_compatible_types)
1177 << Types[j]->getTypeLoc().getSourceRange()
1178 << Types[j]->getType()
1179 << Types[i]->getType();
1180 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1181 diag::note_compat_assoc)
1182 << Types[i]->getTypeLoc().getSourceRange()
1183 << Types[i]->getType();
1184 TypeErrorFound = true;
1185 }
1186 }
1187 }
1188 }
1189 if (TypeErrorFound)
1190 return ExprError();
1191
1192 // If we determined that the generic selection is result-dependent, don't
1193 // try to compute the result expression.
1194 if (IsResultDependent)
1195 return Owned(new (Context) GenericSelectionExpr(
1196 Context, KeyLoc, ControllingExpr,
1197 Types, Exprs, NumAssocs, DefaultLoc,
1198 RParenLoc, ContainsUnexpandedParameterPack));
1199
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001200 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001201 unsigned DefaultIndex = -1U;
1202 for (unsigned i = 0; i < NumAssocs; ++i) {
1203 if (!Types[i])
1204 DefaultIndex = i;
1205 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1206 Types[i]->getType()))
1207 CompatIndices.push_back(i);
1208 }
1209
Benjamin Kramere56f3932011-12-23 17:00:35 +00001210 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001211 // type compatible with at most one of the types named in its generic
1212 // association list."
1213 if (CompatIndices.size() > 1) {
1214 // We strip parens here because the controlling expression is typically
1215 // parenthesized in macro definitions.
1216 ControllingExpr = ControllingExpr->IgnoreParens();
1217 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1218 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1219 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001220 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001221 E = CompatIndices.end(); I != E; ++I) {
1222 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1223 diag::note_compat_assoc)
1224 << Types[*I]->getTypeLoc().getSourceRange()
1225 << Types[*I]->getType();
1226 }
1227 return ExprError();
1228 }
1229
Benjamin Kramere56f3932011-12-23 17:00:35 +00001230 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001231 // its controlling expression shall have type compatible with exactly one of
1232 // the types named in its generic association list."
1233 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1234 // We strip parens here because the controlling expression is typically
1235 // parenthesized in macro definitions.
1236 ControllingExpr = ControllingExpr->IgnoreParens();
1237 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1238 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1239 return ExprError();
1240 }
1241
Benjamin Kramere56f3932011-12-23 17:00:35 +00001242 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001243 // type name that is compatible with the type of the controlling expression,
1244 // then the result expression of the generic selection is the expression
1245 // in that generic association. Otherwise, the result expression of the
1246 // generic selection is the expression in the default generic association."
1247 unsigned ResultIndex =
1248 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1249
1250 return Owned(new (Context) GenericSelectionExpr(
1251 Context, KeyLoc, ControllingExpr,
1252 Types, Exprs, NumAssocs, DefaultLoc,
1253 RParenLoc, ContainsUnexpandedParameterPack,
1254 ResultIndex));
1255}
1256
Richard Smith75b67d62012-03-08 01:34:56 +00001257/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1258/// location of the token and the offset of the ud-suffix within it.
1259static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1260 unsigned Offset) {
1261 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001262 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001263}
1264
Richard Smithbcc22fc2012-03-09 08:00:36 +00001265/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1266/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1267static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1268 IdentifierInfo *UDSuffix,
1269 SourceLocation UDSuffixLoc,
1270 ArrayRef<Expr*> Args,
1271 SourceLocation LitEndLoc) {
1272 assert(Args.size() <= 2 && "too many arguments for literal operator");
1273
1274 QualType ArgTy[2];
1275 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1276 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1277 if (ArgTy[ArgIdx]->isArrayType())
1278 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1279 }
1280
1281 DeclarationName OpName =
1282 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1283 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1284 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1285
1286 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1287 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1288 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1289 return ExprError();
1290
1291 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1292}
1293
Steve Naroff83895f72007-09-16 03:34:24 +00001294/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001295/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1296/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1297/// multiple tokens. However, the common case is that StringToks points to one
1298/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001299///
John McCalldadc5752010-08-24 06:29:42 +00001300ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001301Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1302 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001303 assert(NumStringToks && "Must have at least one string!");
1304
Chris Lattner8a24e582009-01-16 18:51:42 +00001305 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001306 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001307 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001308
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001309 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001310 for (unsigned i = 0; i != NumStringToks; ++i)
1311 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001312
Chris Lattner36fc8792008-02-11 00:02:17 +00001313 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001314 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001315 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001316 else if (Literal.isUTF16())
1317 StrTy = Context.Char16Ty;
1318 else if (Literal.isUTF32())
1319 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001320 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001321 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001322
Douglas Gregorfb65e592011-07-27 05:40:30 +00001323 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1324 if (Literal.isWide())
1325 Kind = StringLiteral::Wide;
1326 else if (Literal.isUTF8())
1327 Kind = StringLiteral::UTF8;
1328 else if (Literal.isUTF16())
1329 Kind = StringLiteral::UTF16;
1330 else if (Literal.isUTF32())
1331 Kind = StringLiteral::UTF32;
1332
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001333 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001334 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001335 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001336
Chris Lattner36fc8792008-02-11 00:02:17 +00001337 // Get an array type for the string, according to C99 6.4.5. This includes
1338 // the nul terminator character as well as the string length for pascal
1339 // strings.
1340 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001341 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001342 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattner5b183d82006-11-10 05:03:26 +00001344 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001345 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1346 Kind, Literal.Pascal, StrTy,
1347 &StringTokLocs[0],
1348 StringTokLocs.size());
1349 if (Literal.getUDSuffix().empty())
1350 return Owned(Lit);
1351
1352 // We're building a user-defined literal.
1353 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001354 SourceLocation UDSuffixLoc =
1355 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1356 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001357
Richard Smithbcc22fc2012-03-09 08:00:36 +00001358 // Make sure we're allowed user-defined literals here.
1359 if (!UDLScope)
1360 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1361
Richard Smithc67fdd42012-03-07 08:35:16 +00001362 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1363 // operator "" X (str, len)
1364 QualType SizeType = Context.getSizeType();
1365 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1366 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1367 StringTokLocs[0]);
1368 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001369 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1370 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001371}
1372
John McCalldadc5752010-08-24 06:29:42 +00001373ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001374Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001375 SourceLocation Loc,
1376 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001377 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001378 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001379}
1380
John McCallf4cd4f92011-02-09 01:13:10 +00001381/// BuildDeclRefExpr - Build an expression that references a
1382/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001383ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001384Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001385 const DeclarationNameInfo &NameInfo,
1386 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001387 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001388 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1389 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1390 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1391 CalleeTarget = IdentifyCUDATarget(Callee);
1392 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1393 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1394 << CalleeTarget << D->getIdentifier() << CallerTarget;
1395 Diag(D->getLocation(), diag::note_previous_decl)
1396 << D->getIdentifier();
1397 return ExprError();
1398 }
1399 }
1400
John McCall113bee02012-03-10 09:33:50 +00001401 bool refersToEnclosingScope =
1402 (CurContext != D->getDeclContext() &&
1403 D->getDeclContext()->isFunctionOrMethod());
1404
Eli Friedmanfa0df832012-02-02 03:46:19 +00001405 DeclRefExpr *E = DeclRefExpr::Create(Context,
1406 SS ? SS->getWithLocInContext(Context)
1407 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001408 SourceLocation(),
1409 D, refersToEnclosingScope,
1410 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001411
Eli Friedmanfa0df832012-02-02 03:46:19 +00001412 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001413
1414 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001415 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1416 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001417 E->setObjectKind(OK_BitField);
1418
1419 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001420}
1421
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001422/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001423/// possibly a list of template arguments.
1424///
1425/// If this produces template arguments, it is permitted to call
1426/// DecomposeTemplateName.
1427///
1428/// This actually loses a lot of source location information for
1429/// non-standard name kinds; we should consider preserving that in
1430/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001431void
1432Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1433 TemplateArgumentListInfo &Buffer,
1434 DeclarationNameInfo &NameInfo,
1435 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001436 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1437 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1438 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1439
Douglas Gregor5476205b2011-06-23 00:49:38 +00001440 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001441 Id.TemplateId->getTemplateArgs(),
1442 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001443 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001444 TemplateArgsPtr.release();
1445
John McCall3e56fd42010-08-23 07:28:44 +00001446 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001447 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001448 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001449 TemplateArgs = &Buffer;
1450 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001451 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001452 TemplateArgs = 0;
1453 }
1454}
1455
John McCalld681c392009-12-16 08:11:27 +00001456/// Diagnose an empty lookup.
1457///
1458/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001459bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001460 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001461 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001462 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001463 DeclarationName Name = R.getLookupName();
1464
John McCalld681c392009-12-16 08:11:27 +00001465 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001466 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001467 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1468 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001469 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001470 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001471 diagnostic_suggest = diag::err_undeclared_use_suggest;
1472 }
John McCalld681c392009-12-16 08:11:27 +00001473
Douglas Gregor598b08f2009-12-31 05:20:13 +00001474 // If the original lookup was an unqualified lookup, fake an
1475 // unqualified lookup. This is useful when (for example) the
1476 // original lookup would not have found something because it was a
1477 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001478 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1479 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001480 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001481 if (isa<CXXRecordDecl>(DC)) {
1482 LookupQualifiedName(R, DC);
1483
1484 if (!R.empty()) {
1485 // Don't give errors about ambiguities in this lookup.
1486 R.suppressDiagnostics();
1487
Francois Pichet857f9d62011-11-17 03:44:24 +00001488 // During a default argument instantiation the CurContext points
1489 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1490 // function parameter list, hence add an explicit check.
1491 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1492 ActiveTemplateInstantiations.back().Kind ==
1493 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001494 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1495 bool isInstance = CurMethod &&
1496 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001497 DC == CurMethod->getParent() && !isDefaultArgument;
1498
John McCalld681c392009-12-16 08:11:27 +00001499
1500 // Give a code modification hint to insert 'this->'.
1501 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1502 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001503 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001504 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1505 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001506 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001507 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001508 if (DepMethod) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001509 if (getLangOpts().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001510 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001511 Diag(R.getNameLoc(), diagnostic) << Name
1512 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1513 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001514 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001515 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1516 R.getNameLoc(), DepThisType, false);
1517 TemplateArgumentListInfo TList;
1518 if (ULE->hasExplicitTemplateArgs())
1519 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001520
Douglas Gregore16af532011-02-28 18:50:33 +00001521 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001522 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001523 CXXDependentScopeMemberExpr *DepExpr =
1524 CXXDependentScopeMemberExpr::Create(
1525 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001526 SS.getWithLocInContext(Context),
1527 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001528 R.getLookupNameInfo(),
1529 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001530 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001531 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001532 // FIXME: we should be able to handle this case too. It is correct
1533 // to add this-> here. This is a workaround for PR7947.
1534 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001535 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001536 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001537 if (getLangOpts().MicrosoftMode)
Francois Pichet78286b22011-11-15 23:33:34 +00001538 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001539 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001540 }
John McCalld681c392009-12-16 08:11:27 +00001541
1542 // Do we really want to note all of these?
1543 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1544 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1545
Francois Pichet857f9d62011-11-17 03:44:24 +00001546 // Return true if we are inside a default argument instantiation
1547 // and the found name refers to an instance member function, otherwise
1548 // the function calling DiagnoseEmptyLookup will try to create an
1549 // implicit member call and this is wrong for default argument.
1550 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1551 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1552 return true;
1553 }
1554
John McCalld681c392009-12-16 08:11:27 +00001555 // Tell the callee to try to recover.
1556 return false;
1557 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001558
1559 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001560 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001561
1562 // In Microsoft mode, if we are performing lookup from within a friend
1563 // function definition declared at class scope then we must set
1564 // DC to the lexical parent to be able to search into the parent
1565 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001566 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001567 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1568 DC->getLexicalParent()->isRecord())
1569 DC = DC->getLexicalParent();
1570 else
1571 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001572 }
1573
Douglas Gregor598b08f2009-12-31 05:20:13 +00001574 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001575 TypoCorrection Corrected;
1576 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001577 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1579 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001580 R.setLookupName(Corrected.getCorrection());
1581
Hans Wennborg38198de2011-07-12 08:45:31 +00001582 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001583 if (Corrected.isOverloaded()) {
1584 OverloadCandidateSet OCS(R.getNameLoc());
1585 OverloadCandidateSet::iterator Best;
1586 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1587 CDEnd = Corrected.end();
1588 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001589 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001590 dyn_cast<FunctionTemplateDecl>(*CD))
1591 AddTemplateOverloadCandidate(
1592 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001593 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001594 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1595 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1596 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001597 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001598 }
1599 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1600 case OR_Success:
1601 ND = Best->Function;
1602 break;
1603 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001604 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001605 }
1606 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001607 R.addDecl(ND);
1608 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001609 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001610 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1611 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001612 else
1613 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001614 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001615 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001616 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1617 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001618 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001619 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001620
1621 // Tell the callee to try to recover.
1622 return false;
1623 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001624
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001625 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001626 // FIXME: If we ended up with a typo for a type name or
1627 // Objective-C class name, we're in trouble because the parser
1628 // is in the wrong place to recover. Suggest the typo
1629 // correction, but don't make it a fix-it since we're not going
1630 // to recover well anyway.
1631 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001632 Diag(R.getNameLoc(), diagnostic_suggest)
1633 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001634 else
1635 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001636 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001637 << SS.getRange();
1638
1639 // Don't try to recover; it won't work.
1640 return true;
1641 }
1642 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001643 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001644 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001645 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001646 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001647 else
Douglas Gregor25363982010-01-01 00:15:04 +00001648 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001649 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001650 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001651 return true;
1652 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001653 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001654 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001655
1656 // Emit a special diagnostic for failed member lookups.
1657 // FIXME: computing the declaration context might fail here (?)
1658 if (!SS.isEmpty()) {
1659 Diag(R.getNameLoc(), diag::err_no_member)
1660 << Name << computeDeclContext(SS, false)
1661 << SS.getRange();
1662 return true;
1663 }
1664
John McCalld681c392009-12-16 08:11:27 +00001665 // Give up, we can't recover.
1666 Diag(R.getNameLoc(), diagnostic) << Name;
1667 return true;
1668}
1669
John McCalldadc5752010-08-24 06:29:42 +00001670ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001671 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001672 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001673 UnqualifiedId &Id,
1674 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001675 bool IsAddressOfOperand,
1676 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001677 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001678 "cannot be direct & operand and have a trailing lparen");
1679
1680 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001681 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001682
John McCall10eae182009-11-30 22:42:35 +00001683 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001684
1685 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001686 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001687 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001688 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001689
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001690 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001691 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001692 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001693
John McCalle66edc12009-11-24 19:00:30 +00001694 // C++ [temp.dep.expr]p3:
1695 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001696 // -- an identifier that was declared with a dependent type,
1697 // (note: handled after lookup)
1698 // -- a template-id that is dependent,
1699 // (note: handled in BuildTemplateIdExpr)
1700 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001701 // -- a nested-name-specifier that contains a class-name that
1702 // names a dependent type.
1703 // Determine whether this is a member of an unknown specialization;
1704 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001705 bool DependentID = false;
1706 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1707 Name.getCXXNameType()->isDependentType()) {
1708 DependentID = true;
1709 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001710 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001711 if (RequireCompleteDeclContext(SS, DC))
1712 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001713 } else {
1714 DependentID = true;
1715 }
1716 }
1717
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001718 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001719 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1720 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001721
John McCalle66edc12009-11-24 19:00:30 +00001722 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001723 LookupResult R(*this, NameInfo,
1724 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1725 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001726 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001727 // Lookup the template name again to correctly establish the context in
1728 // which it was found. This is really unfortunate as we already did the
1729 // lookup to determine that it was a template name in the first place. If
1730 // this becomes a performance hit, we can work harder to preserve those
1731 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001732 bool MemberOfUnknownSpecialization;
1733 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1734 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001735
1736 if (MemberOfUnknownSpecialization ||
1737 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1739 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001740 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001742 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregora5226932011-02-04 13:35:07 +00001744 // If the result might be in a dependent base class, this is a dependent
1745 // id-expression.
1746 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001747 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748 IsAddressOfOperand, TemplateArgs);
1749
John McCalle66edc12009-11-24 19:00:30 +00001750 // If this reference is in an Objective-C method, then we need to do
1751 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001752 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001753 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001754 if (E.isInvalid())
1755 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001756
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001757 if (Expr *Ex = E.takeAs<Expr>())
1758 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001759 }
Chris Lattner59a25942008-03-31 00:36:02 +00001760 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001761
John McCalle66edc12009-11-24 19:00:30 +00001762 if (R.isAmbiguous())
1763 return ExprError();
1764
Douglas Gregor171c45a2009-02-18 21:56:37 +00001765 // Determine whether this name might be a candidate for
1766 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001767 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001768
John McCalle66edc12009-11-24 19:00:30 +00001769 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001770 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001771 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001772 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001773 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1774 if (D) R.addDecl(D);
1775 }
1776
1777 // If this name wasn't predeclared and if this is not a function
1778 // call, diagnose the problem.
1779 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001780
1781 // In Microsoft mode, if we are inside a template class member function
1782 // and we can't resolve an identifier then assume the identifier is type
1783 // dependent. The goal is to postpone name lookup to instantiation time
1784 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001785 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001786 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001787 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1788 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001789
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001790 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001791 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001792 return ExprError();
1793
1794 assert(!R.empty() &&
1795 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001796
1797 // If we found an Objective-C instance variable, let
1798 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001799 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001800 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1801 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001802 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001803 // In a hopelessly buggy code, Objective-C instance variable
1804 // lookup fails and no expression will be built to reference it.
1805 if (!E.isInvalid() && !E.get())
1806 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001807 return move(E);
1808 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001809 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001810 }
Mike Stump11289f42009-09-09 15:08:12 +00001811
John McCalle66edc12009-11-24 19:00:30 +00001812 // This is guaranteed from this point on.
1813 assert(!R.empty() || ADL);
1814
John McCall2d74de92009-12-01 22:10:20 +00001815 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001816 // C++ [class.mfct.non-static]p3:
1817 // When an id-expression that is not part of a class member access
1818 // syntax and not used to form a pointer to member is used in the
1819 // body of a non-static member function of class X, if name lookup
1820 // resolves the name in the id-expression to a non-static non-type
1821 // member of some class C, the id-expression is transformed into a
1822 // class member access expression using (*this) as the
1823 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001824 //
1825 // But we don't actually need to do this for '&' operands if R
1826 // resolved to a function or overloaded function set, because the
1827 // expression is ill-formed if it actually works out to be a
1828 // non-static member function:
1829 //
1830 // C++ [expr.ref]p4:
1831 // Otherwise, if E1.E2 refers to a non-static member function. . .
1832 // [t]he expression can be used only as the left-hand operand of a
1833 // member function call.
1834 //
1835 // There are other safeguards against such uses, but it's important
1836 // to get this right here so that we don't end up making a
1837 // spuriously dependent expression if we're inside a dependent
1838 // instance method.
John McCall57500772009-12-16 12:17:52 +00001839 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001840 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001841 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001842 MightBeImplicitMember = true;
1843 else if (!SS.isEmpty())
1844 MightBeImplicitMember = false;
1845 else if (R.isOverloadedResult())
1846 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001847 else if (R.isUnresolvableResult())
1848 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001849 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001850 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1851 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001852
1853 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001854 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1855 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001856 }
1857
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001858 if (TemplateArgs || TemplateKWLoc.isValid())
1859 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001860
John McCalle66edc12009-11-24 19:00:30 +00001861 return BuildDeclarationNameExpr(SS, R, ADL);
1862}
1863
John McCall10eae182009-11-30 22:42:35 +00001864/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1865/// declaration name, generally during template instantiation.
1866/// There's a large number of things which don't need to be done along
1867/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001868ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001869Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001870 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001871 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001872 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001873 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1874 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001875
John McCall0b66eb32010-05-01 00:40:08 +00001876 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001877 return ExprError();
1878
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001879 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001880 LookupQualifiedName(R, DC);
1881
1882 if (R.isAmbiguous())
1883 return ExprError();
1884
1885 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001886 Diag(NameInfo.getLoc(), diag::err_no_member)
1887 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001888 return ExprError();
1889 }
1890
1891 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1892}
1893
1894/// LookupInObjCMethod - The parser has read a name in, and Sema has
1895/// detected that we're currently inside an ObjC method. Perform some
1896/// additional lookup.
1897///
1898/// Ideally, most of this would be done by lookup, but there's
1899/// actually quite a lot of extra work involved.
1900///
1901/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001902ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001903Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001904 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001905 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001906 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001907
John McCalle66edc12009-11-24 19:00:30 +00001908 // There are two cases to handle here. 1) scoped lookup could have failed,
1909 // in which case we should look for an ivar. 2) scoped lookup could have
1910 // found a decl, but that decl is outside the current instance method (i.e.
1911 // a global variable). In these two cases, we do a lookup for an ivar with
1912 // this name, if the lookup sucedes, we replace it our current decl.
1913
1914 // If we're in a class method, we don't normally want to look for
1915 // ivars. But if we don't find anything else, and there's an
1916 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001917 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001918
1919 bool LookForIvars;
1920 if (Lookup.empty())
1921 LookForIvars = true;
1922 else if (IsClassMethod)
1923 LookForIvars = false;
1924 else
1925 LookForIvars = (Lookup.isSingleResult() &&
1926 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001927 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001928 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001929 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001930 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001931 ObjCIvarDecl *IV = 0;
1932 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001933 // Diagnose using an ivar in a class method.
1934 if (IsClassMethod)
1935 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1936 << IV->getDeclName());
1937
1938 // If we're referencing an invalid decl, just return this as a silent
1939 // error node. The error diagnostic was already emitted on the decl.
1940 if (IV->isInvalidDecl())
1941 return ExprError();
1942
1943 // Check if referencing a field with __attribute__((deprecated)).
1944 if (DiagnoseUseOfDecl(IV, Loc))
1945 return ExprError();
1946
1947 // Diagnose the use of an ivar outside of the declaring class.
1948 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001949 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001951 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1952
1953 // FIXME: This should use a new expr for a direct reference, don't
1954 // turn this into Self->ivar, just return a BareIVarExpr or something.
1955 IdentifierInfo &II = Context.Idents.get("self");
1956 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001957 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001958 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001959 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001960 SourceLocation TemplateKWLoc;
1961 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001962 SelfName, false, false);
1963 if (SelfExpr.isInvalid())
1964 return ExprError();
1965
John Wiegley01296292011-04-08 18:41:53 +00001966 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1967 if (SelfExpr.isInvalid())
1968 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001969
Eli Friedmanfa0df832012-02-02 03:46:19 +00001970 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001971 return Owned(new (Context)
1972 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001973 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001974 }
Chris Lattner87313662010-04-12 05:10:17 +00001975 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001976 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001977 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1978 ObjCInterfaceDecl *ClassDeclared;
1979 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1980 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001981 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001982 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1983 }
John McCalle66edc12009-11-24 19:00:30 +00001984 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001985 } else if (Lookup.isSingleResult() &&
1986 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1987 // If accessing a stand-alone ivar in a class method, this is an error.
1988 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1989 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1990 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001991 }
1992
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001993 if (Lookup.empty() && II && AllowBuiltinCreation) {
1994 // FIXME. Consolidate this with similar code in LookupName.
1995 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001996 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001997 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1998 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1999 S, Lookup.isForRedeclaration(),
2000 Lookup.getNameLoc());
2001 if (D) Lookup.addDecl(D);
2002 }
2003 }
2004 }
John McCalle66edc12009-11-24 19:00:30 +00002005 // Sentinel value saying that we didn't do anything special.
2006 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002007}
John McCalld14a8642009-11-21 08:51:07 +00002008
John McCall16df1e52010-03-30 21:47:33 +00002009/// \brief Cast a base object to a member's actual type.
2010///
2011/// Logically this happens in three phases:
2012///
2013/// * First we cast from the base type to the naming class.
2014/// The naming class is the class into which we were looking
2015/// when we found the member; it's the qualifier type if a
2016/// qualifier was provided, and otherwise it's the base type.
2017///
2018/// * Next we cast from the naming class to the declaring class.
2019/// If the member we found was brought into a class's scope by
2020/// a using declaration, this is that class; otherwise it's
2021/// the class declaring the member.
2022///
2023/// * Finally we cast from the declaring class to the "true"
2024/// declaring class of the member. This conversion does not
2025/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002026ExprResult
2027Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002028 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002029 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002030 NamedDecl *Member) {
2031 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2032 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002033 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002034
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002035 QualType DestRecordType;
2036 QualType DestType;
2037 QualType FromRecordType;
2038 QualType FromType = From->getType();
2039 bool PointerConversions = false;
2040 if (isa<FieldDecl>(Member)) {
2041 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002042
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002043 if (FromType->getAs<PointerType>()) {
2044 DestType = Context.getPointerType(DestRecordType);
2045 FromRecordType = FromType->getPointeeType();
2046 PointerConversions = true;
2047 } else {
2048 DestType = DestRecordType;
2049 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002050 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002051 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2052 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002053 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002054
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002055 DestType = Method->getThisType(Context);
2056 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002057
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002058 if (FromType->getAs<PointerType>()) {
2059 FromRecordType = FromType->getPointeeType();
2060 PointerConversions = true;
2061 } else {
2062 FromRecordType = FromType;
2063 DestType = DestRecordType;
2064 }
2065 } else {
2066 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002067 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002068 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002069
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002070 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002071 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002072
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002073 // If the unqualified types are the same, no conversion is necessary.
2074 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002075 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002076
John McCall16df1e52010-03-30 21:47:33 +00002077 SourceRange FromRange = From->getSourceRange();
2078 SourceLocation FromLoc = FromRange.getBegin();
2079
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002080 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002081
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002082 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002083 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002084 // class name.
2085 //
2086 // If the member was a qualified name and the qualified referred to a
2087 // specific base subobject type, we'll cast to that intermediate type
2088 // first and then to the object in which the member is declared. That allows
2089 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2090 //
2091 // class Base { public: int x; };
2092 // class Derived1 : public Base { };
2093 // class Derived2 : public Base { };
2094 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2095 //
2096 // void VeryDerived::f() {
2097 // x = 17; // error: ambiguous base subobjects
2098 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2099 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002100 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002101 QualType QType = QualType(Qualifier->getAsType(), 0);
2102 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2103 assert(QType->isRecordType() && "lookup done with non-record type");
2104
2105 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2106
2107 // In C++98, the qualifier type doesn't actually have to be a base
2108 // type of the object type, in which case we just ignore it.
2109 // Otherwise build the appropriate casts.
2110 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002111 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002112 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002113 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002114 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002115
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002116 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002117 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002118 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2119 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002120
2121 FromType = QType;
2122 FromRecordType = QRecordType;
2123
2124 // If the qualifier type was the same as the destination type,
2125 // we're done.
2126 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002127 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002128 }
2129 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002130
John McCall16df1e52010-03-30 21:47:33 +00002131 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002132
John McCall16df1e52010-03-30 21:47:33 +00002133 // If we actually found the member through a using declaration, cast
2134 // down to the using declaration's type.
2135 //
2136 // Pointer equality is fine here because only one declaration of a
2137 // class ever has member declarations.
2138 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2139 assert(isa<UsingShadowDecl>(FoundDecl));
2140 QualType URecordType = Context.getTypeDeclType(
2141 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2142
2143 // We only need to do this if the naming-class to declaring-class
2144 // conversion is non-trivial.
2145 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2146 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002147 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002148 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002149 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002150 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002151
John McCall16df1e52010-03-30 21:47:33 +00002152 QualType UType = URecordType;
2153 if (PointerConversions)
2154 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002155 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2156 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002157 FromType = UType;
2158 FromRecordType = URecordType;
2159 }
2160
2161 // We don't do access control for the conversion from the
2162 // declaring class to the true declaring class.
2163 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002164 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002165
John McCallcf142162010-08-07 06:22:56 +00002166 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002167 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2168 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002169 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002170 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002171
John Wiegley01296292011-04-08 18:41:53 +00002172 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2173 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002174}
Douglas Gregor3256d042009-06-30 15:47:41 +00002175
John McCalle66edc12009-11-24 19:00:30 +00002176bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002177 const LookupResult &R,
2178 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002179 // Only when used directly as the postfix-expression of a call.
2180 if (!HasTrailingLParen)
2181 return false;
2182
2183 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002184 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002185 return false;
2186
2187 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002188 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002189 return false;
2190
2191 // Turn off ADL when we find certain kinds of declarations during
2192 // normal lookup:
2193 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2194 NamedDecl *D = *I;
2195
2196 // C++0x [basic.lookup.argdep]p3:
2197 // -- a declaration of a class member
2198 // Since using decls preserve this property, we check this on the
2199 // original decl.
John McCall57500772009-12-16 12:17:52 +00002200 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002201 return false;
2202
2203 // C++0x [basic.lookup.argdep]p3:
2204 // -- a block-scope function declaration that is not a
2205 // using-declaration
2206 // NOTE: we also trigger this for function templates (in fact, we
2207 // don't check the decl type at all, since all other decl types
2208 // turn off ADL anyway).
2209 if (isa<UsingShadowDecl>(D))
2210 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2211 else if (D->getDeclContext()->isFunctionOrMethod())
2212 return false;
2213
2214 // C++0x [basic.lookup.argdep]p3:
2215 // -- a declaration that is neither a function or a function
2216 // template
2217 // And also for builtin functions.
2218 if (isa<FunctionDecl>(D)) {
2219 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2220
2221 // But also builtin functions.
2222 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2223 return false;
2224 } else if (!isa<FunctionTemplateDecl>(D))
2225 return false;
2226 }
2227
2228 return true;
2229}
2230
2231
John McCalld14a8642009-11-21 08:51:07 +00002232/// Diagnoses obvious problems with the use of the given declaration
2233/// as an expression. This is only actually called for lookups that
2234/// were not overloaded, and it doesn't promise that the declaration
2235/// will in fact be used.
2236static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002237 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002238 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2239 return true;
2240 }
2241
2242 if (isa<ObjCInterfaceDecl>(D)) {
2243 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2244 return true;
2245 }
2246
2247 if (isa<NamespaceDecl>(D)) {
2248 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2249 return true;
2250 }
2251
2252 return false;
2253}
2254
John McCalldadc5752010-08-24 06:29:42 +00002255ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002256Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002257 LookupResult &R,
2258 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002259 // If this is a single, fully-resolved result and we don't need ADL,
2260 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002261 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002262 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2263 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002264
2265 // We only need to check the declaration if there's exactly one
2266 // result, because in the overloaded case the results can only be
2267 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002268 if (R.isSingleResult() &&
2269 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002270 return ExprError();
2271
John McCall58cc69d2010-01-27 01:50:18 +00002272 // Otherwise, just build an unresolved lookup expression. Suppress
2273 // any lookup-related diagnostics; we'll hash these out later, when
2274 // we've picked a target.
2275 R.suppressDiagnostics();
2276
John McCalld14a8642009-11-21 08:51:07 +00002277 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002278 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002279 SS.getWithLocInContext(Context),
2280 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002281 NeedsADL, R.isOverloadedResult(),
2282 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002283
2284 return Owned(ULE);
2285}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002286
John McCalld14a8642009-11-21 08:51:07 +00002287/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002288ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002289Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002290 const DeclarationNameInfo &NameInfo,
2291 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002292 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002293 assert(!isa<FunctionTemplateDecl>(D) &&
2294 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002295
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002296 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002297 if (CheckDeclInExpr(*this, Loc, D))
2298 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002299
Douglas Gregore7488b92009-12-01 16:58:18 +00002300 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2301 // Specifically diagnose references to class templates that are missing
2302 // a template argument list.
2303 Diag(Loc, diag::err_template_decl_ref)
2304 << Template << SS.getRange();
2305 Diag(Template->getLocation(), diag::note_template_decl_here);
2306 return ExprError();
2307 }
2308
2309 // Make sure that we're referring to a value.
2310 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2311 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002312 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002313 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002314 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002315 return ExprError();
2316 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002317
Douglas Gregor171c45a2009-02-18 21:56:37 +00002318 // Check whether this declaration can be used. Note that we suppress
2319 // this check when we're going to perform argument-dependent lookup
2320 // on this function name, because this might not be the function
2321 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002322 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002323 return ExprError();
2324
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002325 // Only create DeclRefExpr's for valid Decl's.
2326 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002327 return ExprError();
2328
John McCallf3a88602011-02-03 08:15:49 +00002329 // Handle members of anonymous structs and unions. If we got here,
2330 // and the reference is to a class member indirect field, then this
2331 // must be the subject of a pointer-to-member expression.
2332 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2333 if (!indirectField->isCXXClassMember())
2334 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2335 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002336
Eli Friedman9bb33f52012-02-03 02:04:35 +00002337 {
John McCallf4cd4f92011-02-09 01:13:10 +00002338 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002339 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002340
2341 switch (D->getKind()) {
2342 // Ignore all the non-ValueDecl kinds.
2343#define ABSTRACT_DECL(kind)
2344#define VALUE(type, base)
2345#define DECL(type, base) \
2346 case Decl::type:
2347#include "clang/AST/DeclNodes.inc"
2348 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002349
2350 // These shouldn't make it here.
2351 case Decl::ObjCAtDefsField:
2352 case Decl::ObjCIvar:
2353 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002354
2355 // Enum constants are always r-values and never references.
2356 // Unresolved using declarations are dependent.
2357 case Decl::EnumConstant:
2358 case Decl::UnresolvedUsingValue:
2359 valueKind = VK_RValue;
2360 break;
2361
2362 // Fields and indirect fields that got here must be for
2363 // pointer-to-member expressions; we just call them l-values for
2364 // internal consistency, because this subexpression doesn't really
2365 // exist in the high-level semantics.
2366 case Decl::Field:
2367 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002368 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002369 "building reference to field in C?");
2370
2371 // These can't have reference type in well-formed programs, but
2372 // for internal consistency we do this anyway.
2373 type = type.getNonReferenceType();
2374 valueKind = VK_LValue;
2375 break;
2376
2377 // Non-type template parameters are either l-values or r-values
2378 // depending on the type.
2379 case Decl::NonTypeTemplateParm: {
2380 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2381 type = reftype->getPointeeType();
2382 valueKind = VK_LValue; // even if the parameter is an r-value reference
2383 break;
2384 }
2385
2386 // For non-references, we need to strip qualifiers just in case
2387 // the template parameter was declared as 'const int' or whatever.
2388 valueKind = VK_RValue;
2389 type = type.getUnqualifiedType();
2390 break;
2391 }
2392
2393 case Decl::Var:
2394 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002395 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002396 !type.hasQualifiers() &&
2397 type->isVoidType()) {
2398 valueKind = VK_RValue;
2399 break;
2400 }
2401 // fallthrough
2402
2403 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002404 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002405 // These are always l-values.
2406 valueKind = VK_LValue;
2407 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002408
Douglas Gregor812d8f62012-02-18 05:51:20 +00002409 // FIXME: Does the addition of const really only apply in
2410 // potentially-evaluated contexts? Since the variable isn't actually
2411 // captured in an unevaluated context, it seems that the answer is no.
2412 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2413 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2414 if (!CapturedType.isNull())
2415 type = CapturedType;
2416 }
2417
John McCallf4cd4f92011-02-09 01:13:10 +00002418 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002419 }
2420
John McCallf4cd4f92011-02-09 01:13:10 +00002421 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002422 const FunctionType *fty = type->castAs<FunctionType>();
2423
2424 // If we're referring to a function with an __unknown_anytype
2425 // result type, make the entire expression __unknown_anytype.
2426 if (fty->getResultType() == Context.UnknownAnyTy) {
2427 type = Context.UnknownAnyTy;
2428 valueKind = VK_RValue;
2429 break;
2430 }
2431
John McCallf4cd4f92011-02-09 01:13:10 +00002432 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002433 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002434 valueKind = VK_LValue;
2435 break;
2436 }
2437
2438 // C99 DR 316 says that, if a function type comes from a
2439 // function definition (without a prototype), that type is only
2440 // used for checking compatibility. Therefore, when referencing
2441 // the function, we pretend that we don't have the full function
2442 // type.
John McCall2979fe02011-04-12 00:42:48 +00002443 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2444 isa<FunctionProtoType>(fty))
2445 type = Context.getFunctionNoProtoType(fty->getResultType(),
2446 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002447
2448 // Functions are r-values in C.
2449 valueKind = VK_RValue;
2450 break;
2451 }
2452
2453 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002454 // If we're referring to a method with an __unknown_anytype
2455 // result type, make the entire expression __unknown_anytype.
2456 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002457 if (const FunctionProtoType *proto
2458 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002459 if (proto->getResultType() == Context.UnknownAnyTy) {
2460 type = Context.UnknownAnyTy;
2461 valueKind = VK_RValue;
2462 break;
2463 }
2464
John McCallf4cd4f92011-02-09 01:13:10 +00002465 // C++ methods are l-values if static, r-values if non-static.
2466 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2467 valueKind = VK_LValue;
2468 break;
2469 }
2470 // fallthrough
2471
2472 case Decl::CXXConversion:
2473 case Decl::CXXDestructor:
2474 case Decl::CXXConstructor:
2475 valueKind = VK_RValue;
2476 break;
2477 }
2478
2479 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2480 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002481}
Chris Lattnere168f762006-11-10 05:29:30 +00002482
John McCall2979fe02011-04-12 00:42:48 +00002483ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002484 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002485
Chris Lattnere168f762006-11-10 05:29:30 +00002486 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002487 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002488 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2489 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2490 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002491 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002492
Chris Lattnera81a0272008-01-12 08:14:25 +00002493 // Pre-defined identifiers are of type char[x], where x is the length of the
2494 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002495
Anders Carlsson2fb08242009-09-08 18:24:21 +00002496 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002497 if (!currentDecl && getCurBlock())
2498 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002499 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002500 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002501 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002502 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002503
Anders Carlsson0b209a82009-09-11 01:22:35 +00002504 QualType ResTy;
2505 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2506 ResTy = Context.DependentTy;
2507 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002508 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002509
Anders Carlsson0b209a82009-09-11 01:22:35 +00002510 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002511 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002512 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2513 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002514 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002515}
2516
Richard Smithbcc22fc2012-03-09 08:00:36 +00002517ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002518 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002519 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002520 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002521 if (Invalid)
2522 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002523
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002524 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002525 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002526 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002527 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002528
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002529 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002530 if (Literal.isWide())
2531 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002532 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002533 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002534 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002535 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002536 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002537 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002538 else
2539 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002540
Douglas Gregorfb65e592011-07-27 05:40:30 +00002541 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2542 if (Literal.isWide())
2543 Kind = CharacterLiteral::Wide;
2544 else if (Literal.isUTF16())
2545 Kind = CharacterLiteral::UTF16;
2546 else if (Literal.isUTF32())
2547 Kind = CharacterLiteral::UTF32;
2548
Richard Smith75b67d62012-03-08 01:34:56 +00002549 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2550 Tok.getLocation());
2551
2552 if (Literal.getUDSuffix().empty())
2553 return Owned(Lit);
2554
2555 // We're building a user-defined literal.
2556 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2557 SourceLocation UDSuffixLoc =
2558 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2559
Richard Smithbcc22fc2012-03-09 08:00:36 +00002560 // Make sure we're allowed user-defined literals here.
2561 if (!UDLScope)
2562 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2563
Richard Smith75b67d62012-03-08 01:34:56 +00002564 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2565 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002566 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2567 llvm::makeArrayRef(&Lit, 1),
2568 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002569}
2570
Ted Kremeneke65b0862012-03-06 20:05:56 +00002571ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2572 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2573 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2574 Context.IntTy, Loc));
2575}
2576
Richard Smith39570d002012-03-08 08:45:32 +00002577static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2578 QualType Ty, SourceLocation Loc) {
2579 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2580
2581 using llvm::APFloat;
2582 APFloat Val(Format);
2583
2584 APFloat::opStatus result = Literal.GetFloatValue(Val);
2585
2586 // Overflow is always an error, but underflow is only an error if
2587 // we underflowed to zero (APFloat reports denormals as underflow).
2588 if ((result & APFloat::opOverflow) ||
2589 ((result & APFloat::opUnderflow) && Val.isZero())) {
2590 unsigned diagnostic;
2591 SmallString<20> buffer;
2592 if (result & APFloat::opOverflow) {
2593 diagnostic = diag::warn_float_overflow;
2594 APFloat::getLargest(Format).toString(buffer);
2595 } else {
2596 diagnostic = diag::warn_float_underflow;
2597 APFloat::getSmallest(Format).toString(buffer);
2598 }
2599
2600 S.Diag(Loc, diagnostic)
2601 << Ty
2602 << StringRef(buffer.data(), buffer.size());
2603 }
2604
2605 bool isExact = (result == APFloat::opOK);
2606 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2607}
2608
Richard Smithbcc22fc2012-03-09 08:00:36 +00002609ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002610 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002611 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002612 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002613 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002614 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002615 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002616
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002617 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002618 // Add padding so that NumericLiteralParser can overread by one character.
2619 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002620 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002621
Chris Lattner67ca9252007-05-21 01:08:44 +00002622 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002623 bool Invalid = false;
2624 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2625 if (Invalid)
2626 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002627
Mike Stump11289f42009-09-09 15:08:12 +00002628 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002629 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002630 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002631 return ExprError();
2632
Richard Smith39570d002012-03-08 08:45:32 +00002633 if (Literal.hasUDSuffix()) {
2634 // We're building a user-defined literal.
2635 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2636 SourceLocation UDSuffixLoc =
2637 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2638
Richard Smithbcc22fc2012-03-09 08:00:36 +00002639 // Make sure we're allowed user-defined literals here.
2640 if (!UDLScope)
2641 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002642
Richard Smithbcc22fc2012-03-09 08:00:36 +00002643 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002644 if (Literal.isFloatingLiteral()) {
2645 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2646 // long double, the literal is treated as a call of the form
2647 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002648 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002649 } else {
2650 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2651 // unsigned long long, the literal is treated as a call of the form
2652 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002653 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002654 }
2655
Richard Smithbcc22fc2012-03-09 08:00:36 +00002656 DeclarationName OpName =
2657 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2658 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2659 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2660
2661 // Perform literal operator lookup to determine if we're building a raw
2662 // literal or a cooked one.
2663 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2664 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2665 /*AllowRawAndTemplate*/true)) {
2666 case LOLR_Error:
2667 return ExprError();
2668
2669 case LOLR_Cooked: {
2670 Expr *Lit;
2671 if (Literal.isFloatingLiteral()) {
2672 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2673 } else {
2674 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2675 if (Literal.GetIntegerValue(ResultVal))
2676 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2677 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2678 Tok.getLocation());
2679 }
2680 return BuildLiteralOperatorCall(R, OpNameInfo,
2681 llvm::makeArrayRef(&Lit, 1),
2682 Tok.getLocation());
2683 }
2684
2685 case LOLR_Raw: {
2686 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2687 // literal is treated as a call of the form
2688 // operator "" X ("n")
2689 SourceLocation TokLoc = Tok.getLocation();
2690 unsigned Length = Literal.getUDSuffixOffset();
2691 QualType StrTy = Context.getConstantArrayType(
2692 Context.CharTy, llvm::APInt(32, Length + 1),
2693 ArrayType::Normal, 0);
2694 Expr *Lit = StringLiteral::Create(
2695 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2696 /*Pascal*/false, StrTy, &TokLoc, 1);
2697 return BuildLiteralOperatorCall(R, OpNameInfo,
2698 llvm::makeArrayRef(&Lit, 1), TokLoc);
2699 }
2700
2701 case LOLR_Template:
2702 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2703 // template), L is treated as a call fo the form
2704 // operator "" X <'c1', 'c2', ... 'ck'>()
2705 // where n is the source character sequence c1 c2 ... ck.
2706 TemplateArgumentListInfo ExplicitArgs;
2707 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2708 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2709 llvm::APSInt Value(CharBits, CharIsUnsigned);
2710 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2711 Value = ThisTokBegin[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002712 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002713 TemplateArgumentLocInfo ArgInfo;
2714 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2715 }
2716 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2717 Tok.getLocation(), &ExplicitArgs);
2718 }
2719
2720 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002721 }
2722
Chris Lattner1c20a172007-08-26 03:42:43 +00002723 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002724
Chris Lattner1c20a172007-08-26 03:42:43 +00002725 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002726 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002727 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002728 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002729 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002730 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002731 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002732 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002733
Richard Smith39570d002012-03-08 08:45:32 +00002734 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002735
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002736 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002737 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002738 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002739 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002740 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002741 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002742 }
2743 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002744 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002745 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002746 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002747 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002748
Neil Boothac582c52007-08-29 22:00:19 +00002749 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002750 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002751 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002752 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002753 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002754
Chris Lattner67ca9252007-05-21 01:08:44 +00002755 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002756 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2757 // The microsoft literal suffix extensions support 128-bit literals, which
2758 // may be wider than [u]intmax_t.
2759 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2760 MaxWidth = 128;
2761 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002762
Chris Lattner67ca9252007-05-21 01:08:44 +00002763 if (Literal.GetIntegerValue(ResultVal)) {
2764 // If this value didn't fit into uintmax_t, warn and force to ull.
2765 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002766 Ty = Context.UnsignedLongLongTy;
2767 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002768 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002769 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002770 // If this value fits into a ULL, try to figure out what else it fits into
2771 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002772
Chris Lattner67ca9252007-05-21 01:08:44 +00002773 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2774 // be an unsigned int.
2775 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2776
2777 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002778 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002779 if (!Literal.isLong && !Literal.isLongLong) {
2780 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002781 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002782
Chris Lattner67ca9252007-05-21 01:08:44 +00002783 // Does it fit in a unsigned int?
2784 if (ResultVal.isIntN(IntSize)) {
2785 // Does it fit in a signed int?
2786 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002787 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002788 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002789 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002790 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002791 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002792 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002793
Chris Lattner67ca9252007-05-21 01:08:44 +00002794 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002795 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002796 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002797
Chris Lattner67ca9252007-05-21 01:08:44 +00002798 // Does it fit in a unsigned long?
2799 if (ResultVal.isIntN(LongSize)) {
2800 // Does it fit in a signed long?
2801 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002802 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002803 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002804 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002805 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002806 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002807 }
2808
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002809 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002810 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002811 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002812
Chris Lattner67ca9252007-05-21 01:08:44 +00002813 // Does it fit in a unsigned long long?
2814 if (ResultVal.isIntN(LongLongSize)) {
2815 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002816 // To be compatible with MSVC, hex integer literals ending with the
2817 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002818 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002819 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002820 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002821 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002822 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002823 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002824 }
2825 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002826
2827 // If it doesn't fit in unsigned long long, and we're using Microsoft
2828 // extensions, then its a 128-bit integer literal.
2829 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2830 if (Literal.isUnsigned)
2831 Ty = Context.UnsignedInt128Ty;
2832 else
2833 Ty = Context.Int128Ty;
2834 Width = 128;
2835 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002836
Chris Lattner67ca9252007-05-21 01:08:44 +00002837 // If we still couldn't decide a type, we probably have something that
2838 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002839 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002840 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002841 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002842 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002843 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002844
Chris Lattner55258cf2008-05-09 05:59:00 +00002845 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002846 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002847 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002848 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002849 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002850
Chris Lattner1c20a172007-08-26 03:42:43 +00002851 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2852 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002853 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002854 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002855
2856 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002857}
2858
Richard Trieuba63ce62011-09-09 01:45:06 +00002859ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002860 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002861 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002862}
2863
Chandler Carruth62da79c2011-05-26 08:53:12 +00002864static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2865 SourceLocation Loc,
2866 SourceRange ArgRange) {
2867 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2868 // scalar or vector data type argument..."
2869 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2870 // type (C99 6.2.5p18) or void.
2871 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2872 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2873 << T << ArgRange;
2874 return true;
2875 }
2876
2877 assert((T->isVoidType() || !T->isIncompleteType()) &&
2878 "Scalar types should always be complete");
2879 return false;
2880}
2881
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002882static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2883 SourceLocation Loc,
2884 SourceRange ArgRange,
2885 UnaryExprOrTypeTrait TraitKind) {
2886 // C99 6.5.3.4p1:
2887 if (T->isFunctionType()) {
2888 // alignof(function) is allowed as an extension.
2889 if (TraitKind == UETT_SizeOf)
2890 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2891 return false;
2892 }
2893
2894 // Allow sizeof(void)/alignof(void) as an extension.
2895 if (T->isVoidType()) {
2896 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2897 return false;
2898 }
2899
2900 return true;
2901}
2902
2903static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2904 SourceLocation Loc,
2905 SourceRange ArgRange,
2906 UnaryExprOrTypeTrait TraitKind) {
2907 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2908 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2909 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2910 << T << (TraitKind == UETT_SizeOf)
2911 << ArgRange;
2912 return true;
2913 }
2914
2915 return false;
2916}
2917
Chandler Carruth14502c22011-05-26 08:53:10 +00002918/// \brief Check the constrains on expression operands to unary type expression
2919/// and type traits.
2920///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002921/// Completes any types necessary and validates the constraints on the operand
2922/// expression. The logic mostly mirrors the type-based overload, but may modify
2923/// the expression as it completes the type for that expression through template
2924/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002925bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002926 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002927 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002928
2929 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2930 // the result is the size of the referenced type."
2931 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2932 // result shall be the alignment of the referenced type."
2933 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2934 ExprTy = Ref->getPointeeType();
2935
2936 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002937 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2938 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002939
2940 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002941 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2942 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002943 return false;
2944
Richard Trieuba63ce62011-09-09 01:45:06 +00002945 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002946 diag::err_sizeof_alignof_incomplete_type,
2947 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002948 return true;
2949
2950 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002951 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002952 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2953 ExprTy = Ref->getPointeeType();
2954
Richard Trieuba63ce62011-09-09 01:45:06 +00002955 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2956 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002957 return true;
2958
Nico Weber0870deb2011-06-15 02:47:03 +00002959 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002960 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002961 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2962 QualType OType = PVD->getOriginalType();
2963 QualType Type = PVD->getType();
2964 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002965 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002966 << Type << OType;
2967 Diag(PVD->getLocation(), diag::note_declared_at);
2968 }
2969 }
2970 }
2971 }
2972
Chandler Carruth7c430c02011-05-27 01:33:31 +00002973 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002974}
2975
2976/// \brief Check the constraints on operands to unary expression and type
2977/// traits.
2978///
2979/// This will complete any types necessary, and validate the various constraints
2980/// on those operands.
2981///
Steve Naroff71b59a92007-06-04 22:22:31 +00002982/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002983/// C99 6.3.2.1p[2-4] all state:
2984/// Except when it is the operand of the sizeof operator ...
2985///
2986/// C++ [expr.sizeof]p4
2987/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2988/// standard conversions are not applied to the operand of sizeof.
2989///
2990/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002991bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002992 SourceLocation OpLoc,
2993 SourceRange ExprRange,
2994 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002995 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002996 return false;
2997
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002998 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2999 // the result is the size of the referenced type."
3000 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3001 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003002 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3003 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003004
Chandler Carruth62da79c2011-05-26 08:53:12 +00003005 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003006 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003007
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003008 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003009 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003010 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003011 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003012
Richard Trieuba63ce62011-09-09 01:45:06 +00003013 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003014 diag::err_sizeof_alignof_incomplete_type,
3015 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003016 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003017
Richard Trieuba63ce62011-09-09 01:45:06 +00003018 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003019 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003020 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003021
Chris Lattner62975a72009-04-24 00:30:45 +00003022 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003023}
3024
Chandler Carruth14502c22011-05-26 08:53:10 +00003025static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003026 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003027
Mike Stump11289f42009-09-09 15:08:12 +00003028 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003029 if (isa<DeclRefExpr>(E))
3030 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003031
3032 // Cannot know anything else if the expression is dependent.
3033 if (E->isTypeDependent())
3034 return false;
3035
Douglas Gregor71235ec2009-05-02 02:18:30 +00003036 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003037 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3038 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003039 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003040 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003041
3042 // Alignment of a field access is always okay, so long as it isn't a
3043 // bit-field.
3044 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003045 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003046 return false;
3047
Chandler Carruth14502c22011-05-26 08:53:10 +00003048 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003049}
3050
Chandler Carruth14502c22011-05-26 08:53:10 +00003051bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003052 E = E->IgnoreParens();
3053
3054 // Cannot know anything else if the expression is dependent.
3055 if (E->isTypeDependent())
3056 return false;
3057
Chandler Carruth14502c22011-05-26 08:53:10 +00003058 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003059}
3060
Douglas Gregor0950e412009-03-13 21:01:28 +00003061/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003062ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003063Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3064 SourceLocation OpLoc,
3065 UnaryExprOrTypeTrait ExprKind,
3066 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003067 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003068 return ExprError();
3069
John McCallbcd03502009-12-07 02:54:59 +00003070 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003071
Douglas Gregor0950e412009-03-13 21:01:28 +00003072 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003073 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003074 return ExprError();
3075
3076 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003077 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3078 Context.getSizeType(),
3079 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003080}
3081
3082/// \brief Build a sizeof or alignof expression given an expression
3083/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003084ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003085Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3086 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003087 ExprResult PE = CheckPlaceholderExpr(E);
3088 if (PE.isInvalid())
3089 return ExprError();
3090
3091 E = PE.get();
3092
Douglas Gregor0950e412009-03-13 21:01:28 +00003093 // Verify that the operand is valid.
3094 bool isInvalid = false;
3095 if (E->isTypeDependent()) {
3096 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003097 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003098 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003099 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003100 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003101 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003102 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003103 isInvalid = true;
3104 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003105 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003106 }
3107
3108 if (isInvalid)
3109 return ExprError();
3110
Eli Friedmane0afc982012-01-21 01:01:51 +00003111 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3112 PE = TranformToPotentiallyEvaluated(E);
3113 if (PE.isInvalid()) return ExprError();
3114 E = PE.take();
3115 }
3116
Douglas Gregor0950e412009-03-13 21:01:28 +00003117 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003118 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003119 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003120 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003121}
3122
Peter Collingbournee190dee2011-03-11 19:24:49 +00003123/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3124/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003125/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003126ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003127Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003128 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003129 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003130 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003131 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003132
Richard Trieuba63ce62011-09-09 01:45:06 +00003133 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003134 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003135 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003136 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003137 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003138
Douglas Gregor0950e412009-03-13 21:01:28 +00003139 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003140 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003141 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003142}
3143
John Wiegley01296292011-04-08 18:41:53 +00003144static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003145 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003146 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003147 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003148
John McCall34376a62010-12-04 03:47:34 +00003149 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003150 if (V.get()->getObjectKind() != OK_Ordinary) {
3151 V = S.DefaultLvalueConversion(V.take());
3152 if (V.isInvalid())
3153 return QualType();
3154 }
John McCall34376a62010-12-04 03:47:34 +00003155
Chris Lattnere267f5d2007-08-26 05:39:26 +00003156 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003157 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003158 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003159
Chris Lattnere267f5d2007-08-26 05:39:26 +00003160 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003161 if (V.get()->getType()->isArithmeticType())
3162 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003163
John McCall36226622010-10-12 02:09:17 +00003164 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003165 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003166 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003167 if (PR.get() != V.get()) {
3168 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003169 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003170 }
3171
Chris Lattnere267f5d2007-08-26 05:39:26 +00003172 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003173 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003174 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003175 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003176}
3177
3178
Chris Lattnere168f762006-11-10 05:29:30 +00003179
John McCalldadc5752010-08-24 06:29:42 +00003180ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003181Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003182 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003183 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003184 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003185 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003186 case tok::plusplus: Opc = UO_PostInc; break;
3187 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003188 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003189
Sebastian Redla9351792012-02-11 23:51:47 +00003190 // Since this might is a postfix expression, get rid of ParenListExprs.
3191 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3192 if (Result.isInvalid()) return ExprError();
3193 Input = Result.take();
3194
John McCallb268a282010-08-23 23:25:46 +00003195 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003196}
3197
John McCalldadc5752010-08-24 06:29:42 +00003198ExprResult
John McCallb268a282010-08-23 23:25:46 +00003199Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3200 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003201 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003202 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003203 if (Result.isInvalid()) return ExprError();
3204 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003205
John McCallb268a282010-08-23 23:25:46 +00003206 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003207
David Blaikiebbafb8a2012-03-11 07:00:24 +00003208 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003209 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003210 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003211 Context.DependentTy,
3212 VK_LValue, OK_Ordinary,
3213 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003214 }
3215
David Blaikiebbafb8a2012-03-11 07:00:24 +00003216 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003217 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003218 LHSExp->getType()->isEnumeralType() ||
3219 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003220 RHSExp->getType()->isEnumeralType()) &&
3221 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003222 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003223 }
3224
John McCallb268a282010-08-23 23:25:46 +00003225 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003226}
3227
3228
John McCalldadc5752010-08-24 06:29:42 +00003229ExprResult
John McCallb268a282010-08-23 23:25:46 +00003230Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003231 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003232 Expr *LHSExp = Base;
3233 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003234
Chris Lattner36d572b2007-07-16 00:14:47 +00003235 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003236 if (!LHSExp->getType()->getAs<VectorType>()) {
3237 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3238 if (Result.isInvalid())
3239 return ExprError();
3240 LHSExp = Result.take();
3241 }
3242 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3243 if (Result.isInvalid())
3244 return ExprError();
3245 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003246
Chris Lattner36d572b2007-07-16 00:14:47 +00003247 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003248 ExprValueKind VK = VK_LValue;
3249 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003250
Steve Naroffc1aadb12007-03-28 21:49:40 +00003251 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003252 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003253 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003254 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003255 Expr *BaseExpr, *IndexExpr;
3256 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003257 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3258 BaseExpr = LHSExp;
3259 IndexExpr = RHSExp;
3260 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003261 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003262 BaseExpr = LHSExp;
3263 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003264 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003265 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003266 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003267 BaseExpr = LHSExp;
3268 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003269 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3270 if (!Result.isInvalid())
3271 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003272 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003273 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3274 // Handle the uncommon case of "123[Ptr]".
3275 BaseExpr = RHSExp;
3276 IndexExpr = LHSExp;
3277 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003278 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003279 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003280 // Handle the uncommon case of "123[Ptr]".
3281 BaseExpr = RHSExp;
3282 IndexExpr = LHSExp;
3283 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003284 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003285 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003286 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003287 VK = LHSExp->getValueKind();
3288 if (VK != VK_RValue)
3289 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003290
Chris Lattner36d572b2007-07-16 00:14:47 +00003291 // FIXME: need to deal with const...
3292 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003293 } else if (LHSTy->isArrayType()) {
3294 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003295 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003296 // wasn't promoted because of the C90 rule that doesn't
3297 // allow promoting non-lvalue arrays. Warn, then
3298 // force the promotion here.
3299 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3300 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003301 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3302 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003303 LHSTy = LHSExp->getType();
3304
3305 BaseExpr = LHSExp;
3306 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003307 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003308 } else if (RHSTy->isArrayType()) {
3309 // Same as previous, except for 123[f().a] case
3310 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3311 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003312 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3313 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003314 RHSTy = RHSExp->getType();
3315
3316 BaseExpr = RHSExp;
3317 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003318 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003319 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003320 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3321 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003322 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003323 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003324 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003325 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3326 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003327
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003328 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003329 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3330 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003331 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3332
Douglas Gregorac1fb652009-03-24 19:52:54 +00003333 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003334 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3335 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003336 // incomplete types are not object types.
3337 if (ResultType->isFunctionType()) {
3338 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3339 << ResultType << BaseExpr->getSourceRange();
3340 return ExprError();
3341 }
Mike Stump11289f42009-09-09 15:08:12 +00003342
David Blaikiebbafb8a2012-03-11 07:00:24 +00003343 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003344 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003345 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3346 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003347
3348 // C forbids expressions of unqualified void type from being l-values.
3349 // See IsCForbiddenLValueType.
3350 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003351 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003352 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003353 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003354 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003355
Chris Lattner62975a72009-04-24 00:30:45 +00003356 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003357 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003358 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3359 << ResultType << BaseExpr->getSourceRange();
3360 return ExprError();
3361 }
Mike Stump11289f42009-09-09 15:08:12 +00003362
John McCall4bc41ae2010-11-18 19:01:18 +00003363 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003364 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003365
Mike Stump4e1f26a2009-02-19 03:04:26 +00003366 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003367 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003368}
3369
John McCalldadc5752010-08-24 06:29:42 +00003370ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003371 FunctionDecl *FD,
3372 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003373 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003374 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003375 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003376 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003377 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003378 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003379 return ExprError();
3380 }
3381
3382 if (Param->hasUninstantiatedDefaultArg()) {
3383 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003384
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003385 // Instantiate the expression.
3386 MultiLevelTemplateArgumentList ArgList
3387 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003388
Nico Weber44887f62010-11-29 18:19:25 +00003389 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003390 = ArgList.getInnermost();
3391 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3392 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003393
Nico Weber44887f62010-11-29 18:19:25 +00003394 ExprResult Result;
3395 {
3396 // C++ [dcl.fct.default]p5:
3397 // The names in the [default argument] expression are bound, and
3398 // the semantic constraints are checked, at the point where the
3399 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003400 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003401 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003402 Result = SubstExpr(UninstExpr, ArgList);
3403 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003404 if (Result.isInvalid())
3405 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003406
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003407 // Check the expression as an initializer for the parameter.
3408 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003409 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003410 InitializationKind Kind
3411 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003412 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003413 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003414
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003415 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3416 Result = InitSeq.Perform(*this, Entity, Kind,
3417 MultiExprArg(*this, &ResultE, 1));
3418 if (Result.isInvalid())
3419 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003420
David Blaikief68e8092012-04-30 18:21:31 +00003421 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003422 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003423 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003424 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003425 }
3426
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003427 // If the default expression creates temporaries, we need to
3428 // push them to the current stack of expression temporaries so they'll
3429 // be properly destroyed.
3430 // FIXME: We should really be rebuilding the default argument with new
3431 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003432 // We don't need to do that with block decls, though, because
3433 // blocks in default argument expression can never capture anything.
3434 if (isa<ExprWithCleanups>(Param->getInit())) {
3435 // Set the "needs cleanups" bit regardless of whether there are
3436 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003437 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003438
3439 // Append all the objects to the cleanup list. Right now, this
3440 // should always be a no-op, because blocks in default argument
3441 // expressions should never be able to capture anything.
3442 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3443 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003444 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003445
3446 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003447 // Just mark all of the declarations in this potentially-evaluated expression
3448 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003449 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3450 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003451 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003452}
3453
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003454/// ConvertArgumentsForCall - Converts the arguments specified in
3455/// Args/NumArgs to the parameter types of the function FDecl with
3456/// function prototype Proto. Call is the call expression itself, and
3457/// Fn is the function expression. For a C++ member function, this
3458/// routine does not attempt to convert the object argument. Returns
3459/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003460bool
3461Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003462 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003463 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003464 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003465 SourceLocation RParenLoc,
3466 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003467 // Bail out early if calling a builtin with custom typechecking.
3468 // We don't need to do this in the
3469 if (FDecl)
3470 if (unsigned ID = FDecl->getBuiltinID())
3471 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3472 return false;
3473
Mike Stump4e1f26a2009-02-19 03:04:26 +00003474 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003475 // assignment, to the types of the corresponding parameter, ...
3476 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003477 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003478 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003479 unsigned FnKind = Fn->getType()->isBlockPointerType()
3480 ? 1 /* block */
3481 : (IsExecConfig ? 3 /* kernel function (exec config) */
3482 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003483
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003484 // If too few arguments are available (and we don't have default
3485 // arguments for the remaining parameters), don't make the call.
3486 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003487 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003488 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3489 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3490 ? diag::err_typecheck_call_too_few_args_one
3491 : diag::err_typecheck_call_too_few_args_at_least_one)
3492 << FnKind
3493 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3494 else
3495 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3496 ? diag::err_typecheck_call_too_few_args
3497 : diag::err_typecheck_call_too_few_args_at_least)
3498 << FnKind
3499 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003500
3501 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003502 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003503 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3504 << FDecl;
3505
3506 return true;
3507 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003508 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003509 }
3510
3511 // If too many are passed and not variadic, error on the extras and drop
3512 // them.
3513 if (NumArgs > NumArgsInProto) {
3514 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003515 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3516 Diag(Args[NumArgsInProto]->getLocStart(),
3517 MinArgs == NumArgsInProto
3518 ? diag::err_typecheck_call_too_many_args_one
3519 : diag::err_typecheck_call_too_many_args_at_most_one)
3520 << FnKind
3521 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3522 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3523 Args[NumArgs-1]->getLocEnd());
3524 else
3525 Diag(Args[NumArgsInProto]->getLocStart(),
3526 MinArgs == NumArgsInProto
3527 ? diag::err_typecheck_call_too_many_args
3528 : diag::err_typecheck_call_too_many_args_at_most)
3529 << FnKind
3530 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3531 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3532 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003533
3534 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003535 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003536 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3537 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003538
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003539 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003540 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003541 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003542 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003543 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003544 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003545 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003546 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3547 if (Fn->getType()->isBlockPointerType())
3548 CallType = VariadicBlock; // Block
3549 else if (isa<MemberExpr>(Fn))
3550 CallType = VariadicMethod;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003551 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003552 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003553 if (Invalid)
3554 return true;
3555 unsigned TotalNumArgs = AllArgs.size();
3556 for (unsigned i = 0; i < TotalNumArgs; ++i)
3557 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003558
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003559 return false;
3560}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003561
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003562bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3563 FunctionDecl *FDecl,
3564 const FunctionProtoType *Proto,
3565 unsigned FirstProtoArg,
3566 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003567 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003568 VariadicCallType CallType,
3569 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003570 unsigned NumArgsInProto = Proto->getNumArgs();
3571 unsigned NumArgsToCheck = NumArgs;
3572 bool Invalid = false;
3573 if (NumArgs != NumArgsInProto)
3574 // Use default arguments for missing arguments
3575 NumArgsToCheck = NumArgsInProto;
3576 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003577 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003578 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003579 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003580
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003581 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003582 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003583 if (ArgIx < NumArgs) {
3584 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003585
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003586 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003587 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003588 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003589 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003590
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003591 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003592 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003593 if (FDecl && i < FDecl->getNumParams())
3594 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003595
John McCall4124c492011-10-17 18:40:02 +00003596 // Strip the unbridged-cast placeholder expression off, if applicable.
3597 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3598 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3599 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3600 Arg = stripARCUnbridgedCast(Arg);
3601
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003602 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003603 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003604 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3605 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003606 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003607 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003608 Owned(Arg),
3609 /*TopLevelOfInitList=*/false,
3610 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003611 if (ArgE.isInvalid())
3612 return true;
3613
3614 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003615 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003616 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003617
John McCalldadc5752010-08-24 06:29:42 +00003618 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003619 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003620 if (ArgExpr.isInvalid())
3621 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003622
Anders Carlsson355933d2009-08-25 03:49:14 +00003623 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003624 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003625
3626 // Check for array bounds violations for each argument to the call. This
3627 // check only triggers warnings when the argument isn't a more complex Expr
3628 // with its own checking, such as a BinaryOperator.
3629 CheckArrayAccess(Arg);
3630
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003631 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3632 CheckStaticArrayArgument(CallLoc, Param, Arg);
3633
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003634 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003635 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003636
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003637 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003638 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003639
3640 // Assume that extern "C" functions with variadic arguments that
3641 // return __unknown_anytype aren't *really* variadic.
3642 if (Proto->getResultType() == Context.UnknownAnyTy &&
3643 FDecl && FDecl->isExternC()) {
3644 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3645 ExprResult arg;
3646 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3647 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3648 else
3649 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3650 Invalid |= arg.isInvalid();
3651 AllArgs.push_back(arg.take());
3652 }
3653
3654 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3655 } else {
3656 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003657 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3658 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003659 Invalid |= Arg.isInvalid();
3660 AllArgs.push_back(Arg.take());
3661 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003662 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003663
3664 // Check for array bounds violations.
3665 for (unsigned i = ArgIx; i != NumArgs; ++i)
3666 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003667 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003668 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003669}
3670
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003671static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3672 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3673 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3674 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3675 << ATL->getLocalSourceRange();
3676}
3677
3678/// CheckStaticArrayArgument - If the given argument corresponds to a static
3679/// array parameter, check that it is non-null, and that if it is formed by
3680/// array-to-pointer decay, the underlying array is sufficiently large.
3681///
3682/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3683/// array type derivation, then for each call to the function, the value of the
3684/// corresponding actual argument shall provide access to the first element of
3685/// an array with at least as many elements as specified by the size expression.
3686void
3687Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3688 ParmVarDecl *Param,
3689 const Expr *ArgExpr) {
3690 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003691 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003692 return;
3693
3694 QualType OrigTy = Param->getOriginalType();
3695
3696 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3697 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3698 return;
3699
3700 if (ArgExpr->isNullPointerConstant(Context,
3701 Expr::NPC_NeverValueDependent)) {
3702 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3703 DiagnoseCalleeStaticArrayParam(*this, Param);
3704 return;
3705 }
3706
3707 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3708 if (!CAT)
3709 return;
3710
3711 const ConstantArrayType *ArgCAT =
3712 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3713 if (!ArgCAT)
3714 return;
3715
3716 if (ArgCAT->getSize().ult(CAT->getSize())) {
3717 Diag(CallLoc, diag::warn_static_array_too_small)
3718 << ArgExpr->getSourceRange()
3719 << (unsigned) ArgCAT->getSize().getZExtValue()
3720 << (unsigned) CAT->getSize().getZExtValue();
3721 DiagnoseCalleeStaticArrayParam(*this, Param);
3722 }
3723}
3724
John McCall2979fe02011-04-12 00:42:48 +00003725/// Given a function expression of unknown-any type, try to rebuild it
3726/// to have a function type.
3727static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3728
Steve Naroff83895f72007-09-16 03:34:24 +00003729/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003730/// This provides the location of the left/right parens and a list of comma
3731/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003732ExprResult
John McCallb268a282010-08-23 23:25:46 +00003733Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003734 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003735 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003736 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003737
3738 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003739 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003740 if (Result.isInvalid()) return ExprError();
3741 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003742
Richard Trieuba63ce62011-09-09 01:45:06 +00003743 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003744
David Blaikiebbafb8a2012-03-11 07:00:24 +00003745 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003746 // If this is a pseudo-destructor expression, build the call immediately.
3747 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3748 if (NumArgs > 0) {
3749 // Pseudo-destructor calls should not have any arguments.
3750 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003751 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003752 SourceRange(Args[0]->getLocStart(),
3753 Args[NumArgs-1]->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003754 }
Mike Stump11289f42009-09-09 15:08:12 +00003755
Douglas Gregorad8a3362009-09-04 17:36:40 +00003756 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003757 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003758 }
Mike Stump11289f42009-09-09 15:08:12 +00003759
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003760 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003761 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003762 // FIXME: Will need to cache the results of name lookup (including ADL) in
3763 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003764 bool Dependent = false;
3765 if (Fn->isTypeDependent())
3766 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003767 else if (Expr::hasAnyTypeDependentArguments(
3768 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003769 Dependent = true;
3770
Peter Collingbourne41f85462011-02-09 21:07:24 +00003771 if (Dependent) {
3772 if (ExecConfig) {
3773 return Owned(new (Context) CUDAKernelCallExpr(
3774 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3775 Context.DependentTy, VK_RValue, RParenLoc));
3776 } else {
3777 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3778 Context.DependentTy, VK_RValue,
3779 RParenLoc));
3780 }
3781 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003782
3783 // Determine whether this is a call to an object (C++ [over.call.object]).
3784 if (Fn->getType()->isRecordType())
3785 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003786 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003787
John McCall2979fe02011-04-12 00:42:48 +00003788 if (Fn->getType() == Context.UnknownAnyTy) {
3789 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3790 if (result.isInvalid()) return ExprError();
3791 Fn = result.take();
3792 }
3793
John McCall0009fcc2011-04-26 20:42:42 +00003794 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003795 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003796 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003797 }
John McCall0009fcc2011-04-26 20:42:42 +00003798 }
John McCall10eae182009-11-30 22:42:35 +00003799
John McCall0009fcc2011-04-26 20:42:42 +00003800 // Check for overloaded calls. This can happen even in C due to extensions.
3801 if (Fn->getType() == Context.OverloadTy) {
3802 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3803
Douglas Gregorcda22702011-10-13 18:10:35 +00003804 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003805 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003806 OverloadExpr *ovl = find.Expression;
3807 if (isa<UnresolvedLookupExpr>(ovl)) {
3808 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3809 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3810 RParenLoc, ExecConfig);
3811 } else {
John McCall2d74de92009-12-01 22:10:20 +00003812 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003813 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003814 }
3815 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003816 }
3817
Douglas Gregore254f902009-02-04 00:32:51 +00003818 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003819 if (Fn->getType() == Context.UnknownAnyTy) {
3820 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3821 if (result.isInvalid()) return ExprError();
3822 Fn = result.take();
3823 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003824
Eli Friedmane14b1992009-12-26 03:35:45 +00003825 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003826
John McCall57500772009-12-16 12:17:52 +00003827 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003828 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3829 if (UnOp->getOpcode() == UO_AddrOf)
3830 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3831
John McCall57500772009-12-16 12:17:52 +00003832 if (isa<DeclRefExpr>(NakedFn))
3833 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003834 else if (isa<MemberExpr>(NakedFn))
3835 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003836
Peter Collingbourne41f85462011-02-09 21:07:24 +00003837 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003838 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003839}
3840
3841ExprResult
3842Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003843 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003844 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3845 if (!ConfigDecl)
3846 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3847 << "cudaConfigureCall");
3848 QualType ConfigQTy = ConfigDecl->getType();
3849
3850 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003851 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003852 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003853
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003854 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3855 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003856}
3857
Tanya Lattner55808c12011-06-04 00:47:47 +00003858/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3859///
3860/// __builtin_astype( value, dst type )
3861///
Richard Trieuba63ce62011-09-09 01:45:06 +00003862ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003863 SourceLocation BuiltinLoc,
3864 SourceLocation RParenLoc) {
3865 ExprValueKind VK = VK_RValue;
3866 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003867 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3868 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003869 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3870 return ExprError(Diag(BuiltinLoc,
3871 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003872 << DstTy
3873 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003874 << E->getSourceRange());
3875 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003876 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003877}
3878
John McCall57500772009-12-16 12:17:52 +00003879/// BuildResolvedCallExpr - Build a call to a resolved expression,
3880/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003881/// unary-convert to an expression of function-pointer or
3882/// block-pointer type.
3883///
3884/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003885ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003886Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3887 SourceLocation LParenLoc,
3888 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003889 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003890 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003891 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3892
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003893 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003894 ExprResult Result = UsualUnaryConversions(Fn);
3895 if (Result.isInvalid())
3896 return ExprError();
3897 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003898
Chris Lattner08464942007-12-28 05:29:59 +00003899 // Make the call expr early, before semantic checks. This guarantees cleanup
3900 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003901 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003902 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003903 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3904 cast<CallExpr>(Config),
3905 Args, NumArgs,
3906 Context.BoolTy,
3907 VK_RValue,
3908 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003909 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003910 TheCall = new (Context) CallExpr(Context, Fn,
3911 Args, NumArgs,
3912 Context.BoolTy,
3913 VK_RValue,
3914 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003915
John McCallbebede42011-02-26 05:39:39 +00003916 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3917
3918 // Bail out early if calling a builtin with custom typechecking.
3919 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3920 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3921
John McCall31996342011-04-07 08:22:57 +00003922 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003923 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003924 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003925 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3926 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003927 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003928 if (FuncT == 0)
3929 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3930 << Fn->getType() << Fn->getSourceRange());
3931 } else if (const BlockPointerType *BPT =
3932 Fn->getType()->getAs<BlockPointerType>()) {
3933 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3934 } else {
John McCall31996342011-04-07 08:22:57 +00003935 // Handle calls to expressions of unknown-any type.
3936 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003937 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003938 if (rewrite.isInvalid()) return ExprError();
3939 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003940 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003941 goto retry;
3942 }
3943
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003944 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3945 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003946 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003947
David Blaikiebbafb8a2012-03-11 07:00:24 +00003948 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003949 if (Config) {
3950 // CUDA: Kernel calls must be to global functions
3951 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3952 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3953 << FDecl->getName() << Fn->getSourceRange());
3954
3955 // CUDA: Kernel function must have 'void' return type
3956 if (!FuncT->getResultType()->isVoidType())
3957 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3958 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003959 } else {
3960 // CUDA: Calls to global functions must be configured
3961 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3962 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3963 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003964 }
3965 }
3966
Eli Friedman3164fb12009-03-22 22:00:50 +00003967 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003968 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003969 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003970 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003971 return ExprError();
3972
Chris Lattner08464942007-12-28 05:29:59 +00003973 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003974 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003975 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003976
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003977 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003978 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003979 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003980 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003981 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003982 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003983
Douglas Gregord8e97de2009-04-02 15:37:10 +00003984 if (FDecl) {
3985 // Check if we have too few/too many template arguments, based
3986 // on our knowledge of the function definition.
3987 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003988 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003989 const FunctionProtoType *Proto
3990 = Def->getType()->getAs<FunctionProtoType>();
3991 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003992 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3993 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003994 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003995
3996 // If the function we're calling isn't a function prototype, but we have
3997 // a function prototype from a prior declaratiom, use that prototype.
3998 if (!FDecl->hasPrototype())
3999 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004000 }
4001
Steve Naroff0b661582007-08-28 23:30:39 +00004002 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004003 for (unsigned i = 0; i != NumArgs; i++) {
4004 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004005
4006 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004007 InitializedEntity Entity
4008 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004009 Proto->getArgType(i),
4010 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004011 ExprResult ArgE = PerformCopyInitialization(Entity,
4012 SourceLocation(),
4013 Owned(Arg));
4014 if (ArgE.isInvalid())
4015 return true;
4016
4017 Arg = ArgE.takeAs<Expr>();
4018
4019 } else {
John Wiegley01296292011-04-08 18:41:53 +00004020 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4021
4022 if (ArgE.isInvalid())
4023 return true;
4024
4025 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004026 }
4027
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004028 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004029 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004030 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004031 return ExprError();
4032
Chris Lattner08464942007-12-28 05:29:59 +00004033 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004034 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004035 }
Chris Lattner08464942007-12-28 05:29:59 +00004036
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004037 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4038 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004039 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4040 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004041
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004042 // Check for sentinels
4043 if (NDecl)
4044 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004045
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004046 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004047 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00004048 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004049 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004050
John McCallbebede42011-02-26 05:39:39 +00004051 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004052 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004053 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00004054 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004055 return ExprError();
4056 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004057
John McCallb268a282010-08-23 23:25:46 +00004058 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004059}
4060
John McCalldadc5752010-08-24 06:29:42 +00004061ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004062Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004063 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004064 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004065 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004066 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004067
4068 TypeSourceInfo *TInfo;
4069 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4070 if (!TInfo)
4071 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4072
John McCallb268a282010-08-23 23:25:46 +00004073 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004074}
4075
John McCalldadc5752010-08-24 06:29:42 +00004076ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004077Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004078 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004079 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004080
Eli Friedman37a186d2008-05-20 05:22:08 +00004081 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004082 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004083 diag::err_illegal_decl_array_incomplete_type,
4084 SourceRange(LParenLoc,
4085 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004086 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004087 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004088 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004089 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004090 } else if (!literalType->isDependentType() &&
4091 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004092 diag::err_typecheck_decl_incomplete_type,
4093 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004094 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004095
Douglas Gregor85dabae2009-12-16 01:38:02 +00004096 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004097 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004098 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004099 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004100 SourceRange(LParenLoc, RParenLoc),
4101 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004102 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004103 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00004104 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004105 &literalType);
4106 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004107 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004108 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004109
Chris Lattner79413952008-12-04 23:50:19 +00004110 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004111 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004112 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004113 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004114 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004115
John McCall7decc9e2010-11-18 06:31:45 +00004116 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004117 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004118
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004119 return MaybeBindToTemporary(
4120 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004121 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004122}
4123
John McCalldadc5752010-08-24 06:29:42 +00004124ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004125Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004126 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004127 unsigned NumInit = InitArgList.size();
4128 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004129
John McCall526ab472011-10-25 17:37:35 +00004130 // Immediately handle non-overload placeholders. Overloads can be
4131 // resolved contextually, but everything else here can't.
4132 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00004133 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00004134 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4135
4136 // Ignore failures; dropping the entire initializer list because
4137 // of one failure would be terrible for indexing/etc.
4138 if (result.isInvalid()) continue;
4139
4140 InitList[I] = result.take();
4141 }
4142 }
4143
Steve Naroff30d242c2007-09-15 18:49:24 +00004144 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004145 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004146
Ted Kremenekac034612010-04-13 23:39:13 +00004147 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4148 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004149 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004150 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004151}
4152
John McCallcd78e802011-09-10 01:16:55 +00004153/// Do an explicit extend of the given block pointer if we're in ARC.
4154static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4155 assert(E.get()->getType()->isBlockPointerType());
4156 assert(E.get()->isRValue());
4157
4158 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004159 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004160
4161 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004162 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004163 /*base path*/ 0, VK_RValue);
4164 S.ExprNeedsCleanups = true;
4165}
4166
4167/// Prepare a conversion of the given expression to an ObjC object
4168/// pointer type.
4169CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4170 QualType type = E.get()->getType();
4171 if (type->isObjCObjectPointerType()) {
4172 return CK_BitCast;
4173 } else if (type->isBlockPointerType()) {
4174 maybeExtendBlockObject(*this, E);
4175 return CK_BlockPointerToObjCPointerCast;
4176 } else {
4177 assert(type->isPointerType());
4178 return CK_CPointerToObjCPointerCast;
4179 }
4180}
4181
John McCalld7646252010-11-14 08:17:51 +00004182/// Prepares for a scalar cast, performing all the necessary stages
4183/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004184CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004185 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4186 // Also, callers should have filtered out the invalid cases with
4187 // pointers. Everything else should be possible.
4188
John Wiegley01296292011-04-08 18:41:53 +00004189 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004190 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004191 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004192
John McCall9320b872011-09-09 05:25:32 +00004193 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004194 case Type::STK_MemberPointer:
4195 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004196
John McCall9320b872011-09-09 05:25:32 +00004197 case Type::STK_CPointer:
4198 case Type::STK_BlockPointer:
4199 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004200 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004201 case Type::STK_CPointer:
4202 return CK_BitCast;
4203 case Type::STK_BlockPointer:
4204 return (SrcKind == Type::STK_BlockPointer
4205 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4206 case Type::STK_ObjCObjectPointer:
4207 if (SrcKind == Type::STK_ObjCObjectPointer)
4208 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004209 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004210 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004211 maybeExtendBlockObject(*this, Src);
4212 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004213 case Type::STK_Bool:
4214 return CK_PointerToBoolean;
4215 case Type::STK_Integral:
4216 return CK_PointerToIntegral;
4217 case Type::STK_Floating:
4218 case Type::STK_FloatingComplex:
4219 case Type::STK_IntegralComplex:
4220 case Type::STK_MemberPointer:
4221 llvm_unreachable("illegal cast from pointer");
4222 }
David Blaikie8a40f702012-01-17 06:56:22 +00004223 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004224
John McCall8cb679e2010-11-15 09:13:47 +00004225 case Type::STK_Bool: // casting from bool is like casting from an integer
4226 case Type::STK_Integral:
4227 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004228 case Type::STK_CPointer:
4229 case Type::STK_ObjCObjectPointer:
4230 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004231 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004232 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004233 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004234 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004235 case Type::STK_Bool:
4236 return CK_IntegralToBoolean;
4237 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004238 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004239 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004240 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004241 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004242 Src = ImpCastExprToType(Src.take(),
4243 DestTy->castAs<ComplexType>()->getElementType(),
4244 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004245 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004246 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004247 Src = ImpCastExprToType(Src.take(),
4248 DestTy->castAs<ComplexType>()->getElementType(),
4249 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004250 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004251 case Type::STK_MemberPointer:
4252 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004253 }
David Blaikie8a40f702012-01-17 06:56:22 +00004254 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004255
John McCall8cb679e2010-11-15 09:13:47 +00004256 case Type::STK_Floating:
4257 switch (DestTy->getScalarTypeKind()) {
4258 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004259 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004260 case Type::STK_Bool:
4261 return CK_FloatingToBoolean;
4262 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004263 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004264 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004265 Src = ImpCastExprToType(Src.take(),
4266 DestTy->castAs<ComplexType>()->getElementType(),
4267 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004268 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004269 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004270 Src = ImpCastExprToType(Src.take(),
4271 DestTy->castAs<ComplexType>()->getElementType(),
4272 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004273 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004274 case Type::STK_CPointer:
4275 case Type::STK_ObjCObjectPointer:
4276 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004277 llvm_unreachable("valid float->pointer cast?");
4278 case Type::STK_MemberPointer:
4279 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004280 }
David Blaikie8a40f702012-01-17 06:56:22 +00004281 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004282
John McCall8cb679e2010-11-15 09:13:47 +00004283 case Type::STK_FloatingComplex:
4284 switch (DestTy->getScalarTypeKind()) {
4285 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004286 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004287 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004288 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004289 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004290 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4291 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004292 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004293 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004294 return CK_FloatingCast;
4295 }
John McCall8cb679e2010-11-15 09:13:47 +00004296 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004297 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004298 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004299 Src = ImpCastExprToType(Src.take(),
4300 SrcTy->castAs<ComplexType>()->getElementType(),
4301 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004302 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004303 case Type::STK_CPointer:
4304 case Type::STK_ObjCObjectPointer:
4305 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004306 llvm_unreachable("valid complex float->pointer cast?");
4307 case Type::STK_MemberPointer:
4308 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004309 }
David Blaikie8a40f702012-01-17 06:56:22 +00004310 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004311
John McCall8cb679e2010-11-15 09:13:47 +00004312 case Type::STK_IntegralComplex:
4313 switch (DestTy->getScalarTypeKind()) {
4314 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004315 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004316 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004317 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004318 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004319 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4320 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004321 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004322 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004323 return CK_IntegralCast;
4324 }
John McCall8cb679e2010-11-15 09:13:47 +00004325 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004326 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004327 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004328 Src = ImpCastExprToType(Src.take(),
4329 SrcTy->castAs<ComplexType>()->getElementType(),
4330 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004331 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004332 case Type::STK_CPointer:
4333 case Type::STK_ObjCObjectPointer:
4334 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004335 llvm_unreachable("valid complex int->pointer cast?");
4336 case Type::STK_MemberPointer:
4337 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004338 }
David Blaikie8a40f702012-01-17 06:56:22 +00004339 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004340 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004341
John McCalld7646252010-11-14 08:17:51 +00004342 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004343}
4344
Anders Carlsson525b76b2009-10-16 02:48:28 +00004345bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004346 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004347 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004348
Anders Carlssonde71adf2007-11-27 05:51:55 +00004349 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004350 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004351 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004352 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004353 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004354 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004355 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004356 } else
4357 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004358 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004359 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004360
John McCalle3027922010-08-25 11:45:40 +00004361 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004362 return false;
4363}
4364
John Wiegley01296292011-04-08 18:41:53 +00004365ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4366 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004367 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004368
Anders Carlsson43d70f82009-10-16 05:23:41 +00004369 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004370
Nate Begemanc8961a42009-06-27 22:05:55 +00004371 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4372 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004373 // In OpenCL, casts between vectors of different types are not allowed.
4374 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004375 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004376 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004377 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004378 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004379 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004380 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004381 return ExprError();
4382 }
John McCalle3027922010-08-25 11:45:40 +00004383 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004384 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004385 }
4386
Nate Begemanbd956c42009-06-28 02:36:38 +00004387 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004388 // conversion will take place first from scalar to elt type, and then
4389 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004390 if (SrcTy->isPointerType())
4391 return Diag(R.getBegin(),
4392 diag::err_invalid_conversion_between_vector_and_scalar)
4393 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004394
4395 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004396 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004397 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004398 if (CastExprRes.isInvalid())
4399 return ExprError();
4400 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004401
John McCalle3027922010-08-25 11:45:40 +00004402 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004403 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004404}
4405
John McCalldadc5752010-08-24 06:29:42 +00004406ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004407Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4408 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004409 SourceLocation RParenLoc, Expr *CastExpr) {
4410 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004411 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004412
Richard Trieuba63ce62011-09-09 01:45:06 +00004413 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004414 if (D.isInvalidType())
4415 return ExprError();
4416
David Blaikiebbafb8a2012-03-11 07:00:24 +00004417 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004418 // Check that there are no default arguments (C++ only).
4419 CheckExtraCXXDefaultArguments(D);
4420 }
4421
John McCall42856de2011-10-01 05:17:03 +00004422 checkUnusedDeclAttributes(D);
4423
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004424 QualType castType = castTInfo->getType();
4425 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004426
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004427 bool isVectorLiteral = false;
4428
4429 // Check for an altivec or OpenCL literal,
4430 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004431 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4432 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004433 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004434 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004435 if (PLE && PLE->getNumExprs() == 0) {
4436 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4437 return ExprError();
4438 }
4439 if (PE || PLE->getNumExprs() == 1) {
4440 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4441 if (!E->getType()->isVectorType())
4442 isVectorLiteral = true;
4443 }
4444 else
4445 isVectorLiteral = true;
4446 }
4447
4448 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4449 // then handle it as such.
4450 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004451 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004452
Nate Begeman5ec4b312009-08-10 23:49:36 +00004453 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004454 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4455 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004456 if (isa<ParenListExpr>(CastExpr)) {
4457 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004458 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004459 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004460 }
John McCallebe54742010-01-15 18:56:44 +00004461
Richard Trieuba63ce62011-09-09 01:45:06 +00004462 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004463}
4464
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004465ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4466 SourceLocation RParenLoc, Expr *E,
4467 TypeSourceInfo *TInfo) {
4468 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4469 "Expected paren or paren list expression");
4470
4471 Expr **exprs;
4472 unsigned numExprs;
4473 Expr *subExpr;
4474 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4475 exprs = PE->getExprs();
4476 numExprs = PE->getNumExprs();
4477 } else {
4478 subExpr = cast<ParenExpr>(E)->getSubExpr();
4479 exprs = &subExpr;
4480 numExprs = 1;
4481 }
4482
4483 QualType Ty = TInfo->getType();
4484 assert(Ty->isVectorType() && "Expected vector type");
4485
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004486 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004487 const VectorType *VTy = Ty->getAs<VectorType>();
4488 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4489
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004490 // '(...)' form of vector initialization in AltiVec: the number of
4491 // initializers must be one or must match the size of the vector.
4492 // If a single value is specified in the initializer then it will be
4493 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004494 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004495 // The number of initializers must be one or must match the size of the
4496 // vector. If a single value is specified in the initializer then it will
4497 // be replicated to all the components of the vector
4498 if (numExprs == 1) {
4499 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004500 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4501 if (Literal.isInvalid())
4502 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004503 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004504 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004505 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4506 }
4507 else if (numExprs < numElems) {
4508 Diag(E->getExprLoc(),
4509 diag::err_incorrect_number_of_vector_initializers);
4510 return ExprError();
4511 }
4512 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004513 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004514 }
Tanya Lattner83559382011-07-15 23:07:01 +00004515 else {
4516 // For OpenCL, when the number of initializers is a single value,
4517 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004518 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004519 VTy->getVectorKind() == VectorType::GenericVector &&
4520 numExprs == 1) {
4521 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004522 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4523 if (Literal.isInvalid())
4524 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004525 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004526 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004527 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4528 }
4529
Benjamin Kramer8001f742012-02-14 12:06:21 +00004530 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004531 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004532 // FIXME: This means that pretty-printing the final AST will produce curly
4533 // braces instead of the original commas.
4534 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4535 &initExprs[0],
4536 initExprs.size(), RParenLoc);
4537 initE->setType(Ty);
4538 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4539}
4540
Sebastian Redla9351792012-02-11 23:51:47 +00004541/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4542/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004543ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004544Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4545 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004546 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004547 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004548
John McCalldadc5752010-08-24 06:29:42 +00004549 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004550
Nate Begeman5ec4b312009-08-10 23:49:36 +00004551 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004552 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4553 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004554
John McCallb268a282010-08-23 23:25:46 +00004555 if (Result.isInvalid()) return ExprError();
4556
4557 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004558}
4559
Sebastian Redla9351792012-02-11 23:51:47 +00004560ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4561 SourceLocation R,
4562 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004563 unsigned nexprs = Val.size();
4564 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004565 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004566 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004567 return Owned(expr);
4568}
4569
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004570/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004571/// constant and the other is not a pointer. Returns true if a diagnostic is
4572/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004573bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004574 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004575 Expr *NullExpr = LHSExpr;
4576 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004577 Expr::NullPointerConstantKind NullKind =
4578 NullExpr->isNullPointerConstant(Context,
4579 Expr::NPC_ValueDependentIsNotNull);
4580
4581 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004582 NullExpr = RHSExpr;
4583 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004584 NullKind =
4585 NullExpr->isNullPointerConstant(Context,
4586 Expr::NPC_ValueDependentIsNotNull);
4587 }
4588
4589 if (NullKind == Expr::NPCK_NotNull)
4590 return false;
4591
4592 if (NullKind == Expr::NPCK_ZeroInteger) {
4593 // In this case, check to make sure that we got here from a "NULL"
4594 // string in the source code.
4595 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004596 SourceLocation loc = NullExpr->getExprLoc();
4597 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004598 return false;
4599 }
4600
4601 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4602 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4603 << NonPointerExpr->getType() << DiagType
4604 << NonPointerExpr->getSourceRange();
4605 return true;
4606}
4607
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004608/// \brief Return false if the condition expression is valid, true otherwise.
4609static bool checkCondition(Sema &S, Expr *Cond) {
4610 QualType CondTy = Cond->getType();
4611
4612 // C99 6.5.15p2
4613 if (CondTy->isScalarType()) return false;
4614
4615 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004616 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004617 return false;
4618
4619 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004620 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004621 diag::err_typecheck_cond_expect_scalar :
4622 diag::err_typecheck_cond_expect_scalar_or_vector)
4623 << CondTy;
4624 return true;
4625}
4626
4627/// \brief Return false if the two expressions can be converted to a vector,
4628/// true otherwise
4629static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4630 ExprResult &RHS,
4631 QualType CondTy) {
4632 // Both operands should be of scalar type.
4633 if (!LHS.get()->getType()->isScalarType()) {
4634 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4635 << CondTy;
4636 return true;
4637 }
4638 if (!RHS.get()->getType()->isScalarType()) {
4639 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4640 << CondTy;
4641 return true;
4642 }
4643
4644 // Implicity convert these scalars to the type of the condition.
4645 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4646 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4647 return false;
4648}
4649
4650/// \brief Handle when one or both operands are void type.
4651static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4652 ExprResult &RHS) {
4653 Expr *LHSExpr = LHS.get();
4654 Expr *RHSExpr = RHS.get();
4655
4656 if (!LHSExpr->getType()->isVoidType())
4657 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4658 << RHSExpr->getSourceRange();
4659 if (!RHSExpr->getType()->isVoidType())
4660 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4661 << LHSExpr->getSourceRange();
4662 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4663 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4664 return S.Context.VoidTy;
4665}
4666
4667/// \brief Return false if the NullExpr can be promoted to PointerTy,
4668/// true otherwise.
4669static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4670 QualType PointerTy) {
4671 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4672 !NullExpr.get()->isNullPointerConstant(S.Context,
4673 Expr::NPC_ValueDependentIsNull))
4674 return true;
4675
4676 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4677 return false;
4678}
4679
4680/// \brief Checks compatibility between two pointers and return the resulting
4681/// type.
4682static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4683 ExprResult &RHS,
4684 SourceLocation Loc) {
4685 QualType LHSTy = LHS.get()->getType();
4686 QualType RHSTy = RHS.get()->getType();
4687
4688 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4689 // Two identical pointers types are always compatible.
4690 return LHSTy;
4691 }
4692
4693 QualType lhptee, rhptee;
4694
4695 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004696 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4697 lhptee = LHSBTy->getPointeeType();
4698 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004699 } else {
John McCall9320b872011-09-09 05:25:32 +00004700 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4701 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004702 }
4703
Eli Friedman57a75392012-04-05 22:30:04 +00004704 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4705 // differently qualified versions of compatible types, the result type is
4706 // a pointer to an appropriately qualified version of the composite
4707 // type.
4708
4709 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4710 // clause doesn't make sense for our extensions. E.g. address space 2 should
4711 // be incompatible with address space 3: they may live on different devices or
4712 // anything.
4713 Qualifiers lhQual = lhptee.getQualifiers();
4714 Qualifiers rhQual = rhptee.getQualifiers();
4715
4716 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4717 lhQual.removeCVRQualifiers();
4718 rhQual.removeCVRQualifiers();
4719
4720 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4721 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4722
4723 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4724
4725 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004726 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4727 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4728 << RHS.get()->getSourceRange();
4729 // In this situation, we assume void* type. No especially good
4730 // reason, but this is what gcc does, and we do have to pick
4731 // to get a consistent AST.
4732 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4733 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4734 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4735 return incompatTy;
4736 }
4737
4738 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004739 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4740 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004741
Eli Friedman57a75392012-04-05 22:30:04 +00004742 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4743 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4744 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004745}
4746
4747/// \brief Return the resulting type when the operands are both block pointers.
4748static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4749 ExprResult &LHS,
4750 ExprResult &RHS,
4751 SourceLocation Loc) {
4752 QualType LHSTy = LHS.get()->getType();
4753 QualType RHSTy = RHS.get()->getType();
4754
4755 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4756 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4757 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4758 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4759 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4760 return destType;
4761 }
4762 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4763 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4764 << RHS.get()->getSourceRange();
4765 return QualType();
4766 }
4767
4768 // We have 2 block pointer types.
4769 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4770}
4771
4772/// \brief Return the resulting type when the operands are both pointers.
4773static QualType
4774checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4775 ExprResult &RHS,
4776 SourceLocation Loc) {
4777 // get the pointer types
4778 QualType LHSTy = LHS.get()->getType();
4779 QualType RHSTy = RHS.get()->getType();
4780
4781 // get the "pointed to" types
4782 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4783 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4784
4785 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4786 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4787 // Figure out necessary qualifiers (C99 6.5.15p6)
4788 QualType destPointee
4789 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4790 QualType destType = S.Context.getPointerType(destPointee);
4791 // Add qualifiers if necessary.
4792 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4793 // Promote to void*.
4794 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4795 return destType;
4796 }
4797 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4798 QualType destPointee
4799 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4800 QualType destType = S.Context.getPointerType(destPointee);
4801 // Add qualifiers if necessary.
4802 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4803 // Promote to void*.
4804 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4805 return destType;
4806 }
4807
4808 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4809}
4810
4811/// \brief Return false if the first expression is not an integer and the second
4812/// expression is not a pointer, true otherwise.
4813static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4814 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004815 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004816 if (!PointerExpr->getType()->isPointerType() ||
4817 !Int.get()->getType()->isIntegerType())
4818 return false;
4819
Richard Trieuba63ce62011-09-09 01:45:06 +00004820 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4821 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004822
4823 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4824 << Expr1->getType() << Expr2->getType()
4825 << Expr1->getSourceRange() << Expr2->getSourceRange();
4826 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4827 CK_IntegralToPointer);
4828 return true;
4829}
4830
Richard Trieud33e46e2011-09-06 20:06:39 +00004831/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4832/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004833/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004834QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4835 ExprResult &RHS, ExprValueKind &VK,
4836 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004837 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004838
Richard Trieud33e46e2011-09-06 20:06:39 +00004839 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4840 if (!LHSResult.isUsable()) return QualType();
4841 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004842
Richard Trieud33e46e2011-09-06 20:06:39 +00004843 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4844 if (!RHSResult.isUsable()) return QualType();
4845 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004846
Sebastian Redl1a99f442009-04-16 17:51:27 +00004847 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004848 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004849 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004850
4851 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004852 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004853
John Wiegley01296292011-04-08 18:41:53 +00004854 Cond = UsualUnaryConversions(Cond.take());
4855 if (Cond.isInvalid())
4856 return QualType();
4857 LHS = UsualUnaryConversions(LHS.take());
4858 if (LHS.isInvalid())
4859 return QualType();
4860 RHS = UsualUnaryConversions(RHS.take());
4861 if (RHS.isInvalid())
4862 return QualType();
4863
4864 QualType CondTy = Cond.get()->getType();
4865 QualType LHSTy = LHS.get()->getType();
4866 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004867
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004868 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004869 if (checkCondition(*this, Cond.get()))
4870 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004871
Chris Lattnere2949f42008-01-06 22:42:25 +00004872 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004873 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004874 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004875
Nate Begemanabb5a732010-09-20 22:41:17 +00004876 // OpenCL: If the condition is a vector, and both operands are scalar,
4877 // attempt to implicity convert them to the vector type to act like the
4878 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004879 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004880 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004881 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004882
Chris Lattnere2949f42008-01-06 22:42:25 +00004883 // If both operands have arithmetic type, do the usual arithmetic conversions
4884 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004885 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4886 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004887 if (LHS.isInvalid() || RHS.isInvalid())
4888 return QualType();
4889 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004890 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004891
Chris Lattnere2949f42008-01-06 22:42:25 +00004892 // If both operands are the same structure or union type, the result is that
4893 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004894 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4895 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004896 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004897 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004898 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004899 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004900 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004901 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004902
Chris Lattnere2949f42008-01-06 22:42:25 +00004903 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004904 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004905 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004906 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004907 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004908
Steve Naroff039ad3c2008-01-08 01:11:38 +00004909 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4910 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004911 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4912 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004913
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004914 // All objective-c pointer type analysis is done here.
4915 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4916 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004917 if (LHS.isInvalid() || RHS.isInvalid())
4918 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004919 if (!compositeType.isNull())
4920 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004921
4922
Steve Naroff05efa972009-07-01 14:36:47 +00004923 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004924 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4925 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4926 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004927
Steve Naroff05efa972009-07-01 14:36:47 +00004928 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004929 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4930 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4931 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004932
John McCalle84af4e2010-11-13 01:35:44 +00004933 // GCC compatibility: soften pointer/integer mismatch. Note that
4934 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004935 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4936 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004937 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004938 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4939 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004940 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004941
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004942 // Emit a better diagnostic if one of the expressions is a null pointer
4943 // constant and the other is not a pointer type. In this case, the user most
4944 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004945 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004946 return QualType();
4947
Chris Lattnere2949f42008-01-06 22:42:25 +00004948 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004949 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004950 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4951 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004952 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004953}
4954
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004955/// FindCompositeObjCPointerType - Helper method to find composite type of
4956/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004957QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004958 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004959 QualType LHSTy = LHS.get()->getType();
4960 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004961
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004962 // Handle things like Class and struct objc_class*. Here we case the result
4963 // to the pseudo-builtin, because that will be implicitly cast back to the
4964 // redefinition type if an attempt is made to access its fields.
4965 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004966 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004967 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004968 return LHSTy;
4969 }
4970 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004971 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004972 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004973 return RHSTy;
4974 }
4975 // And the same for struct objc_object* / id
4976 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004977 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004978 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004979 return LHSTy;
4980 }
4981 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004982 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004983 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004984 return RHSTy;
4985 }
4986 // And the same for struct objc_selector* / SEL
4987 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004988 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004989 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004990 return LHSTy;
4991 }
4992 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004993 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004994 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004995 return RHSTy;
4996 }
4997 // Check constraints for Objective-C object pointers types.
4998 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004999
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005000 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5001 // Two identical object pointer types are always compatible.
5002 return LHSTy;
5003 }
John McCall9320b872011-09-09 05:25:32 +00005004 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5005 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005006 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005007
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005008 // If both operands are interfaces and either operand can be
5009 // assigned to the other, use that type as the composite
5010 // type. This allows
5011 // xxx ? (A*) a : (B*) b
5012 // where B is a subclass of A.
5013 //
5014 // Additionally, as for assignment, if either type is 'id'
5015 // allow silent coercion. Finally, if the types are
5016 // incompatible then make sure to use 'id' as the composite
5017 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005018
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005019 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5020 // It could return the composite type.
5021 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5022 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5023 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5024 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5025 } else if ((LHSTy->isObjCQualifiedIdType() ||
5026 RHSTy->isObjCQualifiedIdType()) &&
5027 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5028 // Need to handle "id<xx>" explicitly.
5029 // GCC allows qualified id and any Objective-C type to devolve to
5030 // id. Currently localizing to here until clear this should be
5031 // part of ObjCQualifiedIdTypesAreCompatible.
5032 compositeType = Context.getObjCIdType();
5033 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5034 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005035 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005036 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5037 ;
5038 else {
5039 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5040 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005042 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005043 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5044 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005045 return incompatTy;
5046 }
5047 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005048 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5049 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005050 return compositeType;
5051 }
5052 // Check Objective-C object pointer types and 'void *'
5053 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005054 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005055 // ARC forbids the implicit conversion of object pointers to 'void *',
5056 // so these types are not compatible.
5057 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5059 LHS = RHS = true;
5060 return QualType();
5061 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005062 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5063 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5064 QualType destPointee
5065 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5066 QualType destType = Context.getPointerType(destPointee);
5067 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005068 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005069 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005070 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005071 return destType;
5072 }
5073 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005074 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005075 // ARC forbids the implicit conversion of object pointers to 'void *',
5076 // so these types are not compatible.
5077 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5079 LHS = RHS = true;
5080 return QualType();
5081 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005082 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5083 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5084 QualType destPointee
5085 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5086 QualType destType = Context.getPointerType(destPointee);
5087 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005088 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005089 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005090 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005091 return destType;
5092 }
5093 return QualType();
5094}
5095
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005096/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005097/// ParenRange in parentheses.
5098static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005099 const PartialDiagnostic &Note,
5100 SourceRange ParenRange) {
5101 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5102 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5103 EndLoc.isValid()) {
5104 Self.Diag(Loc, Note)
5105 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5106 << FixItHint::CreateInsertion(EndLoc, ")");
5107 } else {
5108 // We can't display the parentheses, so just show the bare note.
5109 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005110 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005111}
5112
5113static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5114 return Opc >= BO_Mul && Opc <= BO_Shr;
5115}
5116
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005117/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5118/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005119/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5120/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005121static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005122 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005123 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5124 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005125 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005126 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005127
5128 // Built-in binary operator.
5129 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5130 if (IsArithmeticOp(OP->getOpcode())) {
5131 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005132 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005133 return true;
5134 }
5135 }
5136
5137 // Overloaded operator.
5138 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5139 if (Call->getNumArgs() != 2)
5140 return false;
5141
5142 // Make sure this is really a binary operator that is safe to pass into
5143 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5144 OverloadedOperatorKind OO = Call->getOperator();
5145 if (OO < OO_Plus || OO > OO_Arrow)
5146 return false;
5147
5148 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5149 if (IsArithmeticOp(OpKind)) {
5150 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005151 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005152 return true;
5153 }
5154 }
5155
5156 return false;
5157}
5158
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005159static bool IsLogicOp(BinaryOperatorKind Opc) {
5160 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5161}
5162
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005163/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5164/// or is a logical expression such as (x==y) which has int type, but is
5165/// commonly interpreted as boolean.
5166static bool ExprLooksBoolean(Expr *E) {
5167 E = E->IgnoreParenImpCasts();
5168
5169 if (E->getType()->isBooleanType())
5170 return true;
5171 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5172 return IsLogicOp(OP->getOpcode());
5173 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5174 return OP->getOpcode() == UO_LNot;
5175
5176 return false;
5177}
5178
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005179/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5180/// and binary operator are mixed in a way that suggests the programmer assumed
5181/// the conditional operator has higher precedence, for example:
5182/// "int x = a + someBinaryCondition ? 1 : 2".
5183static void DiagnoseConditionalPrecedence(Sema &Self,
5184 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005185 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005186 Expr *LHSExpr,
5187 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005188 BinaryOperatorKind CondOpcode;
5189 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005190
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005191 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005192 return;
5193 if (!ExprLooksBoolean(CondRHS))
5194 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005195
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005196 // The condition is an arithmetic binary expression, with a right-
5197 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005198
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005199 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005200 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005201 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005202
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005203 SuggestParentheses(Self, OpLoc,
5204 Self.PDiag(diag::note_precedence_conditional_silence)
5205 << BinaryOperator::getOpcodeStr(CondOpcode),
5206 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005207
5208 SuggestParentheses(Self, OpLoc,
5209 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005210 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005211}
5212
Steve Naroff83895f72007-09-16 03:34:24 +00005213/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005214/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005215ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005216 SourceLocation ColonLoc,
5217 Expr *CondExpr, Expr *LHSExpr,
5218 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005219 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5220 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005221 OpaqueValueExpr *opaqueValue = 0;
5222 Expr *commonExpr = 0;
5223 if (LHSExpr == 0) {
5224 commonExpr = CondExpr;
5225
5226 // We usually want to apply unary conversions *before* saving, except
5227 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005228 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005229 && !commonExpr->isTypeDependent()
5230 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5231 && commonExpr->isGLValue()
5232 && commonExpr->isOrdinaryOrBitFieldObject()
5233 && RHSExpr->isOrdinaryOrBitFieldObject()
5234 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005235 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5236 if (commonRes.isInvalid())
5237 return ExprError();
5238 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005239 }
5240
5241 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5242 commonExpr->getType(),
5243 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005244 commonExpr->getObjectKind(),
5245 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005246 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005247 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005248
John McCall7decc9e2010-11-18 06:31:45 +00005249 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005250 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005251 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5252 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005253 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005254 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5255 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005256 return ExprError();
5257
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005258 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5259 RHS.get());
5260
John McCallc07a0c72011-02-17 10:25:35 +00005261 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005262 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5263 LHS.take(), ColonLoc,
5264 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005265
5266 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005267 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005268 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5269 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005270}
5271
John McCallaba90822011-01-31 23:13:11 +00005272// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005273// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005274// routine is it effectively iqnores the qualifiers on the top level pointee.
5275// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5276// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005277static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005278checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5279 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5280 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005281
Steve Naroff1f4d7272007-05-11 04:00:31 +00005282 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005283 const Type *lhptee, *rhptee;
5284 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005285 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5286 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005287
John McCallaba90822011-01-31 23:13:11 +00005288 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005289
5290 // C99 6.5.16.1p1: This following citation is common to constraints
5291 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5292 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005293 Qualifiers lq;
5294
John McCall31168b02011-06-15 23:02:42 +00005295 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5296 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5297 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5298 // Ignore lifetime for further calculation.
5299 lhq.removeObjCLifetime();
5300 rhq.removeObjCLifetime();
5301 }
5302
John McCall4fff8f62011-02-01 00:10:29 +00005303 if (!lhq.compatiblyIncludes(rhq)) {
5304 // Treat address-space mismatches as fatal. TODO: address subspaces
5305 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5306 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5307
John McCall31168b02011-06-15 23:02:42 +00005308 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005309 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005310 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005311 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005312 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005313 && (lhptee->isVoidType() || rhptee->isVoidType()))
5314 ; // keep old
5315
John McCall31168b02011-06-15 23:02:42 +00005316 // Treat lifetime mismatches as fatal.
5317 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5318 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5319
John McCall4fff8f62011-02-01 00:10:29 +00005320 // For GCC compatibility, other qualifier mismatches are treated
5321 // as still compatible in C.
5322 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5323 }
Steve Naroff3f597292007-05-11 22:18:03 +00005324
Mike Stump4e1f26a2009-02-19 03:04:26 +00005325 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5326 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005327 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005328 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005329 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005330 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005331
Chris Lattner0a788432008-01-03 22:56:36 +00005332 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005333 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005334 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005335 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005336
Chris Lattner0a788432008-01-03 22:56:36 +00005337 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005338 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005339 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005340
5341 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005342 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005343 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005344 }
John McCall4fff8f62011-02-01 00:10:29 +00005345
Mike Stump4e1f26a2009-02-19 03:04:26 +00005346 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005347 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005348 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5349 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005350 // Check if the pointee types are compatible ignoring the sign.
5351 // We explicitly check for char so that we catch "char" vs
5352 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005353 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005354 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005355 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005356 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005357
Chris Lattnerec3a1562009-10-17 20:33:28 +00005358 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005359 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005360 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005361 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005362
John McCall4fff8f62011-02-01 00:10:29 +00005363 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005364 // Types are compatible ignoring the sign. Qualifier incompatibility
5365 // takes priority over sign incompatibility because the sign
5366 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005367 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005368 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005369
John McCallaba90822011-01-31 23:13:11 +00005370 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005371 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005372
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005373 // If we are a multi-level pointer, it's possible that our issue is simply
5374 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5375 // the eventual target type is the same and the pointers have the same
5376 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005377 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005378 do {
John McCall4fff8f62011-02-01 00:10:29 +00005379 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5380 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005381 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005382
John McCall4fff8f62011-02-01 00:10:29 +00005383 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005384 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005385 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005386
Eli Friedman80160bd2009-03-22 23:59:44 +00005387 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005388 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005389 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005390 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005391 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5392 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005393 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005394}
5395
John McCallaba90822011-01-31 23:13:11 +00005396/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005397/// block pointer types are compatible or whether a block and normal pointer
5398/// are compatible. It is more restrict than comparing two function pointer
5399// types.
John McCallaba90822011-01-31 23:13:11 +00005400static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005401checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5402 QualType RHSType) {
5403 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5404 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005405
Steve Naroff081c7422008-09-04 15:10:53 +00005406 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005407
Steve Naroff081c7422008-09-04 15:10:53 +00005408 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005409 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5410 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005411
John McCallaba90822011-01-31 23:13:11 +00005412 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005413 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005414 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005415
John McCallaba90822011-01-31 23:13:11 +00005416 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005417
Steve Naroff081c7422008-09-04 15:10:53 +00005418 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005419 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5420 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005421
Richard Trieua871b972011-09-06 20:21:22 +00005422 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005423 return Sema::IncompatibleBlockPointer;
5424
Steve Naroff081c7422008-09-04 15:10:53 +00005425 return ConvTy;
5426}
5427
John McCallaba90822011-01-31 23:13:11 +00005428/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005429/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005430static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005431checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5432 QualType RHSType) {
5433 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5434 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005435
Richard Trieua871b972011-09-06 20:21:22 +00005436 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005437 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005438 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5439 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005440 return Sema::IncompatiblePointer;
5441 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005442 }
Richard Trieua871b972011-09-06 20:21:22 +00005443 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005444 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5445 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005446 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005447 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005448 }
Richard Trieua871b972011-09-06 20:21:22 +00005449 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5450 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005451
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005452 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5453 // make an exception for id<P>
5454 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005455 return Sema::CompatiblePointerDiscardsQualifiers;
5456
Richard Trieua871b972011-09-06 20:21:22 +00005457 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005458 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005459 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005460 return Sema::IncompatibleObjCQualifiedId;
5461 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005462}
5463
John McCall29600e12010-11-16 02:32:08 +00005464Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005465Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005466 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005467 // Fake up an opaque expression. We don't actually care about what
5468 // cast operations are required, so if CheckAssignmentConstraints
5469 // adds casts to this they'll be wasted, but fortunately that doesn't
5470 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005471 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5472 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005473 CastKind K = CK_Invalid;
5474
Richard Trieua871b972011-09-06 20:21:22 +00005475 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005476}
5477
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5479/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005480/// pointers. Here are some objectionable examples that GCC considers warnings:
5481///
5482/// int a, *pint;
5483/// short *pshort;
5484/// struct foo *pfoo;
5485///
5486/// pint = pshort; // warning: assignment from incompatible pointer type
5487/// a = pint; // warning: assignment makes integer from pointer without a cast
5488/// pint = a; // warning: assignment makes pointer from integer without a cast
5489/// pint = pfoo; // warning: assignment from incompatible pointer type
5490///
5491/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005492/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005493///
John McCall8cb679e2010-11-15 09:13:47 +00005494/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005495Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005496Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005497 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005498 QualType RHSType = RHS.get()->getType();
5499 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005500
Chris Lattnera52c2f22008-01-04 23:18:45 +00005501 // Get canonical types. We're not formatting these types, just comparing
5502 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005503 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5504 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005505
Eli Friedman0dfb8892011-10-06 23:00:33 +00005506
John McCalle5255932011-01-31 22:28:28 +00005507 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005508 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005509 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005510 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005511 }
5512
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005513 // If we have an atomic type, try a non-atomic assignment, then just add an
5514 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005515 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005516 Sema::AssignConvertType result =
5517 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5518 if (result != Compatible)
5519 return result;
5520 if (Kind != CK_NoOp)
5521 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5522 Kind = CK_NonAtomicToAtomic;
5523 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005524 }
5525
Douglas Gregor6b754842008-10-28 00:22:11 +00005526 // If the left-hand side is a reference type, then we are in a
5527 // (rare!) case where we've allowed the use of references in C,
5528 // e.g., as a parameter type in a built-in function. In this case,
5529 // just make sure that the type referenced is compatible with the
5530 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005531 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005532 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005533 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5534 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005535 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005536 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005537 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005538 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005539 }
John McCalle5255932011-01-31 22:28:28 +00005540
Nate Begemanbd956c42009-06-28 02:36:38 +00005541 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5542 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005543 if (LHSType->isExtVectorType()) {
5544 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005545 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005546 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005547 // CK_VectorSplat does T -> vector T, so first cast to the
5548 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005549 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5550 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005551 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005552 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005553 }
5554 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005555 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005556 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005557 }
Mike Stump11289f42009-09-09 15:08:12 +00005558
John McCalle5255932011-01-31 22:28:28 +00005559 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005560 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5561 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005562 // Allow assignments of an AltiVec vector type to an equivalent GCC
5563 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005564 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005565 Kind = CK_BitCast;
5566 return Compatible;
5567 }
5568
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005569 // If we are allowing lax vector conversions, and LHS and RHS are both
5570 // vectors, the total size only needs to be the same. This is a bitcast;
5571 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005572 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005573 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005574 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005575 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005576 }
Chris Lattner881a2122008-01-04 23:32:24 +00005577 }
5578 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005579 }
Eli Friedman3360d892008-05-30 18:07:22 +00005580
John McCalle5255932011-01-31 22:28:28 +00005581 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005582 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005583 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005584 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005585 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005586 }
Eli Friedman3360d892008-05-30 18:07:22 +00005587
John McCalle5255932011-01-31 22:28:28 +00005588 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005589 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005590 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005591 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005592 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005593 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005594 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005595
John McCalle5255932011-01-31 22:28:28 +00005596 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005597 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005598 Kind = CK_IntegralToPointer; // FIXME: null?
5599 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005600 }
John McCalle5255932011-01-31 22:28:28 +00005601
5602 // C pointers are not compatible with ObjC object pointers,
5603 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005604 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005605 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005606 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005607 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005608 return Compatible;
5609 }
5610
5611 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005612 if (RHSType->isObjCClassType() &&
5613 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005614 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005615 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005616 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005617 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005618
John McCalle5255932011-01-31 22:28:28 +00005619 Kind = CK_BitCast;
5620 return IncompatiblePointer;
5621 }
5622
5623 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005624 if (RHSType->getAs<BlockPointerType>()) {
5625 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005626 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005627 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005628 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005629 }
John McCalle5255932011-01-31 22:28:28 +00005630
Steve Naroff081c7422008-09-04 15:10:53 +00005631 return Incompatible;
5632 }
5633
John McCalle5255932011-01-31 22:28:28 +00005634 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005635 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005636 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005637 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005638 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005639 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005640 }
5641
5642 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005643 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005644 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005645 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005646 }
5647
John McCalle5255932011-01-31 22:28:28 +00005648 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005649 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005650 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005651 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005652 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005653
John McCalle5255932011-01-31 22:28:28 +00005654 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005655 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005656 if (RHSPT->getPointeeType()->isVoidType()) {
5657 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005658 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005659 }
John McCall8cb679e2010-11-15 09:13:47 +00005660
Chris Lattnera52c2f22008-01-04 23:18:45 +00005661 return Incompatible;
5662 }
5663
John McCalle5255932011-01-31 22:28:28 +00005664 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005665 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005666 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005667 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005668 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005669 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005670 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005671 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005672 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005673 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005674 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005675 return result;
John McCalle5255932011-01-31 22:28:28 +00005676 }
5677
5678 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005679 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005680 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005681 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005682 }
5683
John McCalle5255932011-01-31 22:28:28 +00005684 // In general, C pointers are not compatible with ObjC object pointers,
5685 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005686 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005687 Kind = CK_CPointerToObjCPointerCast;
5688
John McCalle5255932011-01-31 22:28:28 +00005689 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005690 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005691 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005692 }
5693
5694 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005695 if (LHSType->isObjCClassType() &&
5696 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005697 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005698 return Compatible;
5699 }
5700
Steve Naroffaccc4882009-07-20 17:56:53 +00005701 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005702 }
John McCalle5255932011-01-31 22:28:28 +00005703
5704 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005705 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005706 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005707 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005708 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005709 }
5710
Steve Naroff7cae42b2009-07-10 23:34:53 +00005711 return Incompatible;
5712 }
John McCalle5255932011-01-31 22:28:28 +00005713
5714 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005715 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005716 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005717 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005718 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005719 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005720 }
Eli Friedman3360d892008-05-30 18:07:22 +00005721
John McCalle5255932011-01-31 22:28:28 +00005722 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005723 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005724 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005725 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005726 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005727
Chris Lattnera52c2f22008-01-04 23:18:45 +00005728 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005729 }
John McCalle5255932011-01-31 22:28:28 +00005730
5731 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005732 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005733 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005734 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005735 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005736 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005737 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005738
John McCalle5255932011-01-31 22:28:28 +00005739 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005740 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005741 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005742 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005743 }
5744
Steve Naroff7cae42b2009-07-10 23:34:53 +00005745 return Incompatible;
5746 }
Eli Friedman3360d892008-05-30 18:07:22 +00005747
John McCalle5255932011-01-31 22:28:28 +00005748 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005749 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5750 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005751 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005752 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005753 }
Bill Wendling216423b2007-05-30 06:30:29 +00005754 }
John McCalle5255932011-01-31 22:28:28 +00005755
Steve Naroff98cf3e92007-06-06 18:38:38 +00005756 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005757}
5758
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005759/// \brief Constructs a transparent union from an expression that is
5760/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005761static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5762 ExprResult &EResult, QualType UnionType,
5763 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005764 // Build an initializer list that designates the appropriate member
5765 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005766 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005767 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005768 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005769 SourceLocation());
5770 Initializer->setType(UnionType);
5771 Initializer->setInitializedFieldInUnion(Field);
5772
5773 // Build a compound literal constructing a value of the transparent
5774 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005775 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005776 EResult = S.Owned(
5777 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5778 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005779}
5780
5781Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005782Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005783 ExprResult &RHS) {
5784 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005785
Mike Stump11289f42009-09-09 15:08:12 +00005786 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005787 // transparent_union GCC extension.
5788 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005789 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005790 return Incompatible;
5791
5792 // The field to initialize within the transparent union.
5793 RecordDecl *UD = UT->getDecl();
5794 FieldDecl *InitField = 0;
5795 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005796 for (RecordDecl::field_iterator it = UD->field_begin(),
5797 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005798 it != itend; ++it) {
5799 if (it->getType()->isPointerType()) {
5800 // If the transparent union contains a pointer type, we allow:
5801 // 1) void pointer
5802 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005803 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005804 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005805 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005806 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005807 break;
5808 }
Mike Stump11289f42009-09-09 15:08:12 +00005809
Richard Trieueb299142011-09-06 20:40:12 +00005810 if (RHS.get()->isNullPointerConstant(Context,
5811 Expr::NPC_ValueDependentIsNull)) {
5812 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5813 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005814 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005815 break;
5816 }
5817 }
5818
John McCall8cb679e2010-11-15 09:13:47 +00005819 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005820 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005821 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005822 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005823 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005824 break;
5825 }
5826 }
5827
5828 if (!InitField)
5829 return Incompatible;
5830
Richard Trieueb299142011-09-06 20:40:12 +00005831 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005832 return Compatible;
5833}
5834
Chris Lattner9bad62c2008-01-04 18:04:52 +00005835Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005836Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5837 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005838 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005839 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005840 // C++ 5.17p3: If the left operand is not of class type, the
5841 // expression is implicitly converted (C++ 4) to the
5842 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005843 ExprResult Res;
5844 if (Diagnose) {
5845 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5846 AA_Assigning);
5847 } else {
5848 ImplicitConversionSequence ICS =
5849 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5850 /*SuppressUserConversions=*/false,
5851 /*AllowExplicit=*/false,
5852 /*InOverloadResolution=*/false,
5853 /*CStyle=*/false,
5854 /*AllowObjCWritebackConversion=*/false);
5855 if (ICS.isFailure())
5856 return Incompatible;
5857 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5858 ICS, AA_Assigning);
5859 }
John Wiegley01296292011-04-08 18:41:53 +00005860 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005861 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005862 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005863 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005864 !CheckObjCARCUnavailableWeakConversion(LHSType,
5865 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005866 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005867 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005868 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005869 }
5870
5871 // FIXME: Currently, we fall through and treat C++ classes like C
5872 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005873 // FIXME: We also fall through for atomics; not sure what should
5874 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005875 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005876
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005877 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5878 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005879 if ((LHSType->isPointerType() ||
5880 LHSType->isObjCObjectPointerType() ||
5881 LHSType->isBlockPointerType())
5882 && RHS.get()->isNullPointerConstant(Context,
5883 Expr::NPC_ValueDependentIsNull)) {
5884 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005885 return Compatible;
5886 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005887
Chris Lattnere6dcd502007-10-16 02:55:40 +00005888 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005889 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005890 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005891 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005892 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005893 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005894 if (!LHSType->isReferenceType()) {
5895 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5896 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005897 return Incompatible;
5898 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005899
John McCall8cb679e2010-11-15 09:13:47 +00005900 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005901 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005902 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005903
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005904 // C99 6.5.16.1p2: The value of the right operand is converted to the
5905 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005906 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5907 // so that we can use references in built-in functions even in C.
5908 // The getNonReferenceType() call makes sure that the resulting expression
5909 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005910 if (result != Incompatible && RHS.get()->getType() != LHSType)
5911 RHS = ImpCastExprToType(RHS.take(),
5912 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005913 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005914}
5915
Richard Trieueb299142011-09-06 20:40:12 +00005916QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5917 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005918 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005919 << LHS.get()->getType() << RHS.get()->getType()
5920 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005921 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005922}
5923
Richard Trieu859d23f2011-09-06 21:01:04 +00005924QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005925 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005926 if (!IsCompAssign) {
5927 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5928 if (LHS.isInvalid())
5929 return QualType();
5930 }
5931 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5932 if (RHS.isInvalid())
5933 return QualType();
5934
Mike Stump4e1f26a2009-02-19 03:04:26 +00005935 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005936 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005937 QualType LHSType =
5938 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5939 QualType RHSType =
5940 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005941
Nate Begeman191a6b12008-07-14 18:02:46 +00005942 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005943 if (LHSType == RHSType)
5944 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005945
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005946 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005947 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5948 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5949 if (LHSType->isExtVectorType()) {
5950 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5951 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005952 }
5953
Richard Trieuba63ce62011-09-09 01:45:06 +00005954 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005955 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5956 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005957 }
5958
David Blaikiebbafb8a2012-03-11 07:00:24 +00005959 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005960 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005961 // If we are allowing lax vector conversions, and LHS and RHS are both
5962 // vectors, the total size only needs to be the same. This is a
5963 // bitcast; no bits are changed but the result type is different.
5964 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005965 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5966 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005967 }
5968
Nate Begemanbd956c42009-06-28 02:36:38 +00005969 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5970 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5971 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005972 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005973 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005974 std::swap(RHS, LHS);
5975 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005976 }
Mike Stump11289f42009-09-09 15:08:12 +00005977
Nate Begeman886448d2009-06-28 19:12:57 +00005978 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005979 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005980 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005981 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5982 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005983 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005984 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005985 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005986 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5987 if (swapped) std::swap(RHS, LHS);
5988 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005989 }
5990 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005991 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5992 RHSType->isRealFloatingType()) {
5993 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005994 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005995 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005996 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005997 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5998 if (swapped) std::swap(RHS, LHS);
5999 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006000 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006001 }
6002 }
Mike Stump11289f42009-09-09 15:08:12 +00006003
Nate Begeman886448d2009-06-28 19:12:57 +00006004 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006005 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006006 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006007 << LHS.get()->getType() << RHS.get()->getType()
6008 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006009 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006010}
6011
Richard Trieuf8916e12011-09-16 00:53:10 +00006012// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6013// expression. These are mainly cases where the null pointer is used as an
6014// integer instead of a pointer.
6015static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6016 SourceLocation Loc, bool IsCompare) {
6017 // The canonical way to check for a GNU null is with isNullPointerConstant,
6018 // but we use a bit of a hack here for speed; this is a relatively
6019 // hot path, and isNullPointerConstant is slow.
6020 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6021 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6022
6023 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6024
6025 // Avoid analyzing cases where the result will either be invalid (and
6026 // diagnosed as such) or entirely valid and not something to warn about.
6027 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6028 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6029 return;
6030
6031 // Comparison operations would not make sense with a null pointer no matter
6032 // what the other expression is.
6033 if (!IsCompare) {
6034 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6035 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6036 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6037 return;
6038 }
6039
6040 // The rest of the operations only make sense with a null pointer
6041 // if the other expression is a pointer.
6042 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6043 NonNullType->canDecayToPointerType())
6044 return;
6045
6046 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6047 << LHSNull /* LHS is NULL */ << NonNullType
6048 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6049}
6050
Richard Trieu859d23f2011-09-06 21:01:04 +00006051QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006052 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006053 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006054 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6055
Richard Trieu859d23f2011-09-06 21:01:04 +00006056 if (LHS.get()->getType()->isVectorType() ||
6057 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006058 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006059
Richard Trieuba63ce62011-09-09 01:45:06 +00006060 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006061 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006062 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006063
David Chisnallfa35df62012-01-16 17:27:18 +00006064
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006065 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006066 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006067
Chris Lattnerfaa54172010-01-12 21:23:57 +00006068 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006069 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006070 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006071 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006072 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6073 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006074
Chris Lattnerfaa54172010-01-12 21:23:57 +00006075 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006076}
6077
Chris Lattnerfaa54172010-01-12 21:23:57 +00006078QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006079 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006080 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6081
Richard Trieu859d23f2011-09-06 21:01:04 +00006082 if (LHS.get()->getType()->isVectorType() ||
6083 RHS.get()->getType()->isVectorType()) {
6084 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6085 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006086 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006087 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006088 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006089
Richard Trieuba63ce62011-09-09 01:45:06 +00006090 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006091 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006092 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006093
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006094 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006095 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006096
Chris Lattnerfaa54172010-01-12 21:23:57 +00006097 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006098 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006099 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006100 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6101 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006102
Chris Lattnerfaa54172010-01-12 21:23:57 +00006103 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006104}
6105
Chandler Carruthc9332212011-06-27 08:02:19 +00006106/// \brief Diagnose invalid arithmetic on two void pointers.
6107static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006108 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006109 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006110 ? diag::err_typecheck_pointer_arith_void_type
6111 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006112 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6113 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006114}
6115
6116/// \brief Diagnose invalid arithmetic on a void pointer.
6117static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6118 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006119 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006120 ? diag::err_typecheck_pointer_arith_void_type
6121 : diag::ext_gnu_void_ptr)
6122 << 0 /* one pointer */ << Pointer->getSourceRange();
6123}
6124
6125/// \brief Diagnose invalid arithmetic on two function pointers.
6126static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6127 Expr *LHS, Expr *RHS) {
6128 assert(LHS->getType()->isAnyPointerType());
6129 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006130 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006131 ? diag::err_typecheck_pointer_arith_function_type
6132 : diag::ext_gnu_ptr_func_arith)
6133 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6134 // We only show the second type if it differs from the first.
6135 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6136 RHS->getType())
6137 << RHS->getType()->getPointeeType()
6138 << LHS->getSourceRange() << RHS->getSourceRange();
6139}
6140
6141/// \brief Diagnose invalid arithmetic on a function pointer.
6142static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6143 Expr *Pointer) {
6144 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006145 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006146 ? diag::err_typecheck_pointer_arith_function_type
6147 : diag::ext_gnu_ptr_func_arith)
6148 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6149 << 0 /* one pointer, so only one type */
6150 << Pointer->getSourceRange();
6151}
6152
Richard Trieu993f3ab2011-09-12 18:08:02 +00006153/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006154///
6155/// \returns True if pointer has incomplete type
6156static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6157 Expr *Operand) {
6158 if ((Operand->getType()->isPointerType() &&
6159 !Operand->getType()->isDependentType()) ||
6160 Operand->getType()->isObjCObjectPointerType()) {
6161 QualType PointeeTy = Operand->getType()->getPointeeType();
6162 if (S.RequireCompleteType(
6163 Loc, PointeeTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006164 diag::err_typecheck_arithmetic_incomplete_type,
6165 PointeeTy, Operand->getSourceRange()))
Richard Trieuaba22802011-09-02 02:15:37 +00006166 return true;
6167 }
6168 return false;
6169}
6170
Chandler Carruthc9332212011-06-27 08:02:19 +00006171/// \brief Check the validity of an arithmetic pointer operand.
6172///
6173/// If the operand has pointer type, this code will check for pointer types
6174/// which are invalid in arithmetic operations. These will be diagnosed
6175/// appropriately, including whether or not the use is supported as an
6176/// extension.
6177///
6178/// \returns True when the operand is valid to use (even if as an extension).
6179static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6180 Expr *Operand) {
6181 if (!Operand->getType()->isAnyPointerType()) return true;
6182
6183 QualType PointeeTy = Operand->getType()->getPointeeType();
6184 if (PointeeTy->isVoidType()) {
6185 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006186 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006187 }
6188 if (PointeeTy->isFunctionType()) {
6189 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006190 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006191 }
6192
Richard Trieuaba22802011-09-02 02:15:37 +00006193 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006194
6195 return true;
6196}
6197
6198/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6199/// operands.
6200///
6201/// This routine will diagnose any invalid arithmetic on pointer operands much
6202/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6203/// for emitting a single diagnostic even for operations where both LHS and RHS
6204/// are (potentially problematic) pointers.
6205///
6206/// \returns True when the operand is valid to use (even if as an extension).
6207static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006208 Expr *LHSExpr, Expr *RHSExpr) {
6209 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6210 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006211 if (!isLHSPointer && !isRHSPointer) return true;
6212
6213 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006214 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6215 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006216
6217 // Check for arithmetic on pointers to incomplete types.
6218 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6219 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6220 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006221 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6222 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6223 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006224
David Blaikiebbafb8a2012-03-11 07:00:24 +00006225 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006226 }
6227
6228 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6229 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6230 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006231 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6232 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6233 RHSExpr);
6234 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006235
David Blaikiebbafb8a2012-03-11 07:00:24 +00006236 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006237 }
6238
Richard Trieu4ae7e972011-09-06 21:13:51 +00006239 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6240 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006241
Chandler Carruthc9332212011-06-27 08:02:19 +00006242 return true;
6243}
6244
Richard Trieub10c6312011-09-01 22:53:23 +00006245/// \brief Check bad cases where we step over interface counts.
6246static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6247 SourceLocation OpLoc,
6248 Expr *Op) {
6249 assert(Op->getType()->isAnyPointerType());
6250 QualType PointeeTy = Op->getType()->getPointeeType();
6251 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6252 return true;
6253
6254 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6255 << PointeeTy << Op->getSourceRange();
6256 return false;
6257}
6258
Nico Weberccec40d2012-03-02 22:01:22 +00006259/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6260/// literal.
6261static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6262 Expr *LHSExpr, Expr *RHSExpr) {
6263 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6264 Expr* IndexExpr = RHSExpr;
6265 if (!StrExpr) {
6266 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6267 IndexExpr = LHSExpr;
6268 }
6269
6270 bool IsStringPlusInt = StrExpr &&
6271 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6272 if (!IsStringPlusInt)
6273 return;
6274
6275 llvm::APSInt index;
6276 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6277 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6278 if (index.isNonNegative() &&
6279 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6280 index.isUnsigned()))
6281 return;
6282 }
6283
6284 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6285 Self.Diag(OpLoc, diag::warn_string_plus_int)
6286 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6287
6288 // Only print a fixit for "str" + int, not for int + "str".
6289 if (IndexExpr == RHSExpr) {
6290 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6291 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6292 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6293 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6294 << FixItHint::CreateInsertion(EndLoc, "]");
6295 } else
6296 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6297}
6298
Richard Trieu993f3ab2011-09-12 18:08:02 +00006299/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006300static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006301 Expr *LHSExpr, Expr *RHSExpr) {
6302 assert(LHSExpr->getType()->isAnyPointerType());
6303 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006304 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006305 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6306 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006307}
6308
Chris Lattnerfaa54172010-01-12 21:23:57 +00006309QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006310 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6311 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006312 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6313
Richard Trieu4ae7e972011-09-06 21:13:51 +00006314 if (LHS.get()->getType()->isVectorType() ||
6315 RHS.get()->getType()->isVectorType()) {
6316 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006317 if (CompLHSTy) *CompLHSTy = compType;
6318 return compType;
6319 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006320
Richard Trieu4ae7e972011-09-06 21:13:51 +00006321 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6322 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006323 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006324
Nico Weberccec40d2012-03-02 22:01:22 +00006325 // Diagnose "string literal" '+' int.
6326 if (Opc == BO_Add)
6327 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6328
Steve Naroffe4718892007-04-27 18:30:00 +00006329 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006330 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006331 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006332 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006333 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006334
Eli Friedman8e122982008-05-18 18:08:51 +00006335 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006336 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006337 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006338 std::swap(PExp, IExp);
6339
Richard Trieub420bca2011-09-12 18:37:54 +00006340 if (!PExp->getType()->isAnyPointerType())
6341 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006342
Richard Trieub420bca2011-09-12 18:37:54 +00006343 if (!IExp->getType()->isIntegerType())
6344 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006345
Richard Trieub420bca2011-09-12 18:37:54 +00006346 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6347 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006348
Richard Trieub420bca2011-09-12 18:37:54 +00006349 // Diagnose bad cases where we step over interface counts.
6350 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6351 return QualType();
6352
6353 // Check array bounds for pointer arithemtic
6354 CheckArrayAccess(PExp, IExp);
6355
6356 if (CompLHSTy) {
6357 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6358 if (LHSTy.isNull()) {
6359 LHSTy = LHS.get()->getType();
6360 if (LHSTy->isPromotableIntegerType())
6361 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006362 }
Richard Trieub420bca2011-09-12 18:37:54 +00006363 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006364 }
6365
Richard Trieub420bca2011-09-12 18:37:54 +00006366 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006367}
6368
Chris Lattner2a3569b2008-04-07 05:30:13 +00006369// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006370QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006371 SourceLocation Loc,
6372 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006373 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6374
Richard Trieu4ae7e972011-09-06 21:13:51 +00006375 if (LHS.get()->getType()->isVectorType() ||
6376 RHS.get()->getType()->isVectorType()) {
6377 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006378 if (CompLHSTy) *CompLHSTy = compType;
6379 return compType;
6380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006381
Richard Trieu4ae7e972011-09-06 21:13:51 +00006382 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6383 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006384 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006385
Chris Lattner4d62f422007-12-09 21:53:25 +00006386 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006387
Chris Lattner4d62f422007-12-09 21:53:25 +00006388 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006389 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006390 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006391 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006392 }
Mike Stump11289f42009-09-09 15:08:12 +00006393
Chris Lattner4d62f422007-12-09 21:53:25 +00006394 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006395 if (LHS.get()->getType()->isAnyPointerType()) {
6396 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006397
Chris Lattner12bdebb2009-04-24 23:50:08 +00006398 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006399 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006400 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006401
Chris Lattner4d62f422007-12-09 21:53:25 +00006402 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006403 if (RHS.get()->getType()->isIntegerType()) {
6404 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006405 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006406
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006407 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006408 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6409 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006410
Richard Trieu4ae7e972011-09-06 21:13:51 +00006411 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6412 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006413 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006414
Chris Lattner4d62f422007-12-09 21:53:25 +00006415 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006416 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006417 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006418 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006419
David Blaikiebbafb8a2012-03-11 07:00:24 +00006420 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006421 // Pointee types must be the same: C++ [expr.add]
6422 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006423 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006424 }
6425 } else {
6426 // Pointee types must be compatible C99 6.5.6p3
6427 if (!Context.typesAreCompatible(
6428 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6429 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006430 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006431 return QualType();
6432 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006433 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006434
Chandler Carruthc9332212011-06-27 08:02:19 +00006435 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006436 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006437 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006438
Richard Trieu4ae7e972011-09-06 21:13:51 +00006439 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006440 return Context.getPointerDiffType();
6441 }
6442 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006443
Richard Trieu4ae7e972011-09-06 21:13:51 +00006444 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006445}
6446
Douglas Gregor0bf31402010-10-08 23:50:27 +00006447static bool isScopedEnumerationType(QualType T) {
6448 if (const EnumType *ET = dyn_cast<EnumType>(T))
6449 return ET->getDecl()->isScoped();
6450 return false;
6451}
6452
Richard Trieue4a19fb2011-09-06 21:21:28 +00006453static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006454 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006455 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006456 llvm::APSInt Right;
6457 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006458 if (RHS.get()->isValueDependent() ||
6459 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006460 return;
6461
6462 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006463 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006464 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006465 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006466 return;
6467 }
6468 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006469 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006470 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006471 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006472 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006473 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006474 return;
6475 }
6476 if (Opc != BO_Shl)
6477 return;
6478
6479 // When left shifting an ICE which is signed, we can check for overflow which
6480 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6481 // integers have defined behavior modulo one more than the maximum value
6482 // representable in the result type, so never warn for those.
6483 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006484 if (LHS.get()->isValueDependent() ||
6485 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6486 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006487 return;
6488 llvm::APInt ResultBits =
6489 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6490 if (LeftBits.uge(ResultBits))
6491 return;
6492 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6493 Result = Result.shl(Right);
6494
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006495 // Print the bit representation of the signed integer as an unsigned
6496 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006497 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006498 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6499
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006500 // If we are only missing a sign bit, this is less likely to result in actual
6501 // bugs -- if the result is cast back to an unsigned type, it will have the
6502 // expected value. Thus we place this behind a different warning that can be
6503 // turned off separately if needed.
6504 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006505 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006506 << HexResult.str() << LHSType
6507 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006508 return;
6509 }
6510
6511 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006512 << HexResult.str() << Result.getMinSignedBits() << LHSType
6513 << Left.getBitWidth() << LHS.get()->getSourceRange()
6514 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006515}
6516
Chris Lattner2a3569b2008-04-07 05:30:13 +00006517// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006518QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006519 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006520 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006521 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6522
Chris Lattner5c11c412007-12-12 05:47:28 +00006523 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006524 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6525 !RHS.get()->getType()->hasIntegerRepresentation())
6526 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006527
Douglas Gregor0bf31402010-10-08 23:50:27 +00006528 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6529 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006530 if (isScopedEnumerationType(LHS.get()->getType()) ||
6531 isScopedEnumerationType(RHS.get()->getType())) {
6532 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006533 }
6534
Nate Begemane46ee9a2009-10-25 02:26:48 +00006535 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006536 if (LHS.get()->getType()->isVectorType() ||
6537 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006538 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006539
Chris Lattner5c11c412007-12-12 05:47:28 +00006540 // Shifts don't perform usual arithmetic conversions, they just do integer
6541 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006542
John McCall57cdd882010-12-16 19:28:59 +00006543 // For the LHS, do usual unary conversions, but then reset them away
6544 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006545 ExprResult OldLHS = LHS;
6546 LHS = UsualUnaryConversions(LHS.take());
6547 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006548 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006549 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006550 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006551
6552 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006553 RHS = UsualUnaryConversions(RHS.take());
6554 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006555 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006556
Ryan Flynnf53fab82009-08-07 16:20:20 +00006557 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006558 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006559
Chris Lattner5c11c412007-12-12 05:47:28 +00006560 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006561 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006562}
6563
Chandler Carruth17773fc2010-07-10 12:30:03 +00006564static bool IsWithinTemplateSpecialization(Decl *D) {
6565 if (DeclContext *DC = D->getDeclContext()) {
6566 if (isa<ClassTemplateSpecializationDecl>(DC))
6567 return true;
6568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6569 return FD->isFunctionTemplateSpecialization();
6570 }
6571 return false;
6572}
6573
Richard Trieueea56f72011-09-02 03:48:46 +00006574/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006575static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6576 ExprResult &RHS) {
6577 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6578 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006579
6580 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6581 if (!LHSEnumType)
6582 return;
6583 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6584 if (!RHSEnumType)
6585 return;
6586
6587 // Ignore anonymous enums.
6588 if (!LHSEnumType->getDecl()->getIdentifier())
6589 return;
6590 if (!RHSEnumType->getDecl()->getIdentifier())
6591 return;
6592
6593 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6594 return;
6595
6596 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6597 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006599}
6600
Richard Trieudd82a5c2011-09-02 02:55:45 +00006601/// \brief Diagnose bad pointer comparisons.
6602static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006603 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006604 bool IsError) {
6605 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006606 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006607 << LHS.get()->getType() << RHS.get()->getType()
6608 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006609}
6610
6611/// \brief Returns false if the pointers are converted to a composite type,
6612/// true otherwise.
6613static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006614 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006615 // C++ [expr.rel]p2:
6616 // [...] Pointer conversions (4.10) and qualification
6617 // conversions (4.4) are performed on pointer operands (or on
6618 // a pointer operand and a null pointer constant) to bring
6619 // them to their composite pointer type. [...]
6620 //
6621 // C++ [expr.eq]p1 uses the same notion for (in)equality
6622 // comparisons of pointers.
6623
6624 // C++ [expr.eq]p2:
6625 // In addition, pointers to members can be compared, or a pointer to
6626 // member and a null pointer constant. Pointer to member conversions
6627 // (4.11) and qualification conversions (4.4) are performed to bring
6628 // them to a common type. If one operand is a null pointer constant,
6629 // the common type is the type of the other operand. Otherwise, the
6630 // common type is a pointer to member type similar (4.4) to the type
6631 // of one of the operands, with a cv-qualification signature (4.4)
6632 // that is the union of the cv-qualification signatures of the operand
6633 // types.
6634
Richard Trieu1762d7c2011-09-06 21:27:33 +00006635 QualType LHSType = LHS.get()->getType();
6636 QualType RHSType = RHS.get()->getType();
6637 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6638 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006639
6640 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006641 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006642 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006643 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006644 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006645 return true;
6646 }
6647
6648 if (NonStandardCompositeType)
6649 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006650 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6651 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006652
Richard Trieu1762d7c2011-09-06 21:27:33 +00006653 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6654 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006655 return false;
6656}
6657
6658static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006659 ExprResult &LHS,
6660 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006661 bool IsError) {
6662 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6663 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006664 << LHS.get()->getType() << RHS.get()->getType()
6665 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006666}
6667
Jordan Rosed49a33e2012-06-08 21:14:25 +00006668static bool isObjCObjectLiteral(ExprResult &E) {
6669 switch (E.get()->getStmtClass()) {
6670 case Stmt::ObjCArrayLiteralClass:
6671 case Stmt::ObjCDictionaryLiteralClass:
6672 case Stmt::ObjCStringLiteralClass:
6673 case Stmt::ObjCBoxedExprClass:
6674 return true;
6675 default:
6676 // Note that ObjCBoolLiteral is NOT an object literal!
6677 return false;
6678 }
6679}
6680
6681static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S,
6682 SourceLocation Loc,
6683 ExprResult &LHS,
6684 ExprResult &RHS,
6685 bool CanFix = false) {
6686 Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get();
6687
6688 unsigned LiteralKind;
6689 switch (Literal->getStmtClass()) {
6690 case Stmt::ObjCStringLiteralClass:
6691 // "string literal"
6692 LiteralKind = 0;
6693 break;
6694 case Stmt::ObjCArrayLiteralClass:
6695 // "array literal"
6696 LiteralKind = 1;
6697 break;
6698 case Stmt::ObjCDictionaryLiteralClass:
6699 // "dictionary literal"
6700 LiteralKind = 2;
6701 break;
6702 case Stmt::ObjCBoxedExprClass: {
6703 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6704 switch (Inner->getStmtClass()) {
6705 case Stmt::IntegerLiteralClass:
6706 case Stmt::FloatingLiteralClass:
6707 case Stmt::CharacterLiteralClass:
6708 case Stmt::ObjCBoolLiteralExprClass:
6709 case Stmt::CXXBoolLiteralExprClass:
6710 // "numeric literal"
6711 LiteralKind = 3;
6712 break;
6713 case Stmt::ImplicitCastExprClass: {
6714 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6715 // Boolean literals can be represented by implicit casts.
6716 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6717 LiteralKind = 3;
6718 break;
6719 }
6720 // FALLTHROUGH
6721 }
6722 default:
6723 // "boxed expression"
6724 LiteralKind = 4;
6725 break;
6726 }
6727 break;
6728 }
6729 default:
6730 llvm_unreachable("Unknown Objective-C object literal kind");
6731 }
6732
6733 return S.Diag(Loc, diag::err_objc_literal_comparison)
6734 << LiteralKind << CanFix << Literal->getSourceRange();
6735}
6736
6737static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc,
6738 ExprResult &LHS,
6739 ExprResult &RHS,
6740 BinaryOperatorKind Op) {
6741 assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations.");
6742
6743 // Get the LHS object's interface type.
6744 QualType Type = LHS.get()->getType();
6745 QualType InterfaceType;
6746 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6747 InterfaceType = PTy->getPointeeType();
6748 if (const ObjCObjectType *iQFaceTy =
6749 InterfaceType->getAsObjCQualifiedInterfaceType())
6750 InterfaceType = iQFaceTy->getBaseType();
6751 } else {
6752 // If this is not actually an Objective-C object, bail out.
6753 return ExprEmpty();
6754 }
6755
6756 // If the RHS isn't an Objective-C object, bail out.
6757 if (!RHS.get()->getType()->isObjCObjectPointerType())
6758 return ExprEmpty();
6759
6760 // Try to find the -isEqual: method.
6761 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6762 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6763 InterfaceType,
6764 /*instance=*/true);
6765 bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType());
6766
6767 if (!Method && ReceiverIsId) {
6768 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6769 /*receiverId=*/true,
6770 /*warn=*/false);
6771 }
6772
6773 if (!Method)
6774 return ExprEmpty();
6775
6776 QualType T = Method->param_begin()[0]->getType();
6777 if (!T->isObjCObjectPointerType())
6778 return ExprEmpty();
6779
6780 QualType R = Method->getResultType();
6781 if (!R->isScalarType())
6782 return ExprEmpty();
6783
6784 // At this point we know we have a good -isEqual: method.
6785 // Emit the diagnostic and fixit.
6786 DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc,
6787 LHS, RHS, true);
6788
6789 Expr *LHSExpr = LHS.take();
6790 Expr *RHSExpr = RHS.take();
6791
6792 SourceLocation Start = LHSExpr->getLocStart();
6793 SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6794 SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc));
6795
6796 Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![")
6797 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6798 << FixItHint::CreateInsertion(End, "]");
6799
6800 // Finally, build the call to -isEqual: (and possible logical not).
6801 ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(),
6802 /*SuperLoc=*/SourceLocation(),
6803 IsEqualSel, Method,
6804 OpLoc, OpLoc, OpLoc,
6805 MultiExprArg(S, &RHSExpr, 1),
6806 /*isImplicit=*/false);
6807
6808 ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc);
6809
6810 if (Op == BO_NE)
6811 return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get());
6812 return CallCond;
6813}
6814
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006815// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006816QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006817 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006818 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006819 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6820
John McCalle3027922010-08-25 11:45:40 +00006821 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006822
Chris Lattner9a152e22009-12-05 05:40:13 +00006823 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006824 if (LHS.get()->getType()->isVectorType() ||
6825 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006826 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006827
Richard Trieub80728f2011-09-06 21:43:51 +00006828 QualType LHSType = LHS.get()->getType();
6829 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006830
Richard Trieub80728f2011-09-06 21:43:51 +00006831 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6832 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006833
Richard Trieub80728f2011-09-06 21:43:51 +00006834 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006835
Richard Trieub80728f2011-09-06 21:43:51 +00006836 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006837 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006838 !LHS.get()->getLocStart().isMacroID() &&
6839 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006840 // For non-floating point types, check for self-comparisons of the form
6841 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6842 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006843 //
6844 // NOTE: Don't warn about comparison expressions resulting from macro
6845 // expansion. Also don't warn about comparisons which are only self
6846 // comparisons within a template specialization. The warnings should catch
6847 // obvious cases in the definition of the template anyways. The idea is to
6848 // warn when the typed comparison operator will always evaluate to the same
6849 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006850 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006851 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006852 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006853 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006854 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006855 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006856 << (Opc == BO_EQ
6857 || Opc == BO_LE
6858 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006859 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006860 !DRL->getDecl()->getType()->isReferenceType() &&
6861 !DRR->getDecl()->getType()->isReferenceType()) {
6862 // what is it always going to eval to?
6863 char always_evals_to;
6864 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006865 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006866 always_evals_to = 0; // false
6867 break;
John McCalle3027922010-08-25 11:45:40 +00006868 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006869 always_evals_to = 1; // true
6870 break;
6871 default:
6872 // best we can say is 'a constant'
6873 always_evals_to = 2; // e.g. array1 <= array2
6874 break;
6875 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006876 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006877 << 1 // array
6878 << always_evals_to);
6879 }
6880 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006881 }
Mike Stump11289f42009-09-09 15:08:12 +00006882
Chris Lattner222b8bd2009-03-08 19:39:53 +00006883 if (isa<CastExpr>(LHSStripped))
6884 LHSStripped = LHSStripped->IgnoreParenCasts();
6885 if (isa<CastExpr>(RHSStripped))
6886 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006887
Chris Lattner222b8bd2009-03-08 19:39:53 +00006888 // Warn about comparisons against a string constant (unless the other
6889 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006890 Expr *literalString = 0;
6891 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006892 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006893 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006894 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006895 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006896 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006897 } else if ((isa<StringLiteral>(RHSStripped) ||
6898 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006899 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006900 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006901 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006902 literalStringStripped = RHSStripped;
6903 }
6904
6905 if (literalString) {
6906 std::string resultComparison;
6907 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006908 case BO_LT: resultComparison = ") < 0"; break;
6909 case BO_GT: resultComparison = ") > 0"; break;
6910 case BO_LE: resultComparison = ") <= 0"; break;
6911 case BO_GE: resultComparison = ") >= 0"; break;
6912 case BO_EQ: resultComparison = ") == 0"; break;
6913 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006914 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006915 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006916
Ted Kremenek3427fac2011-02-23 01:52:04 +00006917 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006918 PDiag(diag::warn_stringcompare)
6919 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006920 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006921 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006922 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006923
Douglas Gregorec170db2010-06-08 19:50:34 +00006924 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006925 if (LHS.get()->getType()->isArithmeticType() &&
6926 RHS.get()->getType()->isArithmeticType()) {
6927 UsualArithmeticConversions(LHS, RHS);
6928 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006929 return QualType();
6930 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006931 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006932 LHS = UsualUnaryConversions(LHS.take());
6933 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006934 return QualType();
6935
Richard Trieub80728f2011-09-06 21:43:51 +00006936 RHS = UsualUnaryConversions(RHS.take());
6937 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006938 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006939 }
6940
Richard Trieub80728f2011-09-06 21:43:51 +00006941 LHSType = LHS.get()->getType();
6942 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006943
Douglas Gregorca63811b2008-11-19 03:25:36 +00006944 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006945 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006946
Richard Trieuba63ce62011-09-09 01:45:06 +00006947 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006948 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006949 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006950 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006951 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006952 if (LHSType->hasFloatingRepresentation())
6953 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006954
Richard Trieub80728f2011-09-06 21:43:51 +00006955 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006956 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006957 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006958
Richard Trieub80728f2011-09-06 21:43:51 +00006959 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006960 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006961 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006962 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006963
Douglas Gregorf267edd2010-06-15 21:38:40 +00006964 // All of the following pointer-related warnings are GCC extensions, except
6965 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006966 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006967 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006968 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006969 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006970 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006971
David Blaikiebbafb8a2012-03-11 07:00:24 +00006972 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006973 if (LCanPointeeTy == RCanPointeeTy)
6974 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006975 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006976 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6977 // Valid unless comparison between non-null pointer and function pointer
6978 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006979 // In a SFINAE context, we treat this as a hard error to maintain
6980 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006981 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6982 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006983 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006984 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006985
6986 if (isSFINAEContext())
6987 return QualType();
6988
Richard Trieub80728f2011-09-06 21:43:51 +00006989 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006990 return ResultTy;
6991 }
6992 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006993
Richard Trieub80728f2011-09-06 21:43:51 +00006994 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006995 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006996 else
6997 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006998 }
Eli Friedman16c209612009-08-23 00:27:47 +00006999 // C99 6.5.9p2 and C99 6.5.8p2
7000 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7001 RCanPointeeTy.getUnqualifiedType())) {
7002 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007003 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007004 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007005 << LHSType << RHSType << LHS.get()->getSourceRange()
7006 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007007 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007008 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007009 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7010 // Valid unless comparison between non-null pointer and function pointer
7011 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007012 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007013 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007014 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007015 } else {
7016 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007017 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007018 }
John McCall7684dde2011-03-11 04:25:25 +00007019 if (LCanPointeeTy != RCanPointeeTy) {
7020 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007021 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007022 else
Richard Trieub80728f2011-09-06 21:43:51 +00007023 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007024 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007025 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007026 }
Mike Stump11289f42009-09-09 15:08:12 +00007027
David Blaikiebbafb8a2012-03-11 07:00:24 +00007028 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007029 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007030 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007031 return ResultTy;
7032
Mike Stump11289f42009-09-09 15:08:12 +00007033 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007034 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007035 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007036 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007037 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007038 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7039 RHS = ImpCastExprToType(RHS.take(), LHSType,
7040 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007041 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007042 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007043 return ResultTy;
7044 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007045 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007046 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007047 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007048 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7049 LHS = ImpCastExprToType(LHS.take(), RHSType,
7050 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007051 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007052 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007053 return ResultTy;
7054 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007055
7056 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007057 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007058 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7059 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007060 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007061 else
7062 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007063 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007064
7065 // Handle scoped enumeration types specifically, since they don't promote
7066 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007067 if (LHS.get()->getType()->isEnumeralType() &&
7068 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7069 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007070 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007071 }
Mike Stump11289f42009-09-09 15:08:12 +00007072
Steve Naroff081c7422008-09-04 15:10:53 +00007073 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007074 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007075 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007076 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7077 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007078
Steve Naroff081c7422008-09-04 15:10:53 +00007079 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007080 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007081 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007082 << LHSType << RHSType << LHS.get()->getSourceRange()
7083 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007084 }
Richard Trieub80728f2011-09-06 21:43:51 +00007085 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007086 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007087 }
John Wiegley01296292011-04-08 18:41:53 +00007088
Steve Naroffe18f94c2008-09-28 01:11:11 +00007089 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007090 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007091 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7092 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007093 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007094 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007095 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007096 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007097 ->getPointeeType()->isVoidType())))
7098 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007099 << LHSType << RHSType << LHS.get()->getSourceRange()
7100 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007101 }
John McCall7684dde2011-03-11 04:25:25 +00007102 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007103 LHS = ImpCastExprToType(LHS.take(), RHSType,
7104 RHSType->isPointerType() ? CK_BitCast
7105 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007106 else
John McCall9320b872011-09-09 05:25:32 +00007107 RHS = ImpCastExprToType(RHS.take(), LHSType,
7108 LHSType->isPointerType() ? CK_BitCast
7109 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007110 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007111 }
Steve Naroff081c7422008-09-04 15:10:53 +00007112
Richard Trieub80728f2011-09-06 21:43:51 +00007113 if (LHSType->isObjCObjectPointerType() ||
7114 RHSType->isObjCObjectPointerType()) {
7115 const PointerType *LPT = LHSType->getAs<PointerType>();
7116 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007117 if (LPT || RPT) {
7118 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7119 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007120
Steve Naroff753567f2008-11-17 19:49:16 +00007121 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007122 !Context.typesAreCompatible(LHSType, RHSType)) {
7123 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007124 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007125 }
John McCall7684dde2011-03-11 04:25:25 +00007126 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007127 LHS = ImpCastExprToType(LHS.take(), RHSType,
7128 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007129 else
John McCall9320b872011-09-09 05:25:32 +00007130 RHS = ImpCastExprToType(RHS.take(), LHSType,
7131 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007132 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007133 }
Richard Trieub80728f2011-09-06 21:43:51 +00007134 if (LHSType->isObjCObjectPointerType() &&
7135 RHSType->isObjCObjectPointerType()) {
7136 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7137 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007138 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007139 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7140 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS);
7141
John McCall7684dde2011-03-11 04:25:25 +00007142 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007143 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007144 else
Richard Trieub80728f2011-09-06 21:43:51 +00007145 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007146 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007147 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007148 }
Richard Trieub80728f2011-09-06 21:43:51 +00007149 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7150 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007151 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007152 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00007153 if ((LHSIsNull && LHSType->isIntegerType()) ||
7154 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007155 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007156 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007157 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007158 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007159 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007160 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7161 isError = true;
7162 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007163 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007164
Chris Lattnerd99bd522009-08-23 00:03:44 +00007165 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007166 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007167 << LHSType << RHSType << LHS.get()->getSourceRange()
7168 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007169 if (isError)
7170 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007171 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007172
Richard Trieub80728f2011-09-06 21:43:51 +00007173 if (LHSType->isIntegerType())
7174 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007175 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007176 else
Richard Trieub80728f2011-09-06 21:43:51 +00007177 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007178 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007179 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007180 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007181
Steve Naroff4b191572008-09-04 16:56:14 +00007182 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007183 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007184 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7185 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007186 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007187 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007188 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007189 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7190 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007191 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007192 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007193
Richard Trieub80728f2011-09-06 21:43:51 +00007194 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007195}
7196
Tanya Lattner20248222012-01-16 21:02:28 +00007197
7198// Return a signed type that is of identical size and number of elements.
7199// For floating point vectors, return an integer type of identical size
7200// and number of elements.
7201QualType Sema::GetSignedVectorType(QualType V) {
7202 const VectorType *VTy = V->getAs<VectorType>();
7203 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7204 if (TypeSize == Context.getTypeSize(Context.CharTy))
7205 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7206 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7207 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7208 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7209 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7210 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7211 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7212 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7213 "Unhandled vector element size in vector compare");
7214 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7215}
7216
Nate Begeman191a6b12008-07-14 18:02:46 +00007217/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007218/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007219/// like a scalar comparison, a vector comparison produces a vector of integer
7220/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007221QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007222 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007223 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007224 // Check to make sure we're operating on vectors of the same type and width,
7225 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007226 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007227 if (vType.isNull())
7228 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007229
Richard Trieubcce2f72011-09-07 01:19:57 +00007230 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007231
Anton Yartsev530deb92011-03-27 15:36:07 +00007232 // If AltiVec, the comparison results in a numeric type, i.e.
7233 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007234 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007235 return Context.getLogicalOperationType();
7236
Nate Begeman191a6b12008-07-14 18:02:46 +00007237 // For non-floating point types, check for self-comparisons of the form
7238 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7239 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007240 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007241 if (DeclRefExpr* DRL
7242 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7243 if (DeclRefExpr* DRR
7244 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007245 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007246 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007247 PDiag(diag::warn_comparison_always)
7248 << 0 // self-
7249 << 2 // "a constant"
7250 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007251 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007252
Nate Begeman191a6b12008-07-14 18:02:46 +00007253 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007254 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007255 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007256 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007257 }
Tanya Lattner20248222012-01-16 21:02:28 +00007258
7259 // Return a signed type for the vector.
7260 return GetSignedVectorType(LHSType);
7261}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007262
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007263QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7264 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007265 // Ensure that either both operands are of the same vector type, or
7266 // one operand is of a vector type and the other is of its element type.
7267 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7268 if (vType.isNull() || vType->isFloatingType())
7269 return InvalidOperands(Loc, LHS, RHS);
7270
7271 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007272}
7273
Steve Naroff218bc2b2007-05-04 21:54:46 +00007274inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007275 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007276 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7277
Richard Trieubcce2f72011-09-07 01:19:57 +00007278 if (LHS.get()->getType()->isVectorType() ||
7279 RHS.get()->getType()->isVectorType()) {
7280 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7281 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007282 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007283
Richard Trieubcce2f72011-09-07 01:19:57 +00007284 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007285 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007286
Richard Trieubcce2f72011-09-07 01:19:57 +00007287 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7288 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007289 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007290 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007291 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007292 LHS = LHSResult.take();
7293 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007294
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007295 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007296 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007297 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007298}
7299
Steve Naroff218bc2b2007-05-04 21:54:46 +00007300inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007301 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007302
Tanya Lattner20248222012-01-16 21:02:28 +00007303 // Check vector operands differently.
7304 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7305 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7306
Chris Lattner8406c512010-07-13 19:41:32 +00007307 // Diagnose cases where the user write a logical and/or but probably meant a
7308 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7309 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007310 if (LHS.get()->getType()->isIntegerType() &&
7311 !LHS.get()->getType()->isBooleanType() &&
7312 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007313 // Don't warn in macros or template instantiations.
7314 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007315 // If the RHS can be constant folded, and if it constant folds to something
7316 // that isn't 0 or 1 (which indicate a potential logical operation that
7317 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007318 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007319 llvm::APSInt Result;
7320 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007321 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007322 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007323 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007324 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007325 << (Opc == BO_LAnd ? "&&" : "||");
7326 // Suggest replacing the logical operator with the bitwise version
7327 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7328 << (Opc == BO_LAnd ? "&" : "|")
7329 << FixItHint::CreateReplacement(SourceRange(
7330 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007331 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007332 Opc == BO_LAnd ? "&" : "|");
7333 if (Opc == BO_LAnd)
7334 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7335 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7336 << FixItHint::CreateRemoval(
7337 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007338 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007339 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007340 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007341 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007342 }
Chris Lattner938533d2010-07-24 01:10:11 +00007343 }
Chris Lattner8406c512010-07-13 19:41:32 +00007344
David Blaikiebbafb8a2012-03-11 07:00:24 +00007345 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007346 LHS = UsualUnaryConversions(LHS.take());
7347 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007348 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007349
Richard Trieubcce2f72011-09-07 01:19:57 +00007350 RHS = UsualUnaryConversions(RHS.take());
7351 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007352 return QualType();
7353
Richard Trieubcce2f72011-09-07 01:19:57 +00007354 if (!LHS.get()->getType()->isScalarType() ||
7355 !RHS.get()->getType()->isScalarType())
7356 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007357
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007358 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007359 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007360
John McCall4a2429a2010-06-04 00:29:51 +00007361 // The following is safe because we only use this method for
7362 // non-overloadable operands.
7363
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007364 // C++ [expr.log.and]p1
7365 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007366 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007367 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7368 if (LHSRes.isInvalid())
7369 return InvalidOperands(Loc, LHS, RHS);
7370 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007371
Richard Trieubcce2f72011-09-07 01:19:57 +00007372 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7373 if (RHSRes.isInvalid())
7374 return InvalidOperands(Loc, LHS, RHS);
7375 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007376
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007377 // C++ [expr.log.and]p2
7378 // C++ [expr.log.or]p2
7379 // The result is a bool.
7380 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007381}
7382
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007383/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7384/// is a read-only property; return true if so. A readonly property expression
7385/// depends on various declarations and thus must be treated specially.
7386///
Mike Stump11289f42009-09-09 15:08:12 +00007387static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007388 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7389 if (!PropExpr) return false;
7390 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007391
John McCall526ab472011-10-25 17:37:35 +00007392 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7393 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007394 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007395 PropExpr->getBase()->getType();
7396
John McCall526ab472011-10-25 17:37:35 +00007397 if (const ObjCObjectPointerType *OPT =
7398 BaseType->getAsObjCInterfacePointerType())
7399 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7400 if (S.isPropertyReadonly(PDecl, IFace))
7401 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007402 return false;
7403}
7404
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007405static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007406 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7407 if (!ME) return false;
7408 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7409 ObjCMessageExpr *Base =
7410 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7411 if (!Base) return false;
7412 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007413}
7414
John McCall5fa2ef42012-03-13 00:37:01 +00007415/// Is the given expression (which must be 'const') a reference to a
7416/// variable which was originally non-const, but which has become
7417/// 'const' due to being captured within a block?
7418enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7419static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7420 assert(E->isLValue() && E->getType().isConstQualified());
7421 E = E->IgnoreParens();
7422
7423 // Must be a reference to a declaration from an enclosing scope.
7424 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7425 if (!DRE) return NCCK_None;
7426 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7427
7428 // The declaration must be a variable which is not declared 'const'.
7429 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7430 if (!var) return NCCK_None;
7431 if (var->getType().isConstQualified()) return NCCK_None;
7432 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7433
7434 // Decide whether the first capture was for a block or a lambda.
7435 DeclContext *DC = S.CurContext;
7436 while (DC->getParent() != var->getDeclContext())
7437 DC = DC->getParent();
7438 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7439}
7440
Chris Lattner30bd3272008-11-18 01:22:49 +00007441/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7442/// emit an error and return true. If so, return false.
7443static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007444 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007445 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007446 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007447 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007448 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7449 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007450 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7451 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007452 if (IsLV == Expr::MLV_Valid)
7453 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007454
Chris Lattner30bd3272008-11-18 01:22:49 +00007455 unsigned Diag = 0;
7456 bool NeedType = false;
7457 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007458 case Expr::MLV_ConstQualified:
7459 Diag = diag::err_typecheck_assign_const;
7460
John McCall5fa2ef42012-03-13 00:37:01 +00007461 // Use a specialized diagnostic when we're assigning to an object
7462 // from an enclosing function or block.
7463 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7464 if (NCCK == NCCK_Block)
7465 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7466 else
7467 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7468 break;
7469 }
7470
John McCalld4631322011-06-17 06:42:21 +00007471 // In ARC, use some specialized diagnostics for occasions where we
7472 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007473 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007474 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7475 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7476 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7477
John McCalld4631322011-06-17 06:42:21 +00007478 // Use the normal diagnostic if it's pseudo-__strong but the
7479 // user actually wrote 'const'.
7480 if (var->isARCPseudoStrong() &&
7481 (!var->getTypeSourceInfo() ||
7482 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7483 // There are two pseudo-strong cases:
7484 // - self
John McCall31168b02011-06-15 23:02:42 +00007485 ObjCMethodDecl *method = S.getCurMethodDecl();
7486 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007487 Diag = method->isClassMethod()
7488 ? diag::err_typecheck_arc_assign_self_class_method
7489 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007490
7491 // - fast enumeration variables
7492 else
John McCall31168b02011-06-15 23:02:42 +00007493 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007494
John McCall31168b02011-06-15 23:02:42 +00007495 SourceRange Assign;
7496 if (Loc != OrigLoc)
7497 Assign = SourceRange(OrigLoc, OrigLoc);
7498 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7499 // We need to preserve the AST regardless, so migration tool
7500 // can do its job.
7501 return false;
7502 }
7503 }
7504 }
7505
7506 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007507 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007508 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007509 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7510 NeedType = true;
7511 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007512 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007513 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7514 NeedType = true;
7515 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007516 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007517 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7518 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007519 case Expr::MLV_Valid:
7520 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007521 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007522 case Expr::MLV_MemberFunction:
7523 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007524 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7525 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007526 case Expr::MLV_IncompleteType:
7527 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007528 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007529 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007530 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007531 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7532 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007533 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007534 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007535 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007536 case Expr::MLV_InvalidMessageExpression:
7537 Diag = diag::error_readonly_message_assignment;
7538 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007539 case Expr::MLV_SubObjCPropertySetting:
7540 Diag = diag::error_no_subobject_property_setting;
7541 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007542 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007543
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007544 SourceRange Assign;
7545 if (Loc != OrigLoc)
7546 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007547 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007548 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007549 else
Mike Stump11289f42009-09-09 15:08:12 +00007550 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007551 return true;
7552}
7553
7554
7555
7556// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007557QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007558 SourceLocation Loc,
7559 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007560 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7561
Chris Lattner326f7572008-11-18 01:30:42 +00007562 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007563 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007564 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007565
Richard Trieuda4f43a62011-09-07 01:33:52 +00007566 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007567 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7568 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007569 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007570 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007571 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007572 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007573 if (RHS.isInvalid())
7574 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007575 // Special case of NSObject attributes on c-style pointer types.
7576 if (ConvTy == IncompatiblePointer &&
7577 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007578 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007579 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007580 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007581 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007582
John McCall7decc9e2010-11-18 06:31:45 +00007583 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007584 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007585 Diag(Loc, diag::err_objc_object_assignment)
7586 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007587
Chris Lattnerea714382008-08-21 18:04:13 +00007588 // If the RHS is a unary plus or minus, check to see if they = and + are
7589 // right next to each other. If so, the user may have typo'd "x =+ 4"
7590 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007591 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007592 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7593 RHSCheck = ICE->getSubExpr();
7594 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007595 if ((UO->getOpcode() == UO_Plus ||
7596 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007597 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007598 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007599 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007600 // And there is a space or other character before the subexpr of the
7601 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007602 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007603 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007604 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007605 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007606 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007607 }
Chris Lattnerea714382008-08-21 18:04:13 +00007608 }
John McCall31168b02011-06-15 23:02:42 +00007609
7610 if (ConvTy == Compatible) {
7611 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007612 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007613 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007614 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007615 }
Chris Lattnerea714382008-08-21 18:04:13 +00007616 } else {
7617 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007618 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007619 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007620
Chris Lattner326f7572008-11-18 01:30:42 +00007621 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007622 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007623 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007624
Richard Trieuda4f43a62011-09-07 01:33:52 +00007625 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007626
Steve Naroff98cf3e92007-06-06 18:38:38 +00007627 // C99 6.5.16p3: The type of an assignment expression is the type of the
7628 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007629 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007630 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7631 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007632 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007633 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007634 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007635 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007636}
7637
Chris Lattner326f7572008-11-18 01:30:42 +00007638// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007639static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007640 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007641 LHS = S.CheckPlaceholderExpr(LHS.take());
7642 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007643 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007644 return QualType();
7645
John McCall73d36182010-10-12 07:14:40 +00007646 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7647 // operands, but not unary promotions.
7648 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007649
John McCall34376a62010-12-04 03:47:34 +00007650 // So we treat the LHS as a ignored value, and in C++ we allow the
7651 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007652 LHS = S.IgnoredValueConversions(LHS.take());
7653 if (LHS.isInvalid())
7654 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007655
Eli Friedmanc11535c2012-05-24 00:47:05 +00007656 S.DiagnoseUnusedExprResult(LHS.get());
7657
David Blaikiebbafb8a2012-03-11 07:00:24 +00007658 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007659 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7660 if (RHS.isInvalid())
7661 return QualType();
7662 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007663 S.RequireCompleteType(Loc, RHS.get()->getType(),
7664 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007665 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007666
John Wiegley01296292011-04-08 18:41:53 +00007667 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007668}
7669
Steve Naroff7a5af782007-07-13 16:58:59 +00007670/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7671/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007672static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7673 ExprValueKind &VK,
7674 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007675 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007676 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007677 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007678
Chris Lattner6b0cf142008-11-21 07:05:48 +00007679 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007680 // Atomic types can be used for increment / decrement where the non-atomic
7681 // versions can, so ignore the _Atomic() specifier for the purpose of
7682 // checking.
7683 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7684 ResType = ResAtomicType->getValueType();
7685
Chris Lattner6b0cf142008-11-21 07:05:48 +00007686 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007687
David Blaikiebbafb8a2012-03-11 07:00:24 +00007688 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007689 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007690 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007691 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007692 return QualType();
7693 }
7694 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007695 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007696 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007697 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007698 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007699 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007700 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007701 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007702
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007703 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007704 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007705 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007706 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007707 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007708 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007709 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007710 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007711 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007712 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007713 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007714 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007715 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007716 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007717 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007718 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007719 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007720 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007721 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007722 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007723 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007724 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007725 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007726 // In C++, a prefix increment is the same type as the operand. Otherwise
7727 // (in C or with postfix), the increment is the unqualified type of the
7728 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007729 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007730 VK = VK_LValue;
7731 return ResType;
7732 } else {
7733 VK = VK_RValue;
7734 return ResType.getUnqualifiedType();
7735 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007736}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007737
7738
Anders Carlsson806700f2008-02-01 07:15:58 +00007739/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007740/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007741/// where the declaration is needed for type checking. We only need to
7742/// handle cases when the expression references a function designator
7743/// or is an lvalue. Here are some examples:
7744/// - &(x) => x
7745/// - &*****f => f for f a function designator.
7746/// - &s.xx => s
7747/// - &s.zz[1].yy -> s, if zz is an array
7748/// - *(x + 1) -> x, if x is an array
7749/// - &"123"[2] -> 0
7750/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007751static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007752 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007753 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007754 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007755 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007756 // If this is an arrow operator, the address is an offset from
7757 // the base's value, so the object the base refers to is
7758 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007759 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007760 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007761 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007762 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007763 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007764 // FIXME: This code shouldn't be necessary! We should catch the implicit
7765 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007766 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7767 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7768 if (ICE->getSubExpr()->getType()->isArrayType())
7769 return getPrimaryDecl(ICE->getSubExpr());
7770 }
7771 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007772 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007773 case Stmt::UnaryOperatorClass: {
7774 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007775
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007776 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007777 case UO_Real:
7778 case UO_Imag:
7779 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007780 return getPrimaryDecl(UO->getSubExpr());
7781 default:
7782 return 0;
7783 }
7784 }
Steve Naroff47500512007-04-19 23:00:49 +00007785 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007786 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007787 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007788 // If the result of an implicit cast is an l-value, we care about
7789 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007790 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007791 default:
7792 return 0;
7793 }
7794}
7795
Richard Trieu5f376f62011-09-07 21:46:33 +00007796namespace {
7797 enum {
7798 AO_Bit_Field = 0,
7799 AO_Vector_Element = 1,
7800 AO_Property_Expansion = 2,
7801 AO_Register_Variable = 3,
7802 AO_No_Error = 4
7803 };
7804}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007805/// \brief Diagnose invalid operand for address of operations.
7806///
7807/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007808static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7809 Expr *E, unsigned Type) {
7810 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7811}
7812
Steve Naroff47500512007-04-19 23:00:49 +00007813/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007814/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007815/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007816/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007817/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007818/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007819/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007820static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007821 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007822 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7823 if (PTy->getKind() == BuiltinType::Overload) {
7824 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7825 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7826 << OrigOp.get()->getSourceRange();
7827 return QualType();
7828 }
7829
7830 return S.Context.OverloadTy;
7831 }
7832
7833 if (PTy->getKind() == BuiltinType::UnknownAny)
7834 return S.Context.UnknownAnyTy;
7835
7836 if (PTy->getKind() == BuiltinType::BoundMember) {
7837 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7838 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007839 return QualType();
7840 }
John McCall526ab472011-10-25 17:37:35 +00007841
7842 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7843 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007844 }
John McCall8d08b9b2010-08-27 09:08:28 +00007845
John McCall526ab472011-10-25 17:37:35 +00007846 if (OrigOp.get()->isTypeDependent())
7847 return S.Context.DependentTy;
7848
7849 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007850
John McCall8d08b9b2010-08-27 09:08:28 +00007851 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007852 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007853
David Blaikiebbafb8a2012-03-11 07:00:24 +00007854 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007855 // Implement C99-only parts of addressof rules.
7856 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007857 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007858 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7859 // (assuming the deref expression is valid).
7860 return uOp->getSubExpr()->getType();
7861 }
7862 // Technically, there should be a check for array subscript
7863 // expressions here, but the result of one is always an lvalue anyway.
7864 }
John McCallf3a88602011-02-03 08:15:49 +00007865 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007866 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007867 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007868
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007869 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007870 bool sfinae = S.isSFINAEContext();
7871 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7872 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007873 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007874 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007875 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007876 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007877 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007878 } else if (lval == Expr::LV_MemberFunction) {
7879 // If it's an instance method, make a member pointer.
7880 // The expression must have exactly the form &A::foo.
7881
7882 // If the underlying expression isn't a decl ref, give up.
7883 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007884 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007885 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007886 return QualType();
7887 }
7888 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7889 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7890
7891 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007892 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007893 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007894 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007895
7896 // The method was named without a qualifier.
7897 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007898 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007899 << op->getSourceRange();
7900 }
7901
John McCall4bc41ae2010-11-18 19:01:18 +00007902 return S.Context.getMemberPointerType(op->getType(),
7903 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007904 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007905 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007906 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007907 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007908 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007909 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007910 AddressOfError = AO_Property_Expansion;
7911 } else {
7912 // FIXME: emit more specific diag...
7913 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7914 << op->getSourceRange();
7915 return QualType();
7916 }
Steve Naroff35d85152007-05-07 00:24:15 +00007917 }
John McCall086a4642010-11-24 05:12:34 +00007918 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007919 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007920 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007921 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007922 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007923 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007924 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007925 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007926 // with the register storage-class specifier.
7927 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007928 // in C++ it is not error to take address of a register
7929 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007930 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007931 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007932 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007933 }
John McCalld14a8642009-11-21 08:51:07 +00007934 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007935 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007936 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007937 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007938 // Could be a pointer to member, though, if there is an explicit
7939 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007940 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007941 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007942 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007943 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007944 S.Diag(OpLoc,
7945 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007946 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007947 return QualType();
7948 }
Mike Stump11289f42009-09-09 15:08:12 +00007949
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007950 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7951 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007952 return S.Context.getMemberPointerType(op->getType(),
7953 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007954 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007955 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007956 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007957 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007958 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007959
Richard Trieu5f376f62011-09-07 21:46:33 +00007960 if (AddressOfError != AO_No_Error) {
7961 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7962 return QualType();
7963 }
7964
Eli Friedmance7f9002009-05-16 23:27:50 +00007965 if (lval == Expr::LV_IncompleteVoidType) {
7966 // Taking the address of a void variable is technically illegal, but we
7967 // allow it in cases which are otherwise valid.
7968 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007969 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007970 }
7971
Steve Naroff47500512007-04-19 23:00:49 +00007972 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007973 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007974 return S.Context.getObjCObjectPointerType(op->getType());
7975 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007976}
7977
Chris Lattner9156f1b2010-07-05 19:17:26 +00007978/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007979static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7980 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007981 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007982 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007983
John Wiegley01296292011-04-08 18:41:53 +00007984 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7985 if (ConvResult.isInvalid())
7986 return QualType();
7987 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007988 QualType OpTy = Op->getType();
7989 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007990
7991 if (isa<CXXReinterpretCastExpr>(Op)) {
7992 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7993 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7994 Op->getSourceRange());
7995 }
7996
Chris Lattner9156f1b2010-07-05 19:17:26 +00007997 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7998 // is an incomplete type or void. It would be possible to warn about
7999 // dereferencing a void pointer, but it's completely well-defined, and such a
8000 // warning is unlikely to catch any mistakes.
8001 if (const PointerType *PT = OpTy->getAs<PointerType>())
8002 Result = PT->getPointeeType();
8003 else if (const ObjCObjectPointerType *OPT =
8004 OpTy->getAs<ObjCObjectPointerType>())
8005 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008006 else {
John McCall3aef3d82011-04-10 19:13:55 +00008007 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008008 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008009 if (PR.take() != Op)
8010 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008011 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008012
Chris Lattner9156f1b2010-07-05 19:17:26 +00008013 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008014 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008015 << OpTy << Op->getSourceRange();
8016 return QualType();
8017 }
John McCall4bc41ae2010-11-18 19:01:18 +00008018
8019 // Dereferences are usually l-values...
8020 VK = VK_LValue;
8021
8022 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008023 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008024 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008025
8026 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008027}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008028
John McCalle3027922010-08-25 11:45:40 +00008029static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008030 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008031 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008032 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008033 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008034 case tok::periodstar: Opc = BO_PtrMemD; break;
8035 case tok::arrowstar: Opc = BO_PtrMemI; break;
8036 case tok::star: Opc = BO_Mul; break;
8037 case tok::slash: Opc = BO_Div; break;
8038 case tok::percent: Opc = BO_Rem; break;
8039 case tok::plus: Opc = BO_Add; break;
8040 case tok::minus: Opc = BO_Sub; break;
8041 case tok::lessless: Opc = BO_Shl; break;
8042 case tok::greatergreater: Opc = BO_Shr; break;
8043 case tok::lessequal: Opc = BO_LE; break;
8044 case tok::less: Opc = BO_LT; break;
8045 case tok::greaterequal: Opc = BO_GE; break;
8046 case tok::greater: Opc = BO_GT; break;
8047 case tok::exclaimequal: Opc = BO_NE; break;
8048 case tok::equalequal: Opc = BO_EQ; break;
8049 case tok::amp: Opc = BO_And; break;
8050 case tok::caret: Opc = BO_Xor; break;
8051 case tok::pipe: Opc = BO_Or; break;
8052 case tok::ampamp: Opc = BO_LAnd; break;
8053 case tok::pipepipe: Opc = BO_LOr; break;
8054 case tok::equal: Opc = BO_Assign; break;
8055 case tok::starequal: Opc = BO_MulAssign; break;
8056 case tok::slashequal: Opc = BO_DivAssign; break;
8057 case tok::percentequal: Opc = BO_RemAssign; break;
8058 case tok::plusequal: Opc = BO_AddAssign; break;
8059 case tok::minusequal: Opc = BO_SubAssign; break;
8060 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8061 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8062 case tok::ampequal: Opc = BO_AndAssign; break;
8063 case tok::caretequal: Opc = BO_XorAssign; break;
8064 case tok::pipeequal: Opc = BO_OrAssign; break;
8065 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008066 }
8067 return Opc;
8068}
8069
John McCalle3027922010-08-25 11:45:40 +00008070static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008071 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008072 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008073 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008074 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008075 case tok::plusplus: Opc = UO_PreInc; break;
8076 case tok::minusminus: Opc = UO_PreDec; break;
8077 case tok::amp: Opc = UO_AddrOf; break;
8078 case tok::star: Opc = UO_Deref; break;
8079 case tok::plus: Opc = UO_Plus; break;
8080 case tok::minus: Opc = UO_Minus; break;
8081 case tok::tilde: Opc = UO_Not; break;
8082 case tok::exclaim: Opc = UO_LNot; break;
8083 case tok::kw___real: Opc = UO_Real; break;
8084 case tok::kw___imag: Opc = UO_Imag; break;
8085 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008086 }
8087 return Opc;
8088}
8089
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008090/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8091/// This warning is only emitted for builtin assignment operations. It is also
8092/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008093static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008094 SourceLocation OpLoc) {
8095 if (!S.ActiveTemplateInstantiations.empty())
8096 return;
8097 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8098 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008099 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8100 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8101 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8102 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8103 if (!LHSDeclRef || !RHSDeclRef ||
8104 LHSDeclRef->getLocation().isMacroID() ||
8105 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008106 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008107 const ValueDecl *LHSDecl =
8108 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8109 const ValueDecl *RHSDecl =
8110 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8111 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008112 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008113 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008114 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008115 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008116 if (RefTy->getPointeeType().isVolatileQualified())
8117 return;
8118
8119 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008120 << LHSDeclRef->getType()
8121 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008122}
8123
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008124/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8125/// operator @p Opc at location @c TokLoc. This routine only supports
8126/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008127ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008128 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008129 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008130 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008131 // The syntax only allows initializer lists on the RHS of assignment,
8132 // so we don't need to worry about accepting invalid code for
8133 // non-assignment operators.
8134 // C++11 5.17p9:
8135 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8136 // of x = {} is x = T().
8137 InitializationKind Kind =
8138 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8139 InitializedEntity Entity =
8140 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8141 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8142 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8143 MultiExprArg(&RHSExpr, 1));
8144 if (Init.isInvalid())
8145 return Init;
8146 RHSExpr = Init.take();
8147 }
8148
Richard Trieu4a287fb2011-09-07 01:49:20 +00008149 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008150 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008151 // The following two variables are used for compound assignment operators
8152 QualType CompLHSTy; // Type of LHS after promotions for computation
8153 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008154 ExprValueKind VK = VK_RValue;
8155 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008156
8157 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008158 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008159 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008160 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008161 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8162 VK = LHS.get()->getValueKind();
8163 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008164 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008165 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008166 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008167 break;
John McCalle3027922010-08-25 11:45:40 +00008168 case BO_PtrMemD:
8169 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008170 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008171 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008172 break;
John McCalle3027922010-08-25 11:45:40 +00008173 case BO_Mul:
8174 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008175 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008176 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008177 break;
John McCalle3027922010-08-25 11:45:40 +00008178 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008179 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008180 break;
John McCalle3027922010-08-25 11:45:40 +00008181 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008182 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008183 break;
John McCalle3027922010-08-25 11:45:40 +00008184 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008185 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008186 break;
John McCalle3027922010-08-25 11:45:40 +00008187 case BO_Shl:
8188 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008189 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008190 break;
John McCalle3027922010-08-25 11:45:40 +00008191 case BO_LE:
8192 case BO_LT:
8193 case BO_GE:
8194 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008195 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008196 break;
John McCalle3027922010-08-25 11:45:40 +00008197 case BO_EQ:
8198 case BO_NE:
Jordan Rosed49a33e2012-06-08 21:14:25 +00008199 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) {
8200 ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc,
8201 LHS, RHS, Opc);
8202 if (IsEqualCall.isUsable())
8203 return IsEqualCall;
8204 // Otherwise, fall back to the normal diagnostic in CheckCompareOperands.
8205 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008206 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008207 break;
John McCalle3027922010-08-25 11:45:40 +00008208 case BO_And:
8209 case BO_Xor:
8210 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008211 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008212 break;
John McCalle3027922010-08-25 11:45:40 +00008213 case BO_LAnd:
8214 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008215 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008216 break;
John McCalle3027922010-08-25 11:45:40 +00008217 case BO_MulAssign:
8218 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008219 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008220 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008221 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008222 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8223 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008224 break;
John McCalle3027922010-08-25 11:45:40 +00008225 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008226 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008227 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008228 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8229 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008230 break;
John McCalle3027922010-08-25 11:45:40 +00008231 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008232 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008233 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8234 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008235 break;
John McCalle3027922010-08-25 11:45:40 +00008236 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008237 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8238 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8239 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008240 break;
John McCalle3027922010-08-25 11:45:40 +00008241 case BO_ShlAssign:
8242 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008243 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008244 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008245 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8246 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008247 break;
John McCalle3027922010-08-25 11:45:40 +00008248 case BO_AndAssign:
8249 case BO_XorAssign:
8250 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008251 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008252 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008253 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8254 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008255 break;
John McCalle3027922010-08-25 11:45:40 +00008256 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008257 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008258 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008259 VK = RHS.get()->getValueKind();
8260 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008261 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008262 break;
8263 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008264 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008265 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008266
8267 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008268 CheckArrayAccess(LHS.get());
8269 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008270
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008271 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008272 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008273 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008274 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008275 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008276 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008277 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008278 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008279 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008280 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008281 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008282}
8283
Sebastian Redl44615072009-10-27 12:10:02 +00008284/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8285/// operators are mixed in a way that suggests that the programmer forgot that
8286/// comparison operators have higher precedence. The most typical example of
8287/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008288static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008289 SourceLocation OpLoc, Expr *LHSExpr,
8290 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008291 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008292 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8293 RHSopc = static_cast<BinOp::Opcode>(-1);
8294 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8295 LHSopc = BO->getOpcode();
8296 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8297 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008298
8299 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008300 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008301 return;
8302
8303 // Bitwise operations are sometimes used as eager logical ops.
8304 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008305 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8306 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008307 return;
8308
Richard Trieu4a287fb2011-09-07 01:49:20 +00008309 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8310 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008311 if (!isLeftComp && !isRightComp) return;
8312
Richard Trieu4a287fb2011-09-07 01:49:20 +00008313 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8314 OpLoc)
8315 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8316 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8317 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008318 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008319 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8320 RHSExpr->getLocEnd())
8321 : SourceRange(LHSExpr->getLocStart(),
8322 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008323
8324 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8325 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8326 SuggestParentheses(Self, OpLoc,
8327 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008328 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008329 SuggestParentheses(Self, OpLoc,
8330 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8331 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008332}
8333
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008334/// \brief It accepts a '&' expr that is inside a '|' one.
8335/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8336/// in parentheses.
8337static void
8338EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8339 BinaryOperator *Bop) {
8340 assert(Bop->getOpcode() == BO_And);
8341 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8342 << Bop->getSourceRange() << OpLoc;
8343 SuggestParentheses(Self, Bop->getOperatorLoc(),
8344 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8345 Bop->getSourceRange());
8346}
8347
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008348/// \brief It accepts a '&&' expr that is inside a '||' one.
8349/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8350/// in parentheses.
8351static void
8352EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008353 BinaryOperator *Bop) {
8354 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008355 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8356 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008357 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008358 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008359 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008360}
8361
8362/// \brief Returns true if the given expression can be evaluated as a constant
8363/// 'true'.
8364static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8365 bool Res;
8366 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8367}
8368
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008369/// \brief Returns true if the given expression can be evaluated as a constant
8370/// 'false'.
8371static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8372 bool Res;
8373 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8374}
8375
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008376/// \brief Look for '&&' in the left hand of a '||' expr.
8377static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008378 Expr *LHSExpr, Expr *RHSExpr) {
8379 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008380 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008381 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008382 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008383 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008384 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8385 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8386 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8387 } else if (Bop->getOpcode() == BO_LOr) {
8388 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8389 // If it's "a || b && 1 || c" we didn't warn earlier for
8390 // "a || b && 1", but warn now.
8391 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8392 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8393 }
8394 }
8395 }
8396}
8397
8398/// \brief Look for '&&' in the right hand of a '||' expr.
8399static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008400 Expr *LHSExpr, Expr *RHSExpr) {
8401 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008402 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008403 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008404 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008405 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008406 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8407 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8408 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008409 }
8410 }
8411}
8412
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008413/// \brief Look for '&' in the left or right hand of a '|' expr.
8414static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8415 Expr *OrArg) {
8416 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8417 if (Bop->getOpcode() == BO_And)
8418 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8419 }
8420}
8421
Sebastian Redl43028242009-10-26 15:24:15 +00008422/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008423/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008424static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008425 SourceLocation OpLoc, Expr *LHSExpr,
8426 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008427 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008428 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008429 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008430
8431 // Diagnose "arg1 & arg2 | arg3"
8432 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008433 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8434 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008435 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008436
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008437 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8438 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008439 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008440 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8441 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008442 }
Sebastian Redl43028242009-10-26 15:24:15 +00008443}
8444
Steve Naroff218bc2b2007-05-04 21:54:46 +00008445// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008446ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008447 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008448 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008449 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008450 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8451 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008452
Sebastian Redl43028242009-10-26 15:24:15 +00008453 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008454 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008455
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008456 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008457}
8458
John McCall526ab472011-10-25 17:37:35 +00008459/// Build an overloaded binary operator expression in the given scope.
8460static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8461 BinaryOperatorKind Opc,
8462 Expr *LHS, Expr *RHS) {
8463 // Find all of the overloaded operators visible from this
8464 // point. We perform both an operator-name lookup from the local
8465 // scope and an argument-dependent lookup based on the types of
8466 // the arguments.
8467 UnresolvedSet<16> Functions;
8468 OverloadedOperatorKind OverOp
8469 = BinaryOperator::getOverloadedOperator(Opc);
8470 if (Sc && OverOp != OO_None)
8471 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8472 RHS->getType(), Functions);
8473
8474 // Build the (potentially-overloaded, potentially-dependent)
8475 // binary operation.
8476 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8477}
8478
John McCalldadc5752010-08-24 06:29:42 +00008479ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008480 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008481 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008482 // We want to end up calling one of checkPseudoObjectAssignment
8483 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8484 // both expressions are overloadable or either is type-dependent),
8485 // or CreateBuiltinBinOp (in any other case). We also want to get
8486 // any placeholder types out of the way.
8487
John McCall526ab472011-10-25 17:37:35 +00008488 // Handle pseudo-objects in the LHS.
8489 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8490 // Assignments with a pseudo-object l-value need special analysis.
8491 if (pty->getKind() == BuiltinType::PseudoObject &&
8492 BinaryOperator::isAssignmentOp(Opc))
8493 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8494
8495 // Don't resolve overloads if the other type is overloadable.
8496 if (pty->getKind() == BuiltinType::Overload) {
8497 // We can't actually test that if we still have a placeholder,
8498 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008499 // code below are valid when the LHS is an overload set. Note
8500 // that an overload set can be dependently-typed, but it never
8501 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008502 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8503 if (resolvedRHS.isInvalid()) return ExprError();
8504 RHSExpr = resolvedRHS.take();
8505
John McCall9a43e122011-10-28 01:04:34 +00008506 if (RHSExpr->isTypeDependent() ||
8507 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008508 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8509 }
8510
8511 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8512 if (LHS.isInvalid()) return ExprError();
8513 LHSExpr = LHS.take();
8514 }
8515
8516 // Handle pseudo-objects in the RHS.
8517 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8518 // An overload in the RHS can potentially be resolved by the type
8519 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008520 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8521 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8522 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8523
Eli Friedman419b1ff2012-01-17 21:27:43 +00008524 if (LHSExpr->getType()->isOverloadableType())
8525 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8526
John McCall526ab472011-10-25 17:37:35 +00008527 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008528 }
John McCall526ab472011-10-25 17:37:35 +00008529
8530 // Don't resolve overloads if the other type is overloadable.
8531 if (pty->getKind() == BuiltinType::Overload &&
8532 LHSExpr->getType()->isOverloadableType())
8533 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8534
8535 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8536 if (!resolvedRHS.isUsable()) return ExprError();
8537 RHSExpr = resolvedRHS.take();
8538 }
8539
David Blaikiebbafb8a2012-03-11 07:00:24 +00008540 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008541 // If either expression is type-dependent, always build an
8542 // overloaded op.
8543 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8544 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008545
John McCall9a43e122011-10-28 01:04:34 +00008546 // Otherwise, build an overloaded op if either expression has an
8547 // overloadable type.
8548 if (LHSExpr->getType()->isOverloadableType() ||
8549 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008550 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008551 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008552
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008553 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008554 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008555}
8556
John McCalldadc5752010-08-24 06:29:42 +00008557ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008558 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008559 Expr *InputExpr) {
8560 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008561 ExprValueKind VK = VK_RValue;
8562 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008563 QualType resultType;
8564 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008565 case UO_PreInc:
8566 case UO_PreDec:
8567 case UO_PostInc:
8568 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008569 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008570 Opc == UO_PreInc ||
8571 Opc == UO_PostInc,
8572 Opc == UO_PreInc ||
8573 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008574 break;
John McCalle3027922010-08-25 11:45:40 +00008575 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008576 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008577 break;
John McCall31996342011-04-07 08:22:57 +00008578 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008579 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8580 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008581 break;
John McCall31996342011-04-07 08:22:57 +00008582 }
John McCalle3027922010-08-25 11:45:40 +00008583 case UO_Plus:
8584 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008585 Input = UsualUnaryConversions(Input.take());
8586 if (Input.isInvalid()) return ExprError();
8587 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008588 if (resultType->isDependentType())
8589 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008590 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8591 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008592 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008593 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008594 resultType->isEnumeralType())
8595 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008596 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008597 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008598 resultType->isPointerType())
8599 break;
8600
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008601 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008602 << resultType << Input.get()->getSourceRange());
8603
John McCalle3027922010-08-25 11:45:40 +00008604 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008605 Input = UsualUnaryConversions(Input.take());
8606 if (Input.isInvalid()) return ExprError();
8607 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008608 if (resultType->isDependentType())
8609 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008610 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8611 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8612 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008613 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008614 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008615 else if (resultType->hasIntegerRepresentation())
8616 break;
John McCall526ab472011-10-25 17:37:35 +00008617 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008618 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008619 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008620 }
Steve Naroff35d85152007-05-07 00:24:15 +00008621 break;
John Wiegley01296292011-04-08 18:41:53 +00008622
John McCalle3027922010-08-25 11:45:40 +00008623 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008624 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008625 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8626 if (Input.isInvalid()) return ExprError();
8627 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008628
8629 // Though we still have to promote half FP to float...
8630 if (resultType->isHalfType()) {
8631 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8632 resultType = Context.FloatTy;
8633 }
8634
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008635 if (resultType->isDependentType())
8636 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008637 if (resultType->isScalarType()) {
8638 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008639 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008640 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8641 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008642 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8643 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008644 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008645 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008646 // Vector logical not returns the signed variant of the operand type.
8647 resultType = GetSignedVectorType(resultType);
8648 break;
John McCall36226622010-10-12 02:09:17 +00008649 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008650 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008651 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008652 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008653
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008654 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008655 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008656 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008657 break;
John McCalle3027922010-08-25 11:45:40 +00008658 case UO_Real:
8659 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008660 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008661 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8662 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008663 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008664 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8665 if (Input.get()->getValueKind() != VK_RValue &&
8666 Input.get()->getObjectKind() == OK_Ordinary)
8667 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008668 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008669 // In C, a volatile scalar is read by __imag. In C++, it is not.
8670 Input = DefaultLvalueConversion(Input.take());
8671 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008672 break;
John McCalle3027922010-08-25 11:45:40 +00008673 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008674 resultType = Input.get()->getType();
8675 VK = Input.get()->getValueKind();
8676 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008677 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008678 }
John Wiegley01296292011-04-08 18:41:53 +00008679 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008680 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008681
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008682 // Check for array bounds violations in the operand of the UnaryOperator,
8683 // except for the '*' and '&' operators that have to be handled specially
8684 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8685 // that are explicitly defined as valid by the standard).
8686 if (Opc != UO_AddrOf && Opc != UO_Deref)
8687 CheckArrayAccess(Input.get());
8688
John Wiegley01296292011-04-08 18:41:53 +00008689 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008690 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008691}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008692
Douglas Gregor72341032011-12-14 21:23:13 +00008693/// \brief Determine whether the given expression is a qualified member
8694/// access expression, of a form that could be turned into a pointer to member
8695/// with the address-of operator.
8696static bool isQualifiedMemberAccess(Expr *E) {
8697 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8698 if (!DRE->getQualifier())
8699 return false;
8700
8701 ValueDecl *VD = DRE->getDecl();
8702 if (!VD->isCXXClassMember())
8703 return false;
8704
8705 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8706 return true;
8707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8708 return Method->isInstance();
8709
8710 return false;
8711 }
8712
8713 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8714 if (!ULE->getQualifier())
8715 return false;
8716
8717 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8718 DEnd = ULE->decls_end();
8719 D != DEnd; ++D) {
8720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8721 if (Method->isInstance())
8722 return true;
8723 } else {
8724 // Overload set does not contain methods.
8725 break;
8726 }
8727 }
8728
8729 return false;
8730 }
8731
8732 return false;
8733}
8734
John McCalldadc5752010-08-24 06:29:42 +00008735ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008736 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008737 // First things first: handle placeholders so that the
8738 // overloaded-operator check considers the right type.
8739 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8740 // Increment and decrement of pseudo-object references.
8741 if (pty->getKind() == BuiltinType::PseudoObject &&
8742 UnaryOperator::isIncrementDecrementOp(Opc))
8743 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8744
8745 // extension is always a builtin operator.
8746 if (Opc == UO_Extension)
8747 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8748
8749 // & gets special logic for several kinds of placeholder.
8750 // The builtin code knows what to do.
8751 if (Opc == UO_AddrOf &&
8752 (pty->getKind() == BuiltinType::Overload ||
8753 pty->getKind() == BuiltinType::UnknownAny ||
8754 pty->getKind() == BuiltinType::BoundMember))
8755 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8756
8757 // Anything else needs to be handled now.
8758 ExprResult Result = CheckPlaceholderExpr(Input);
8759 if (Result.isInvalid()) return ExprError();
8760 Input = Result.take();
8761 }
8762
David Blaikiebbafb8a2012-03-11 07:00:24 +00008763 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008764 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8765 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008766 // Find all of the overloaded operators visible from this
8767 // point. We perform both an operator-name lookup from the local
8768 // scope and an argument-dependent lookup based on the types of
8769 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008770 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008771 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008772 if (S && OverOp != OO_None)
8773 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8774 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008775
John McCallb268a282010-08-23 23:25:46 +00008776 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008777 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008778
John McCallb268a282010-08-23 23:25:46 +00008779 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008780}
8781
Douglas Gregor5287f092009-11-05 00:51:44 +00008782// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008783ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008784 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008785 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008786}
8787
Steve Naroff66356bd2007-09-16 14:56:35 +00008788/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008789ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008790 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008791 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008792 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008793 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008794 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008795}
8796
John McCall31168b02011-06-15 23:02:42 +00008797/// Given the last statement in a statement-expression, check whether
8798/// the result is a producing expression (like a call to an
8799/// ns_returns_retained function) and, if so, rebuild it to hoist the
8800/// release out of the full-expression. Otherwise, return null.
8801/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008802static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008803 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008804 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008805 if (!cleanups) return 0;
8806
8807 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008808 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008809 return 0;
8810
8811 // Splice out the cast. This shouldn't modify any interesting
8812 // features of the statement.
8813 Expr *producer = cast->getSubExpr();
8814 assert(producer->getType() == cast->getType());
8815 assert(producer->getValueKind() == cast->getValueKind());
8816 cleanups->setSubExpr(producer);
8817 return cleanups;
8818}
8819
John McCall3abee492012-04-04 01:27:53 +00008820void Sema::ActOnStartStmtExpr() {
8821 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8822}
8823
8824void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008825 // Note that function is also called by TreeTransform when leaving a
8826 // StmtExpr scope without rebuilding anything.
8827
John McCall3abee492012-04-04 01:27:53 +00008828 DiscardCleanupsInEvaluationContext();
8829 PopExpressionEvaluationContext();
8830}
8831
John McCalldadc5752010-08-24 06:29:42 +00008832ExprResult
John McCallb268a282010-08-23 23:25:46 +00008833Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008834 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008835 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8836 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8837
John McCall3abee492012-04-04 01:27:53 +00008838 if (hasAnyUnrecoverableErrorsInThisFunction())
8839 DiscardCleanupsInEvaluationContext();
8840 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8841 PopExpressionEvaluationContext();
8842
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008843 bool isFileScope
8844 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008845 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008846 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008847
Chris Lattner366727f2007-07-24 16:58:17 +00008848 // FIXME: there are a variety of strange constraints to enforce here, for
8849 // example, it is not possible to goto into a stmt expression apparently.
8850 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008851
Chris Lattner366727f2007-07-24 16:58:17 +00008852 // If there are sub stmts in the compound stmt, take the type of the last one
8853 // as the type of the stmtexpr.
8854 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008855 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008856 if (!Compound->body_empty()) {
8857 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008858 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008859 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008860 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8861 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008862 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008863 }
John McCall31168b02011-06-15 23:02:42 +00008864
John Wiegley01296292011-04-08 18:41:53 +00008865 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008866 // Do function/array conversion on the last expression, but not
8867 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008868 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8869 if (LastExpr.isInvalid())
8870 return ExprError();
8871 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008872
John Wiegley01296292011-04-08 18:41:53 +00008873 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008874 // In ARC, if the final expression ends in a consume, splice
8875 // the consume out and bind it later. In the alternate case
8876 // (when dealing with a retainable type), the result
8877 // initialization will create a produce. In both cases the
8878 // result will be +1, and we'll need to balance that out with
8879 // a bind.
8880 if (Expr *rebuiltLastStmt
8881 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8882 LastExpr = rebuiltLastStmt;
8883 } else {
8884 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008885 InitializedEntity::InitializeResult(LPLoc,
8886 Ty,
8887 false),
8888 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008889 LastExpr);
8890 }
8891
John Wiegley01296292011-04-08 18:41:53 +00008892 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008893 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008894 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008895 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008896 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008897 else
John Wiegley01296292011-04-08 18:41:53 +00008898 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008899 StmtExprMayBindToTemp = true;
8900 }
8901 }
8902 }
Chris Lattner944d3062008-07-26 19:51:01 +00008903 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008904
Eli Friedmanba961a92009-03-23 00:24:07 +00008905 // FIXME: Check that expression type is complete/non-abstract; statement
8906 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008907 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8908 if (StmtExprMayBindToTemp)
8909 return MaybeBindToTemporary(ResStmtExpr);
8910 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008911}
Steve Naroff78864672007-08-01 22:05:33 +00008912
John McCalldadc5752010-08-24 06:29:42 +00008913ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008914 TypeSourceInfo *TInfo,
8915 OffsetOfComponent *CompPtr,
8916 unsigned NumComponents,
8917 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008918 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008919 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008920 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008921
Chris Lattnerf17bd422007-08-30 17:45:32 +00008922 // We must have at least one component that refers to the type, and the first
8923 // one is known to be a field designator. Verify that the ArgTy represents
8924 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008925 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008926 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8927 << ArgTy << TypeRange);
8928
8929 // Type must be complete per C99 7.17p3 because a declaring a variable
8930 // with an incomplete type would be ill-formed.
8931 if (!Dependent
8932 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008933 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00008934 return ExprError();
8935
Chris Lattner78502cf2007-08-31 21:49:13 +00008936 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8937 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008938 // FIXME: This diagnostic isn't actually visible because the location is in
8939 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008940 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008941 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8942 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008943
8944 bool DidWarnAboutNonPOD = false;
8945 QualType CurrentType = ArgTy;
8946 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008947 SmallVector<OffsetOfNode, 4> Comps;
8948 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008949 for (unsigned i = 0; i != NumComponents; ++i) {
8950 const OffsetOfComponent &OC = CompPtr[i];
8951 if (OC.isBrackets) {
8952 // Offset of an array sub-field. TODO: Should we allow vector elements?
8953 if (!CurrentType->isDependentType()) {
8954 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8955 if(!AT)
8956 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8957 << CurrentType);
8958 CurrentType = AT->getElementType();
8959 } else
8960 CurrentType = Context.DependentTy;
8961
Richard Smith9fcc5c32011-10-17 23:29:39 +00008962 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8963 if (IdxRval.isInvalid())
8964 return ExprError();
8965 Expr *Idx = IdxRval.take();
8966
Douglas Gregor882211c2010-04-28 22:16:22 +00008967 // The expression must be an integral expression.
8968 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008969 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8970 !Idx->getType()->isIntegerType())
8971 return ExprError(Diag(Idx->getLocStart(),
8972 diag::err_typecheck_subscript_not_integer)
8973 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008974
Douglas Gregor882211c2010-04-28 22:16:22 +00008975 // Record this array index.
8976 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008977 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008978 continue;
8979 }
8980
8981 // Offset of a field.
8982 if (CurrentType->isDependentType()) {
8983 // We have the offset of a field, but we can't look into the dependent
8984 // type. Just record the identifier of the field.
8985 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8986 CurrentType = Context.DependentTy;
8987 continue;
8988 }
8989
8990 // We need to have a complete type to look into.
8991 if (RequireCompleteType(OC.LocStart, CurrentType,
8992 diag::err_offsetof_incomplete_type))
8993 return ExprError();
8994
8995 // Look for the designated field.
8996 const RecordType *RC = CurrentType->getAs<RecordType>();
8997 if (!RC)
8998 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8999 << CurrentType);
9000 RecordDecl *RD = RC->getDecl();
9001
9002 // C++ [lib.support.types]p5:
9003 // The macro offsetof accepts a restricted set of type arguments in this
9004 // International Standard. type shall be a POD structure or a POD union
9005 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009006 // C++11 [support.types]p4:
9007 // If type is not a standard-layout class (Clause 9), the results are
9008 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009009 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009010 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9011 unsigned DiagID =
9012 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9013 : diag::warn_offsetof_non_pod_type;
9014
9015 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009016 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009017 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009018 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9019 << CurrentType))
9020 DidWarnAboutNonPOD = true;
9021 }
9022
9023 // Look for the field.
9024 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9025 LookupQualifiedName(R, RD);
9026 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009027 IndirectFieldDecl *IndirectMemberDecl = 0;
9028 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009029 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009030 MemberDecl = IndirectMemberDecl->getAnonField();
9031 }
9032
Douglas Gregor882211c2010-04-28 22:16:22 +00009033 if (!MemberDecl)
9034 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9035 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9036 OC.LocEnd));
9037
Douglas Gregor10982ea2010-04-28 22:36:06 +00009038 // C99 7.17p3:
9039 // (If the specified member is a bit-field, the behavior is undefined.)
9040 //
9041 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009042 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009043 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9044 << MemberDecl->getDeclName()
9045 << SourceRange(BuiltinLoc, RParenLoc);
9046 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9047 return ExprError();
9048 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009049
9050 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009051 if (IndirectMemberDecl)
9052 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009053
Douglas Gregord1702062010-04-29 00:18:15 +00009054 // If the member was found in a base class, introduce OffsetOfNodes for
9055 // the base class indirections.
9056 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9057 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009058 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009059 CXXBasePath &Path = Paths.front();
9060 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9061 B != BEnd; ++B)
9062 Comps.push_back(OffsetOfNode(B->Base));
9063 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009064
Francois Pichet783dd6e2010-11-21 06:08:52 +00009065 if (IndirectMemberDecl) {
9066 for (IndirectFieldDecl::chain_iterator FI =
9067 IndirectMemberDecl->chain_begin(),
9068 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9069 assert(isa<FieldDecl>(*FI));
9070 Comps.push_back(OffsetOfNode(OC.LocStart,
9071 cast<FieldDecl>(*FI), OC.LocEnd));
9072 }
9073 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009074 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009075
Douglas Gregor882211c2010-04-28 22:16:22 +00009076 CurrentType = MemberDecl->getType().getNonReferenceType();
9077 }
9078
9079 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9080 TInfo, Comps.data(), Comps.size(),
9081 Exprs.data(), Exprs.size(), RParenLoc));
9082}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009083
John McCalldadc5752010-08-24 06:29:42 +00009084ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009085 SourceLocation BuiltinLoc,
9086 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009087 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009088 OffsetOfComponent *CompPtr,
9089 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009090 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009091
Douglas Gregor882211c2010-04-28 22:16:22 +00009092 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009093 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009094 if (ArgTy.isNull())
9095 return ExprError();
9096
Eli Friedman06dcfd92010-08-05 10:15:45 +00009097 if (!ArgTInfo)
9098 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9099
9100 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009101 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009102}
9103
9104
John McCalldadc5752010-08-24 06:29:42 +00009105ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009106 Expr *CondExpr,
9107 Expr *LHSExpr, Expr *RHSExpr,
9108 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009109 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9110
John McCall7decc9e2010-11-18 06:31:45 +00009111 ExprValueKind VK = VK_RValue;
9112 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009113 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009114 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009115 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009116 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009117 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009118 } else {
9119 // The conditional expression is required to be a constant expression.
9120 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009121 ExprResult CondICE
9122 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9123 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009124 if (CondICE.isInvalid())
9125 return ExprError();
9126 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009127
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009128 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009129 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9130
9131 resType = ActiveExpr->getType();
9132 ValueDependent = ActiveExpr->isValueDependent();
9133 VK = ActiveExpr->getValueKind();
9134 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009135 }
9136
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009137 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009138 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009139 resType->isDependentType(),
9140 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009141}
9142
Steve Naroffc540d662008-09-03 18:15:37 +00009143//===----------------------------------------------------------------------===//
9144// Clang Extensions.
9145//===----------------------------------------------------------------------===//
9146
9147/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009148void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009149 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009150 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009151 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009152 if (CurScope)
9153 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009154 else
9155 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009156
Eli Friedman34b49062012-01-26 03:00:14 +00009157 getCurBlock()->HasImplicitReturnType = true;
9158
John McCallf1a3c2a2011-11-11 03:19:12 +00009159 // Enter a new evaluation context to insulate the block from any
9160 // cleanups from the enclosing full-expression.
9161 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009162}
9163
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009164void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9165 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009166 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009167 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009168 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009169
John McCall8cb7bdf2010-06-04 23:28:52 +00009170 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009171 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009172
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009173 // FIXME: We should allow unexpanded parameter packs here, but that would,
9174 // in turn, make the block expression contain unexpanded parameter packs.
9175 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9176 // Drop the parameters.
9177 FunctionProtoType::ExtProtoInfo EPI;
9178 EPI.HasTrailingReturn = false;
9179 EPI.TypeQuals |= DeclSpec::TQ_const;
9180 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9181 EPI);
9182 Sig = Context.getTrivialTypeSourceInfo(T);
9183 }
9184
John McCall3882ace2011-01-05 12:14:39 +00009185 // GetTypeForDeclarator always produces a function type for a block
9186 // literal signature. Furthermore, it is always a FunctionProtoType
9187 // unless the function was written with a typedef.
9188 assert(T->isFunctionType() &&
9189 "GetTypeForDeclarator made a non-function block signature");
9190
9191 // Look for an explicit signature in that function type.
9192 FunctionProtoTypeLoc ExplicitSignature;
9193
9194 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9195 if (isa<FunctionProtoTypeLoc>(tmp)) {
9196 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9197
9198 // Check whether that explicit signature was synthesized by
9199 // GetTypeForDeclarator. If so, don't save that as part of the
9200 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009201 if (ExplicitSignature.getLocalRangeBegin() ==
9202 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009203 // This would be much cheaper if we stored TypeLocs instead of
9204 // TypeSourceInfos.
9205 TypeLoc Result = ExplicitSignature.getResultLoc();
9206 unsigned Size = Result.getFullDataSize();
9207 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9208 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9209
9210 ExplicitSignature = FunctionProtoTypeLoc();
9211 }
John McCalla3ccba02010-06-04 11:21:44 +00009212 }
Mike Stump11289f42009-09-09 15:08:12 +00009213
John McCall3882ace2011-01-05 12:14:39 +00009214 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9215 CurBlock->FunctionType = T;
9216
9217 const FunctionType *Fn = T->getAs<FunctionType>();
9218 QualType RetTy = Fn->getResultType();
9219 bool isVariadic =
9220 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9221
John McCall8e346702010-06-04 19:02:56 +00009222 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009223
John McCalla3ccba02010-06-04 11:21:44 +00009224 // Don't allow returning a objc interface by value.
9225 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009226 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009227 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9228 return;
9229 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009230
John McCalla3ccba02010-06-04 11:21:44 +00009231 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009232 // return type. TODO: what should we do with declarators like:
9233 // ^ * { ... }
9234 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009235 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009236 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009237 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009238 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009239 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009240
John McCalla3ccba02010-06-04 11:21:44 +00009241 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009242 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009243 if (ExplicitSignature) {
9244 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9245 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009246 if (Param->getIdentifier() == 0 &&
9247 !Param->isImplicit() &&
9248 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009249 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009250 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009251 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009252 }
John McCalla3ccba02010-06-04 11:21:44 +00009253
9254 // Fake up parameter variables if we have a typedef, like
9255 // ^ fntype { ... }
9256 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9257 for (FunctionProtoType::arg_type_iterator
9258 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9259 ParmVarDecl *Param =
9260 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009261 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009262 *I);
John McCall8e346702010-06-04 19:02:56 +00009263 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009264 }
Steve Naroffc540d662008-09-03 18:15:37 +00009265 }
John McCalla3ccba02010-06-04 11:21:44 +00009266
John McCall8e346702010-06-04 19:02:56 +00009267 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009268 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009269 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009270 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9271 CurBlock->TheDecl->param_end(),
9272 /*CheckParameterNames=*/false);
9273 }
9274
John McCalla3ccba02010-06-04 11:21:44 +00009275 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009276 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009277
John McCalla3ccba02010-06-04 11:21:44 +00009278 // Put the parameter variables in scope. We can bail out immediately
9279 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009280 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009281 return;
9282
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009283 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009284 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9285 (*AI)->setOwningFunction(CurBlock->TheDecl);
9286
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009287 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009288 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009289 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009290
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009291 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009292 }
John McCallf7b2fb52010-01-22 00:28:27 +00009293 }
Steve Naroffc540d662008-09-03 18:15:37 +00009294}
9295
9296/// ActOnBlockError - If there is an error parsing a block, this callback
9297/// is invoked to pop the information about the block from the action impl.
9298void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009299 // Leave the expression-evaluation context.
9300 DiscardCleanupsInEvaluationContext();
9301 PopExpressionEvaluationContext();
9302
Steve Naroffc540d662008-09-03 18:15:37 +00009303 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009304 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009305 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009306}
9307
9308/// ActOnBlockStmtExpr - This is called when the body of a block statement
9309/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009310ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009311 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009312 // If blocks are disabled, emit an error.
9313 if (!LangOpts.Blocks)
9314 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009315
John McCallf1a3c2a2011-11-11 03:19:12 +00009316 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009317 if (hasAnyUnrecoverableErrorsInThisFunction())
9318 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009319 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9320 PopExpressionEvaluationContext();
9321
Douglas Gregor9a28e842010-03-01 23:15:13 +00009322 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009323
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009324 PopDeclContext();
9325
Steve Naroffc540d662008-09-03 18:15:37 +00009326 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009327 if (!BSI->ReturnType.isNull())
9328 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009329
Mike Stump3bf1ab42009-07-28 22:04:01 +00009330 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009331 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009332
John McCallc63de662011-02-02 13:00:07 +00009333 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009334 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9335 SmallVector<BlockDecl::Capture, 4> Captures;
9336 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9337 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9338 if (Cap.isThisCapture())
9339 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009340 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009341 Cap.isNested(), Cap.getCopyExpr());
9342 Captures.push_back(NewCap);
9343 }
9344 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9345 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009346
John McCall8e346702010-06-04 19:02:56 +00009347 // If the user wrote a function type in some form, try to use that.
9348 if (!BSI->FunctionType.isNull()) {
9349 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9350
9351 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9352 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9353
9354 // Turn protoless block types into nullary block types.
9355 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009356 FunctionProtoType::ExtProtoInfo EPI;
9357 EPI.ExtInfo = Ext;
9358 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009359
9360 // Otherwise, if we don't need to change anything about the function type,
9361 // preserve its sugar structure.
9362 } else if (FTy->getResultType() == RetTy &&
9363 (!NoReturn || FTy->getNoReturnAttr())) {
9364 BlockTy = BSI->FunctionType;
9365
9366 // Otherwise, make the minimal modifications to the function type.
9367 } else {
9368 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009369 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9370 EPI.TypeQuals = 0; // FIXME: silently?
9371 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009372 BlockTy = Context.getFunctionType(RetTy,
9373 FPT->arg_type_begin(),
9374 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009375 EPI);
John McCall8e346702010-06-04 19:02:56 +00009376 }
9377
9378 // If we don't have a function type, just build one from nothing.
9379 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009380 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009381 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009382 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009383 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009384
John McCall8e346702010-06-04 19:02:56 +00009385 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9386 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009387 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009388
Chris Lattner45542ea2009-04-19 05:28:12 +00009389 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009390 if (getCurFunction()->NeedsScopeChecking() &&
9391 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009392 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009393
Chris Lattner60f84492011-02-17 23:58:47 +00009394 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009395
Douglas Gregor49695f02011-09-06 20:46:03 +00009396 computeNRVO(Body, getCurBlock());
9397
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009398 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9399 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009400 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009401
John McCall28fc7092011-11-10 05:35:25 +00009402 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009403 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009404 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009405 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009406 ExprCleanupObjects.push_back(Result->getBlockDecl());
9407 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009408
9409 // It also gets a branch-protected scope if any of the captured
9410 // variables needs destruction.
9411 for (BlockDecl::capture_const_iterator
9412 ci = Result->getBlockDecl()->capture_begin(),
9413 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9414 const VarDecl *var = ci->getVariable();
9415 if (var->getType().isDestructedType() != QualType::DK_none) {
9416 getCurFunction()->setHasBranchProtectedScope();
9417 break;
9418 }
9419 }
John McCall28fc7092011-11-10 05:35:25 +00009420 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009421
Douglas Gregor9a28e842010-03-01 23:15:13 +00009422 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009423}
9424
John McCalldadc5752010-08-24 06:29:42 +00009425ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009426 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009427 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009428 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009429 GetTypeFromParser(Ty, &TInfo);
9430 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009431}
9432
John McCalldadc5752010-08-24 06:29:42 +00009433ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009434 Expr *E, TypeSourceInfo *TInfo,
9435 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009436 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009437
Eli Friedman121ba0c2008-08-09 23:32:40 +00009438 // Get the va_list type
9439 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009440 if (VaListType->isArrayType()) {
9441 // Deal with implicit array decay; for example, on x86-64,
9442 // va_list is an array, but it's supposed to decay to
9443 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009444 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009445 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009446 ExprResult Result = UsualUnaryConversions(E);
9447 if (Result.isInvalid())
9448 return ExprError();
9449 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009450 } else {
9451 // Otherwise, the va_list argument must be an l-value because
9452 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009453 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009454 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009455 return ExprError();
9456 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009457
Douglas Gregorad3150c2009-05-19 23:10:31 +00009458 if (!E->isTypeDependent() &&
9459 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009460 return ExprError(Diag(E->getLocStart(),
9461 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009462 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009463 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009464
David Majnemerc75d1a12011-06-14 05:17:32 +00009465 if (!TInfo->getType()->isDependentType()) {
9466 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009467 diag::err_second_parameter_to_va_arg_incomplete,
9468 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009469 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009470
David Majnemerc75d1a12011-06-14 05:17:32 +00009471 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009472 TInfo->getType(),
9473 diag::err_second_parameter_to_va_arg_abstract,
9474 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009475 return ExprError();
9476
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009477 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009478 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009479 TInfo->getType()->isObjCLifetimeType()
9480 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9481 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009482 << TInfo->getType()
9483 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009484 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009485
9486 // Check for va_arg where arguments of the given type will be promoted
9487 // (i.e. this va_arg is guaranteed to have undefined behavior).
9488 QualType PromoteType;
9489 if (TInfo->getType()->isPromotableIntegerType()) {
9490 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9491 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9492 PromoteType = QualType();
9493 }
9494 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9495 PromoteType = Context.DoubleTy;
9496 if (!PromoteType.isNull())
9497 Diag(TInfo->getTypeLoc().getBeginLoc(),
9498 diag::warn_second_parameter_to_va_arg_never_compatible)
9499 << TInfo->getType()
9500 << PromoteType
9501 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009502 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009503
Abramo Bagnara27db2392010-08-10 10:06:15 +00009504 QualType T = TInfo->getType().getNonLValueExprType(Context);
9505 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009506}
9507
John McCalldadc5752010-08-24 06:29:42 +00009508ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009509 // The type of __null will be int or long, depending on the size of
9510 // pointers on the target.
9511 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009512 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9513 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009514 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009515 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009516 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009517 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009518 Ty = Context.LongLongTy;
9519 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009520 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009521 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009522
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009523 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009524}
9525
Alexis Huntc46382e2010-04-28 23:02:27 +00009526static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009527 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009528 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009529 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009530
Anders Carlssonace5d072009-11-10 04:46:30 +00009531 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9532 if (!PT)
9533 return;
9534
9535 // Check if the destination is of type 'id'.
9536 if (!PT->isObjCIdType()) {
9537 // Check if the destination is the 'NSString' interface.
9538 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9539 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9540 return;
9541 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009542
John McCallfe96e0b2011-11-06 09:01:30 +00009543 // Ignore any parens, implicit casts (should only be
9544 // array-to-pointer decays), and not-so-opaque values. The last is
9545 // important for making this trigger for property assignments.
9546 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9547 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9548 if (OV->getSourceExpr())
9549 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9550
9551 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009552 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009553 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009554
Douglas Gregora771f462010-03-31 17:46:05 +00009555 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009556}
9557
Chris Lattner9bad62c2008-01-04 18:04:52 +00009558bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9559 SourceLocation Loc,
9560 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009561 Expr *SrcExpr, AssignmentAction Action,
9562 bool *Complained) {
9563 if (Complained)
9564 *Complained = false;
9565
Chris Lattner9bad62c2008-01-04 18:04:52 +00009566 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009567 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009568 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009569 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009570 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009571 ConversionFixItGenerator ConvHints;
9572 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009573 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009574
Chris Lattner9bad62c2008-01-04 18:04:52 +00009575 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009576 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009577 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009578 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009579 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9580 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009581 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009582 case IntToPointer:
9583 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009584 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9585 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009586 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009587 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009588 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009589 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009590 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9591 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009592 if (Hint.isNull() && !CheckInferredResultType) {
9593 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9594 }
9595 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009596 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009597 case IncompatiblePointerSign:
9598 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9599 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009600 case FunctionVoidPointer:
9601 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9602 break;
John McCall4fff8f62011-02-01 00:10:29 +00009603 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009604 // Perform array-to-pointer decay if necessary.
9605 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9606
John McCall4fff8f62011-02-01 00:10:29 +00009607 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9608 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9609 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9610 DiagKind = diag::err_typecheck_incompatible_address_space;
9611 break;
John McCall31168b02011-06-15 23:02:42 +00009612
9613
9614 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009615 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009616 break;
John McCall4fff8f62011-02-01 00:10:29 +00009617 }
9618
9619 llvm_unreachable("unknown error case for discarding qualifiers!");
9620 // fallthrough
9621 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009622 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009623 // If the qualifiers lost were because we were applying the
9624 // (deprecated) C++ conversion from a string literal to a char*
9625 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9626 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009627 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009628 // bit of refactoring (so that the second argument is an
9629 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009630 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009631 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009632 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009633 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9634 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009635 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9636 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009637 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009638 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009639 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009640 case IntToBlockPointer:
9641 DiagKind = diag::err_int_to_block_pointer;
9642 break;
9643 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009644 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009645 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009646 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009647 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009648 // it can give a more specific diagnostic.
9649 DiagKind = diag::warn_incompatible_qualified_id;
9650 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009651 case IncompatibleVectors:
9652 DiagKind = diag::warn_incompatible_vectors;
9653 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009654 case IncompatibleObjCWeakRef:
9655 DiagKind = diag::err_arc_weak_unavailable_assign;
9656 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009657 case Incompatible:
9658 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009659 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9660 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009661 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009662 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009663 break;
9664 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009665
Douglas Gregorc68e1402010-04-09 00:35:39 +00009666 QualType FirstType, SecondType;
9667 switch (Action) {
9668 case AA_Assigning:
9669 case AA_Initializing:
9670 // The destination type comes first.
9671 FirstType = DstType;
9672 SecondType = SrcType;
9673 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009674
Douglas Gregorc68e1402010-04-09 00:35:39 +00009675 case AA_Returning:
9676 case AA_Passing:
9677 case AA_Converting:
9678 case AA_Sending:
9679 case AA_Casting:
9680 // The source type comes first.
9681 FirstType = SrcType;
9682 SecondType = DstType;
9683 break;
9684 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009685
Anna Zaks3b402712011-07-28 19:51:27 +00009686 PartialDiagnostic FDiag = PDiag(DiagKind);
9687 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9688
9689 // If we can fix the conversion, suggest the FixIts.
9690 assert(ConvHints.isNull() || Hint.isNull());
9691 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009692 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9693 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009694 FDiag << *HI;
9695 } else {
9696 FDiag << Hint;
9697 }
9698 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9699
Richard Trieucaff2472011-11-23 22:32:32 +00009700 if (MayHaveFunctionDiff)
9701 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9702
Anna Zaks3b402712011-07-28 19:51:27 +00009703 Diag(Loc, FDiag);
9704
Richard Trieucaff2472011-11-23 22:32:32 +00009705 if (SecondType == Context.OverloadTy)
9706 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9707 FirstType);
9708
Douglas Gregor33823722011-06-11 01:09:30 +00009709 if (CheckInferredResultType)
9710 EmitRelatedResultTypeNote(SrcExpr);
9711
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009712 if (Complained)
9713 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009714 return isInvalid;
9715}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009716
Richard Smithf4c51d92012-02-04 09:53:13 +00009717ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9718 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009719 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9720 public:
9721 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9722 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9723 }
9724 } Diagnoser;
9725
9726 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9727}
9728
9729ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9730 llvm::APSInt *Result,
9731 unsigned DiagID,
9732 bool AllowFold) {
9733 class IDDiagnoser : public VerifyICEDiagnoser {
9734 unsigned DiagID;
9735
9736 public:
9737 IDDiagnoser(unsigned DiagID)
9738 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9739
9740 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9741 S.Diag(Loc, DiagID) << SR;
9742 }
9743 } Diagnoser(DiagID);
9744
9745 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9746}
9747
9748void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9749 SourceRange SR) {
9750 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009751}
9752
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009753ExprResult
9754Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009755 VerifyICEDiagnoser &Diagnoser,
9756 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009757 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009758
David Blaikiebbafb8a2012-03-11 07:00:24 +00009759 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009760 // C++11 [expr.const]p5:
9761 // If an expression of literal class type is used in a context where an
9762 // integral constant expression is required, then that class type shall
9763 // have a single non-explicit conversion function to an integral or
9764 // unscoped enumeration type
9765 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009766 if (!Diagnoser.Suppress) {
9767 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9768 public:
9769 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9770
9771 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9772 QualType T) {
9773 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9774 }
9775
9776 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9777 SourceLocation Loc,
9778 QualType T) {
9779 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9780 }
9781
9782 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9783 SourceLocation Loc,
9784 QualType T,
9785 QualType ConvTy) {
9786 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9787 }
9788
9789 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9790 CXXConversionDecl *Conv,
9791 QualType ConvTy) {
9792 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9793 << ConvTy->isEnumeralType() << ConvTy;
9794 }
9795
9796 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9797 QualType T) {
9798 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9799 }
9800
9801 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9802 CXXConversionDecl *Conv,
9803 QualType ConvTy) {
9804 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9805 << ConvTy->isEnumeralType() << ConvTy;
9806 }
9807
9808 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9809 SourceLocation Loc,
9810 QualType T,
9811 QualType ConvTy) {
9812 return DiagnosticBuilder::getEmpty();
9813 }
9814 } ConvertDiagnoser;
9815
9816 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9817 ConvertDiagnoser,
9818 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009819 } else {
9820 // The caller wants to silently enquire whether this is an ICE. Don't
9821 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009822 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9823 public:
9824 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9825
9826 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9827 QualType T) {
9828 return DiagnosticBuilder::getEmpty();
9829 }
9830
9831 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9832 SourceLocation Loc,
9833 QualType T) {
9834 return DiagnosticBuilder::getEmpty();
9835 }
9836
9837 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9838 SourceLocation Loc,
9839 QualType T,
9840 QualType ConvTy) {
9841 return DiagnosticBuilder::getEmpty();
9842 }
9843
9844 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9845 CXXConversionDecl *Conv,
9846 QualType ConvTy) {
9847 return DiagnosticBuilder::getEmpty();
9848 }
9849
9850 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9851 QualType T) {
9852 return DiagnosticBuilder::getEmpty();
9853 }
9854
9855 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9856 CXXConversionDecl *Conv,
9857 QualType ConvTy) {
9858 return DiagnosticBuilder::getEmpty();
9859 }
9860
9861 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9862 SourceLocation Loc,
9863 QualType T,
9864 QualType ConvTy) {
9865 return DiagnosticBuilder::getEmpty();
9866 }
9867 } ConvertDiagnoser;
9868
9869 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9870 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009871 }
9872 if (Converted.isInvalid())
9873 return Converted;
9874 E = Converted.take();
9875 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9876 return ExprError();
9877 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9878 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009879 if (!Diagnoser.Suppress)
9880 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +00009881 return ExprError();
9882 }
9883
Richard Smith902ca212011-12-14 23:32:26 +00009884 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9885 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009886 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009887 if (Result)
9888 *Result = E->EvaluateKnownConstInt(Context);
9889 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009890 }
9891
Anders Carlssone54e8a12008-11-30 19:50:32 +00009892 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009893 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9894 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009895
Richard Smith902ca212011-12-14 23:32:26 +00009896 // Try to evaluate the expression, and produce diagnostics explaining why it's
9897 // not a constant expression as a side-effect.
9898 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9899 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9900
9901 // In C++11, we can rely on diagnostics being produced for any expression
9902 // which is not a constant expression. If no diagnostics were produced, then
9903 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009904 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +00009905 if (Result)
9906 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009907 return Owned(E);
9908 }
9909
9910 // If our only note is the usual "invalid subexpression" note, just point
9911 // the caret at its location rather than producing an essentially
9912 // redundant note.
9913 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9914 diag::note_invalid_subexpr_in_const_expr) {
9915 DiagLoc = Notes[0].first;
9916 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009917 }
9918
9919 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009920 if (!Diagnoser.Suppress) {
9921 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +00009922 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9923 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009924 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009925
Richard Smithf4c51d92012-02-04 09:53:13 +00009926 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009927 }
9928
Douglas Gregore2b37442012-05-04 22:38:52 +00009929 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +00009930 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9931 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009932
Anders Carlssone54e8a12008-11-30 19:50:32 +00009933 if (Result)
9934 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009935 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009936}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009937
Eli Friedman456f0182012-01-20 01:26:23 +00009938namespace {
9939 // Handle the case where we conclude a expression which we speculatively
9940 // considered to be unevaluated is actually evaluated.
9941 class TransformToPE : public TreeTransform<TransformToPE> {
9942 typedef TreeTransform<TransformToPE> BaseTransform;
9943
9944 public:
9945 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9946
9947 // Make sure we redo semantic analysis
9948 bool AlwaysRebuild() { return true; }
9949
Eli Friedman5f0ca242012-02-06 23:29:57 +00009950 // Make sure we handle LabelStmts correctly.
9951 // FIXME: This does the right thing, but maybe we need a more general
9952 // fix to TreeTransform?
9953 StmtResult TransformLabelStmt(LabelStmt *S) {
9954 S->getDecl()->setStmt(0);
9955 return BaseTransform::TransformLabelStmt(S);
9956 }
9957
Eli Friedman456f0182012-01-20 01:26:23 +00009958 // We need to special-case DeclRefExprs referring to FieldDecls which
9959 // are not part of a member pointer formation; normal TreeTransforming
9960 // doesn't catch this case because of the way we represent them in the AST.
9961 // FIXME: This is a bit ugly; is it really the best way to handle this
9962 // case?
9963 //
9964 // Error on DeclRefExprs referring to FieldDecls.
9965 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9966 if (isa<FieldDecl>(E->getDecl()) &&
9967 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9968 return SemaRef.Diag(E->getLocation(),
9969 diag::err_invalid_non_static_member_use)
9970 << E->getDecl() << E->getSourceRange();
9971
9972 return BaseTransform::TransformDeclRefExpr(E);
9973 }
9974
9975 // Exception: filter out member pointer formation
9976 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9977 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9978 return E;
9979
9980 return BaseTransform::TransformUnaryOperator(E);
9981 }
9982
Douglas Gregor89625492012-02-09 08:14:43 +00009983 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9984 // Lambdas never need to be transformed.
9985 return E;
9986 }
Eli Friedman456f0182012-01-20 01:26:23 +00009987 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009988}
9989
Eli Friedman456f0182012-01-20 01:26:23 +00009990ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009991 assert(ExprEvalContexts.back().Context == Unevaluated &&
9992 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009993 ExprEvalContexts.back().Context =
9994 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9995 if (ExprEvalContexts.back().Context == Unevaluated)
9996 return E;
9997 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009998}
9999
Douglas Gregorff790f12009-11-26 00:44:06 +000010000void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010001Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010002 Decl *LambdaContextDecl,
10003 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010004 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010005 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010006 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010007 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010008 LambdaContextDecl,
10009 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010010 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010011 if (!MaybeODRUseExprs.empty())
10012 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010013}
10014
Richard Trieucfc491d2011-08-02 04:35:43 +000010015void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010016 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010017
Douglas Gregor89625492012-02-09 08:14:43 +000010018 if (!Rec.Lambdas.empty()) {
10019 if (Rec.Context == Unevaluated) {
10020 // C++11 [expr.prim.lambda]p2:
10021 // A lambda-expression shall not appear in an unevaluated operand
10022 // (Clause 5).
10023 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10024 Diag(Rec.Lambdas[I]->getLocStart(),
10025 diag::err_lambda_unevaluated_operand);
10026 } else {
10027 // Mark the capture expressions odr-used. This was deferred
10028 // during lambda expression creation.
10029 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10030 LambdaExpr *Lambda = Rec.Lambdas[I];
10031 for (LambdaExpr::capture_init_iterator
10032 C = Lambda->capture_init_begin(),
10033 CEnd = Lambda->capture_init_end();
10034 C != CEnd; ++C) {
10035 MarkDeclarationsReferencedInExpr(*C);
10036 }
10037 }
10038 }
10039 }
10040
Douglas Gregorff790f12009-11-26 00:44:06 +000010041 // When are coming out of an unevaluated context, clear out any
10042 // temporaries that we may have created as part of the evaluation of
10043 // the expression in that context: they aren't relevant because they
10044 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010045 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010046 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10047 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010048 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010049 CleanupVarDeclMarking();
10050 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010051 // Otherwise, merge the contexts together.
10052 } else {
10053 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010054 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10055 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010056 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010057
10058 // Pop the current expression evaluation context off the stack.
10059 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010060}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010061
John McCall31168b02011-06-15 23:02:42 +000010062void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010063 ExprCleanupObjects.erase(
10064 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10065 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010066 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010067 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010068}
10069
Eli Friedmane0afc982012-01-21 01:01:51 +000010070ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10071 if (!E->getType()->isVariablyModifiedType())
10072 return E;
10073 return TranformToPotentiallyEvaluated(E);
10074}
10075
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010076static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010077 // Do not mark anything as "used" within a dependent context; wait for
10078 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010079 if (SemaRef.CurContext->isDependentContext())
10080 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010081
Eli Friedmanfa0df832012-02-02 03:46:19 +000010082 switch (SemaRef.ExprEvalContexts.back().Context) {
10083 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010084 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010085 // (Depending on how you read the standard, we actually do need to do
10086 // something here for null pointer constants, but the standard's
10087 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010088 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010089
Eli Friedmanfa0df832012-02-02 03:46:19 +000010090 case Sema::ConstantEvaluated:
10091 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010092 // We are in a potentially evaluated expression (or a constant-expression
10093 // in C++03); we need to do implicit template instantiation, implicitly
10094 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010095 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010096
Eli Friedmanfa0df832012-02-02 03:46:19 +000010097 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010098 // Referenced declarations will only be used if the construct in the
10099 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010100 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010101 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010102 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010103}
10104
10105/// \brief Mark a function referenced, and check whether it is odr-used
10106/// (C++ [basic.def.odr]p2, C99 6.9p3)
10107void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10108 assert(Func && "No function?");
10109
10110 Func->setReferenced();
10111
Richard Smith4a941e22012-02-14 22:25:15 +000010112 // Don't mark this function as used multiple times, unless it's a constexpr
10113 // function which we need to instantiate.
10114 if (Func->isUsed(false) &&
10115 !(Func->isConstexpr() && !Func->getBody() &&
10116 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010117 return;
10118
10119 if (!IsPotentiallyEvaluatedContext(*this))
10120 return;
Mike Stump11289f42009-09-09 15:08:12 +000010121
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010122 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010123 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010124 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010125 if (Constructor->isDefaultConstructor()) {
10126 if (Constructor->isTrivial())
10127 return;
10128 if (!Constructor->isUsed(false))
10129 DefineImplicitDefaultConstructor(Loc, Constructor);
10130 } else if (Constructor->isCopyConstructor()) {
10131 if (!Constructor->isUsed(false))
10132 DefineImplicitCopyConstructor(Loc, Constructor);
10133 } else if (Constructor->isMoveConstructor()) {
10134 if (!Constructor->isUsed(false))
10135 DefineImplicitMoveConstructor(Loc, Constructor);
10136 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010137 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010138
Douglas Gregor88d292c2010-05-13 16:44:06 +000010139 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010140 } else if (CXXDestructorDecl *Destructor =
10141 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010142 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10143 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010144 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010145 if (Destructor->isVirtual())
10146 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010147 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010148 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10149 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010150 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010151 if (!MethodDecl->isUsed(false)) {
10152 if (MethodDecl->isCopyAssignmentOperator())
10153 DefineImplicitCopyAssignment(Loc, MethodDecl);
10154 else
10155 DefineImplicitMoveAssignment(Loc, MethodDecl);
10156 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010157 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10158 MethodDecl->getParent()->isLambda()) {
10159 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10160 if (Conversion->isLambdaToBlockPointerConversion())
10161 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10162 else
10163 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010164 } else if (MethodDecl->isVirtual())
10165 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010166 }
John McCall83779672011-02-19 02:53:41 +000010167
Eli Friedmanfa0df832012-02-02 03:46:19 +000010168 // Recursive functions should be marked when used from another function.
10169 // FIXME: Is this really right?
10170 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010171
Richard Smithf623c962012-04-17 00:58:00 +000010172 // Instantiate the exception specification for any function which is
10173 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010174 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10175 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +000010176 InstantiateExceptionSpec(Loc, Func);
10177
Eli Friedmanfa0df832012-02-02 03:46:19 +000010178 // Implicit instantiation of function templates and member functions of
10179 // class templates.
10180 if (Func->isImplicitlyInstantiable()) {
10181 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010182 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010183 if (FunctionTemplateSpecializationInfo *SpecInfo
10184 = Func->getTemplateSpecializationInfo()) {
10185 if (SpecInfo->getPointOfInstantiation().isInvalid())
10186 SpecInfo->setPointOfInstantiation(Loc);
10187 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010188 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010189 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010190 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10191 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010192 } else if (MemberSpecializationInfo *MSInfo
10193 = Func->getMemberSpecializationInfo()) {
10194 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010195 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010196 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010197 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010198 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010199 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10200 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010201 }
Mike Stump11289f42009-09-09 15:08:12 +000010202
Richard Smith4a941e22012-02-14 22:25:15 +000010203 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010204 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10205 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010206 PendingLocalImplicitInstantiations.push_back(
10207 std::make_pair(Func, PointOfInstantiation));
10208 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010209 // Do not defer instantiations of constexpr functions, to avoid the
10210 // expression evaluator needing to call back into Sema if it sees a
10211 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010212 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010213 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010214 PendingInstantiations.push_back(std::make_pair(Func,
10215 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010216 // Notify the consumer that a function was implicitly instantiated.
10217 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10218 }
John McCall83779672011-02-19 02:53:41 +000010219 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010220 } else {
10221 // Walk redefinitions, as some of them may be instantiable.
10222 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10223 e(Func->redecls_end()); i != e; ++i) {
10224 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10225 MarkFunctionReferenced(Loc, *i);
10226 }
Sam Weinigbae69142009-09-11 03:29:30 +000010227 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010228
10229 // Keep track of used but undefined functions.
10230 if (!Func->isPure() && !Func->hasBody() &&
10231 Func->getLinkage() != ExternalLinkage) {
10232 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10233 if (old.isInvalid()) old = Loc;
10234 }
10235
10236 Func->setUsed(true);
10237}
10238
Eli Friedman9bb33f52012-02-03 02:04:35 +000010239static void
10240diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10241 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010242 DeclContext *VarDC = var->getDeclContext();
10243
Eli Friedman9bb33f52012-02-03 02:04:35 +000010244 // If the parameter still belongs to the translation unit, then
10245 // we're actually just using one parameter in the declaration of
10246 // the next.
10247 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010248 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010249 return;
10250
Eli Friedmandd053f62012-02-07 00:15:00 +000010251 // For C code, don't diagnose about capture if we're not actually in code
10252 // right now; it's impossible to write a non-constant expression outside of
10253 // function context, so we'll get other (more useful) diagnostics later.
10254 //
10255 // For C++, things get a bit more nasty... it would be nice to suppress this
10256 // diagnostic for certain cases like using a local variable in an array bound
10257 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010258 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010259 return;
10260
Eli Friedmandd053f62012-02-07 00:15:00 +000010261 if (isa<CXXMethodDecl>(VarDC) &&
10262 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10263 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10264 << var->getIdentifier();
10265 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10266 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10267 << var->getIdentifier() << fn->getDeclName();
10268 } else if (isa<BlockDecl>(VarDC)) {
10269 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10270 << var->getIdentifier();
10271 } else {
10272 // FIXME: Is there any other context where a local variable can be
10273 // declared?
10274 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10275 << var->getIdentifier();
10276 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010277
Eli Friedman9bb33f52012-02-03 02:04:35 +000010278 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10279 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010280
10281 // FIXME: Add additional diagnostic info about class etc. which prevents
10282 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010283}
10284
Douglas Gregor81495f32012-02-12 18:42:33 +000010285/// \brief Capture the given variable in the given lambda expression.
10286static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010287 VarDecl *Var, QualType FieldType,
10288 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010289 SourceLocation Loc,
10290 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010291 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010292
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010293 // Build the non-static data member.
10294 FieldDecl *Field
10295 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10296 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010297 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010298 Field->setImplicit(true);
10299 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010300 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010301
10302 // C++11 [expr.prim.lambda]p21:
10303 // When the lambda-expression is evaluated, the entities that
10304 // are captured by copy are used to direct-initialize each
10305 // corresponding non-static data member of the resulting closure
10306 // object. (For array members, the array elements are
10307 // direct-initialized in increasing subscript order.) These
10308 // initializations are performed in the (unspecified) order in
10309 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010310
Douglas Gregor89625492012-02-09 08:14:43 +000010311 // Introduce a new evaluation context for the initialization, so
10312 // that temporaries introduced as part of the capture are retained
10313 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010314 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10315
Douglas Gregorf02455e2012-02-10 09:26:04 +000010316 // C++ [expr.prim.labda]p12:
10317 // An entity captured by a lambda-expression is odr-used (3.2) in
10318 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010319 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10320 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010321 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010322 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010323
10324 // When the field has array type, create index variables for each
10325 // dimension of the array. We use these index variables to subscript
10326 // the source array, and other clients (e.g., CodeGen) will perform
10327 // the necessary iteration with these index variables.
10328 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010329 QualType BaseType = FieldType;
10330 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010331 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010332 while (const ConstantArrayType *Array
10333 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010334 // Create the iteration variable for this array index.
10335 IdentifierInfo *IterationVarName = 0;
10336 {
10337 SmallString<8> Str;
10338 llvm::raw_svector_ostream OS(Str);
10339 OS << "__i" << IndexVariables.size();
10340 IterationVarName = &S.Context.Idents.get(OS.str());
10341 }
10342 VarDecl *IterationVar
10343 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10344 IterationVarName, SizeType,
10345 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10346 SC_None, SC_None);
10347 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010348 LSI->ArrayIndexVars.push_back(IterationVar);
10349
Douglas Gregor199cec72012-02-09 02:45:47 +000010350 // Create a reference to the iteration variable.
10351 ExprResult IterationVarRef
10352 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10353 assert(!IterationVarRef.isInvalid() &&
10354 "Reference to invented variable cannot fail!");
10355 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10356 assert(!IterationVarRef.isInvalid() &&
10357 "Conversion of invented variable cannot fail!");
10358
10359 // Subscript the array with this iteration variable.
10360 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10361 Ref, Loc, IterationVarRef.take(), Loc);
10362 if (Subscript.isInvalid()) {
10363 S.CleanupVarDeclMarking();
10364 S.DiscardCleanupsInEvaluationContext();
10365 S.PopExpressionEvaluationContext();
10366 return ExprError();
10367 }
10368
10369 Ref = Subscript.take();
10370 BaseType = Array->getElementType();
10371 }
10372
10373 // Construct the entity that we will be initializing. For an array, this
10374 // will be first element in the array, which may require several levels
10375 // of array-subscript entities.
10376 SmallVector<InitializedEntity, 4> Entities;
10377 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010378 Entities.push_back(
10379 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010380 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10381 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10382 0,
10383 Entities.back()));
10384
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010385 InitializationKind InitKind
10386 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010387 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010388 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010389 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10390 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010391 MultiExprArg(S, &Ref, 1));
10392
10393 // If this initialization requires any cleanups (e.g., due to a
10394 // default argument to a copy constructor), note that for the
10395 // lambda.
10396 if (S.ExprNeedsCleanups)
10397 LSI->ExprNeedsCleanups = true;
10398
10399 // Exit the expression evaluation context used for the capture.
10400 S.CleanupVarDeclMarking();
10401 S.DiscardCleanupsInEvaluationContext();
10402 S.PopExpressionEvaluationContext();
10403 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010404}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010405
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010406bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10407 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10408 bool BuildAndDiagnose,
10409 QualType &CaptureType,
10410 QualType &DeclRefType) {
10411 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010412
Eli Friedman24af8502012-02-03 22:47:37 +000010413 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010414 if (Var->getDeclContext() == DC) return true;
10415 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010416
Douglas Gregor81495f32012-02-12 18:42:33 +000010417 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010418
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010419 // Walk up the stack to determine whether we can capture the variable,
10420 // performing the "simple" checks that don't depend on type. We stop when
10421 // we've either hit the declared scope of the variable or find an existing
10422 // capture of that variable.
10423 CaptureType = Var->getType();
10424 DeclRefType = CaptureType.getNonReferenceType();
10425 bool Explicit = (Kind != TryCapture_Implicit);
10426 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010427 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010428 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010429 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010430 DeclContext *ParentDC;
10431 if (isa<BlockDecl>(DC))
10432 ParentDC = DC->getParent();
10433 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010434 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010435 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10436 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010437 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010438 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010439 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010440 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010441 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010442
Eli Friedman24af8502012-02-03 22:47:37 +000010443 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010444 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010445
Eli Friedman24af8502012-02-03 22:47:37 +000010446 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010447 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010448 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010449 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010450
10451 // Retrieve the capture type for this variable.
10452 CaptureType = CSI->getCapture(Var).getCaptureType();
10453
10454 // Compute the type of an expression that refers to this variable.
10455 DeclRefType = CaptureType.getNonReferenceType();
10456
10457 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10458 if (Cap.isCopyCapture() &&
10459 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10460 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010461 break;
10462 }
10463
Douglas Gregor81495f32012-02-12 18:42:33 +000010464 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010465 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010466
10467 // Lambdas are not allowed to capture unnamed variables
10468 // (e.g. anonymous unions).
10469 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10470 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010471 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010472 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010473 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10474 Diag(Var->getLocation(), diag::note_declared_at);
10475 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010476 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010477 }
10478
10479 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010480 if (Var->getType()->isVariablyModifiedType()) {
10481 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010482 if (IsBlock)
10483 Diag(Loc, diag::err_ref_vm_type);
10484 else
10485 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10486 Diag(Var->getLocation(), diag::note_previous_decl)
10487 << Var->getDeclName();
10488 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010489 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010490 }
10491
Eli Friedman24af8502012-02-03 22:47:37 +000010492 // Lambdas are not allowed to capture __block variables; they don't
10493 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010494 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010495 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010496 Diag(Loc, diag::err_lambda_capture_block)
10497 << Var->getDeclName();
10498 Diag(Var->getLocation(), diag::note_previous_decl)
10499 << Var->getDeclName();
10500 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010501 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010502 }
10503
Douglas Gregor81495f32012-02-12 18:42:33 +000010504 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10505 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010506 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010507 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10508 Diag(Var->getLocation(), diag::note_previous_decl)
10509 << Var->getDeclName();
10510 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10511 diag::note_lambda_decl);
10512 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010513 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010514 }
10515
10516 FunctionScopesIndex--;
10517 DC = ParentDC;
10518 Explicit = false;
10519 } while (!Var->getDeclContext()->Equals(DC));
10520
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010521 // Walk back down the scope stack, computing the type of the capture at
10522 // each step, checking type-specific requirements, and adding captures if
10523 // requested.
10524 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10525 ++I) {
10526 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010527
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010528 // Compute the type of the capture and of a reference to the capture within
10529 // this scope.
10530 if (isa<BlockScopeInfo>(CSI)) {
10531 Expr *CopyExpr = 0;
10532 bool ByRef = false;
10533
10534 // Blocks are not allowed to capture arrays.
10535 if (CaptureType->isArrayType()) {
10536 if (BuildAndDiagnose) {
10537 Diag(Loc, diag::err_ref_array_type);
10538 Diag(Var->getLocation(), diag::note_previous_decl)
10539 << Var->getDeclName();
10540 }
10541 return true;
10542 }
10543
John McCall67cd5e02012-03-30 05:23:48 +000010544 // Forbid the block-capture of autoreleasing variables.
10545 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10546 if (BuildAndDiagnose) {
10547 Diag(Loc, diag::err_arc_autoreleasing_capture)
10548 << /*block*/ 0;
10549 Diag(Var->getLocation(), diag::note_previous_decl)
10550 << Var->getDeclName();
10551 }
10552 return true;
10553 }
10554
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010555 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10556 // Block capture by reference does not change the capture or
10557 // declaration reference types.
10558 ByRef = true;
10559 } else {
10560 // Block capture by copy introduces 'const'.
10561 CaptureType = CaptureType.getNonReferenceType().withConst();
10562 DeclRefType = CaptureType;
10563
David Blaikiebbafb8a2012-03-11 07:00:24 +000010564 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010565 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10566 // The capture logic needs the destructor, so make sure we mark it.
10567 // Usually this is unnecessary because most local variables have
10568 // their destructors marked at declaration time, but parameters are
10569 // an exception because it's technically only the call site that
10570 // actually requires the destructor.
10571 if (isa<ParmVarDecl>(Var))
10572 FinalizeVarWithDestructor(Var, Record);
10573
10574 // According to the blocks spec, the capture of a variable from
10575 // the stack requires a const copy constructor. This is not true
10576 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010577 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010578 DeclRefType.withConst(),
10579 VK_LValue, Loc);
10580 ExprResult Result
10581 = PerformCopyInitialization(
10582 InitializedEntity::InitializeBlock(Var->getLocation(),
10583 CaptureType, false),
10584 Loc, Owned(DeclRef));
10585
10586 // Build a full-expression copy expression if initialization
10587 // succeeded and used a non-trivial constructor. Recover from
10588 // errors by pretending that the copy isn't necessary.
10589 if (!Result.isInvalid() &&
10590 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10591 ->isTrivial()) {
10592 Result = MaybeCreateExprWithCleanups(Result);
10593 CopyExpr = Result.take();
10594 }
10595 }
10596 }
10597 }
10598
10599 // Actually capture the variable.
10600 if (BuildAndDiagnose)
10601 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10602 SourceLocation(), CaptureType, CopyExpr);
10603 Nested = true;
10604 continue;
10605 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010606
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010607 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10608
10609 // Determine whether we are capturing by reference or by value.
10610 bool ByRef = false;
10611 if (I == N - 1 && Kind != TryCapture_Implicit) {
10612 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010613 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010614 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010615 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010616
10617 // Compute the type of the field that will capture this variable.
10618 if (ByRef) {
10619 // C++11 [expr.prim.lambda]p15:
10620 // An entity is captured by reference if it is implicitly or
10621 // explicitly captured but not captured by copy. It is
10622 // unspecified whether additional unnamed non-static data
10623 // members are declared in the closure type for entities
10624 // captured by reference.
10625 //
10626 // FIXME: It is not clear whether we want to build an lvalue reference
10627 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10628 // to do the former, while EDG does the latter. Core issue 1249 will
10629 // clarify, but for now we follow GCC because it's a more permissive and
10630 // easily defensible position.
10631 CaptureType = Context.getLValueReferenceType(DeclRefType);
10632 } else {
10633 // C++11 [expr.prim.lambda]p14:
10634 // For each entity captured by copy, an unnamed non-static
10635 // data member is declared in the closure type. The
10636 // declaration order of these members is unspecified. The type
10637 // of such a data member is the type of the corresponding
10638 // captured entity if the entity is not a reference to an
10639 // object, or the referenced type otherwise. [Note: If the
10640 // captured entity is a reference to a function, the
10641 // corresponding data member is also a reference to a
10642 // function. - end note ]
10643 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10644 if (!RefType->getPointeeType()->isFunctionType())
10645 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010646 }
John McCall67cd5e02012-03-30 05:23:48 +000010647
10648 // Forbid the lambda copy-capture of autoreleasing variables.
10649 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10650 if (BuildAndDiagnose) {
10651 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10652 Diag(Var->getLocation(), diag::note_previous_decl)
10653 << Var->getDeclName();
10654 }
10655 return true;
10656 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010657 }
10658
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010659 // Capture this variable in the lambda.
10660 Expr *CopyExpr = 0;
10661 if (BuildAndDiagnose) {
10662 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010663 DeclRefType, Loc,
10664 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010665 if (!Result.isInvalid())
10666 CopyExpr = Result.take();
10667 }
10668
10669 // Compute the type of a reference to this captured variable.
10670 if (ByRef)
10671 DeclRefType = CaptureType.getNonReferenceType();
10672 else {
10673 // C++ [expr.prim.lambda]p5:
10674 // The closure type for a lambda-expression has a public inline
10675 // function call operator [...]. This function call operator is
10676 // declared const (9.3.1) if and only if the lambda-expression’s
10677 // parameter-declaration-clause is not followed by mutable.
10678 DeclRefType = CaptureType.getNonReferenceType();
10679 if (!LSI->Mutable && !CaptureType->isReferenceType())
10680 DeclRefType.addConst();
10681 }
10682
10683 // Add the capture.
10684 if (BuildAndDiagnose)
10685 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10686 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010687 Nested = true;
10688 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010689
10690 return false;
10691}
10692
10693bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10694 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10695 QualType CaptureType;
10696 QualType DeclRefType;
10697 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10698 /*BuildAndDiagnose=*/true, CaptureType,
10699 DeclRefType);
10700}
10701
10702QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10703 QualType CaptureType;
10704 QualType DeclRefType;
10705
10706 // Determine whether we can capture this variable.
10707 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10708 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10709 return QualType();
10710
10711 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010712}
10713
Eli Friedman3bda6b12012-02-02 23:15:15 +000010714static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10715 SourceLocation Loc) {
10716 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010717 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010718 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010719 Var->getLinkage() != ExternalLinkage &&
10720 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010721 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10722 if (old.isInvalid()) old = Loc;
10723 }
10724
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010725 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010726
Eli Friedman3bda6b12012-02-02 23:15:15 +000010727 Var->setUsed(true);
10728}
10729
10730void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10731 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10732 // an object that satisfies the requirements for appearing in a
10733 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10734 // is immediately applied." This function handles the lvalue-to-rvalue
10735 // conversion part.
10736 MaybeODRUseExprs.erase(E->IgnoreParens());
10737}
10738
Eli Friedmanc6237c62012-02-29 03:16:56 +000010739ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10740 if (!Res.isUsable())
10741 return Res;
10742
10743 // If a constant-expression is a reference to a variable where we delay
10744 // deciding whether it is an odr-use, just assume we will apply the
10745 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10746 // (a non-type template argument), we have special handling anyway.
10747 UpdateMarkingForLValueToRValue(Res.get());
10748 return Res;
10749}
10750
Eli Friedman3bda6b12012-02-02 23:15:15 +000010751void Sema::CleanupVarDeclMarking() {
10752 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10753 e = MaybeODRUseExprs.end();
10754 i != e; ++i) {
10755 VarDecl *Var;
10756 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010757 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010758 Var = cast<VarDecl>(DRE->getDecl());
10759 Loc = DRE->getLocation();
10760 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10761 Var = cast<VarDecl>(ME->getMemberDecl());
10762 Loc = ME->getMemberLoc();
10763 } else {
10764 llvm_unreachable("Unexpcted expression");
10765 }
10766
10767 MarkVarDeclODRUsed(*this, Var, Loc);
10768 }
10769
10770 MaybeODRUseExprs.clear();
10771}
10772
10773// Mark a VarDecl referenced, and perform the necessary handling to compute
10774// odr-uses.
10775static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10776 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010777 Var->setReferenced();
10778
Eli Friedman3bda6b12012-02-02 23:15:15 +000010779 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010780 return;
10781
10782 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010783 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010784 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10785 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010786 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10787 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010788 (!AlreadyInstantiated ||
10789 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010790 if (!AlreadyInstantiated) {
10791 // This is a modification of an existing AST node. Notify listeners.
10792 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10793 L->StaticDataMemberInstantiated(Var);
10794 MSInfo->setPointOfInstantiation(Loc);
10795 }
10796 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010797 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010798 // Do not defer instantiations of variables which could be used in a
10799 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010800 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010801 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010802 SemaRef.PendingInstantiations.push_back(
10803 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010804 }
10805 }
10806
Eli Friedman3bda6b12012-02-02 23:15:15 +000010807 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10808 // an object that satisfies the requirements for appearing in a
10809 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10810 // is immediately applied." We check the first part here, and
10811 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10812 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010813 // C++03 depends on whether we get the C++03 version correct. This does not
10814 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010815 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010816 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010817 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010818 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10819 SemaRef.MaybeODRUseExprs.insert(E);
10820 else
10821 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10822}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010823
Eli Friedman3bda6b12012-02-02 23:15:15 +000010824/// \brief Mark a variable referenced, and check whether it is odr-used
10825/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10826/// used directly for normal expressions referring to VarDecl.
10827void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10828 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010829}
10830
10831static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10832 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010833 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10834 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10835 return;
10836 }
10837
Eli Friedmanfa0df832012-02-02 03:46:19 +000010838 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010839}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010840
Eli Friedmanfa0df832012-02-02 03:46:19 +000010841/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10842void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10843 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10844}
10845
10846/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10847void Sema::MarkMemberReferenced(MemberExpr *E) {
10848 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10849}
10850
Douglas Gregorf02455e2012-02-10 09:26:04 +000010851/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010852/// marks the declaration referenced, and performs odr-use checking for functions
10853/// and variables. This method should not be used when building an normal
10854/// expression which refers to a variable.
10855void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10856 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10857 MarkVariableReferenced(Loc, VD);
10858 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10859 MarkFunctionReferenced(Loc, FD);
10860 else
10861 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010862}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010863
Douglas Gregor5597ab42010-05-07 23:12:07 +000010864namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010865 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010866 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010867 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010868 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10869 Sema &S;
10870 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010871
Douglas Gregor5597ab42010-05-07 23:12:07 +000010872 public:
10873 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010874
Douglas Gregor5597ab42010-05-07 23:12:07 +000010875 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010876
10877 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10878 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010879 };
10880}
10881
Chandler Carruthaf80f662010-06-09 08:17:30 +000010882bool MarkReferencedDecls::TraverseTemplateArgument(
10883 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010884 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010885 if (Decl *D = Arg.getAsDecl())
10886 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010887 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010888
10889 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010890}
10891
Chandler Carruthaf80f662010-06-09 08:17:30 +000010892bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010893 if (ClassTemplateSpecializationDecl *Spec
10894 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10895 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010896 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010897 }
10898
Chandler Carruthc65667c2010-06-10 10:31:57 +000010899 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010900}
10901
10902void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10903 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010904 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010905}
10906
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010907namespace {
10908 /// \brief Helper class that marks all of the declarations referenced by
10909 /// potentially-evaluated subexpressions as "referenced".
10910 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10911 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010912 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010913
10914 public:
10915 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10916
Douglas Gregor680e9e02012-02-21 19:11:17 +000010917 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10918 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010919
10920 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010921 // If we were asked not to visit local variables, don't.
10922 if (SkipLocalVariables) {
10923 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10924 if (VD->hasLocalStorage())
10925 return;
10926 }
10927
Eli Friedmanfa0df832012-02-02 03:46:19 +000010928 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010929 }
10930
10931 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010932 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010933 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010934 }
10935
John McCall28fc7092011-11-10 05:35:25 +000010936 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010937 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010938 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10939 Visit(E->getSubExpr());
10940 }
10941
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010942 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010943 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010944 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010945 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010946 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010947 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010948 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010949
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010950 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10951 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010952 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010953 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10954 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10955 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010956 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010957 S.LookupDestructor(Record));
10958 }
10959
Douglas Gregor32b3de52010-09-11 23:32:50 +000010960 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010961 }
10962
10963 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010964 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010965 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010966 }
10967
Douglas Gregorf0873f42010-10-19 17:17:35 +000010968 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10969 Visit(E->getExpr());
10970 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010971
10972 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10973 Inherited::VisitImplicitCastExpr(E);
10974
10975 if (E->getCastKind() == CK_LValueToRValue)
10976 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10977 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010978 };
10979}
10980
10981/// \brief Mark any declarations that appear within this expression or any
10982/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010983///
10984/// \param SkipLocalVariables If true, don't mark local variables as
10985/// 'referenced'.
10986void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10987 bool SkipLocalVariables) {
10988 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010989}
10990
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010991/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10992/// of the program being compiled.
10993///
10994/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010995/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010996/// possibility that the code will actually be executable. Code in sizeof()
10997/// expressions, code used only during overload resolution, etc., are not
10998/// potentially evaluated. This routine will suppress such diagnostics or,
10999/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011000/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011001/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011002///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011003/// This routine should be used for all diagnostics that describe the run-time
11004/// behavior of a program, such as passing a non-POD value through an ellipsis.
11005/// Failure to do so will likely result in spurious diagnostics or failures
11006/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011007bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011008 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011009 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011010 case Unevaluated:
11011 // The argument will never be evaluated, so don't complain.
11012 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011013
Richard Smith764d2fe2011-12-20 02:08:33 +000011014 case ConstantEvaluated:
11015 // Relevant diagnostics should be produced by constant evaluation.
11016 break;
11017
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011018 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011019 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011020 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011021 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011022 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011023 }
11024 else
11025 Diag(Loc, PD);
11026
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011027 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011028 }
11029
11030 return false;
11031}
11032
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011033bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11034 CallExpr *CE, FunctionDecl *FD) {
11035 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11036 return false;
11037
Richard Smithfd555f62012-02-22 02:04:18 +000011038 // If we're inside a decltype's expression, don't check for a valid return
11039 // type or construct temporaries until we know whether this is the last call.
11040 if (ExprEvalContexts.back().IsDecltype) {
11041 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11042 return false;
11043 }
11044
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011045 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011046 FunctionDecl *FD;
11047 CallExpr *CE;
11048
11049 public:
11050 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11051 : FD(FD), CE(CE) { }
11052
11053 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11054 if (!FD) {
11055 S.Diag(Loc, diag::err_call_incomplete_return)
11056 << T << CE->getSourceRange();
11057 return;
11058 }
11059
11060 S.Diag(Loc, diag::err_call_function_incomplete_return)
11061 << CE->getSourceRange() << FD->getDeclName() << T;
11062 S.Diag(FD->getLocation(),
11063 diag::note_function_with_incomplete_return_type_declared_here)
11064 << FD->getDeclName();
11065 }
11066 } Diagnoser(FD, CE);
11067
11068 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011069 return true;
11070
11071 return false;
11072}
11073
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011074// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011075// will prevent this condition from triggering, which is what we want.
11076void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11077 SourceLocation Loc;
11078
John McCall0506e4a2009-11-11 02:41:58 +000011079 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011080 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011081
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011082 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011083 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011084 return;
11085
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011086 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11087
John McCallb0e419e2009-11-12 00:06:05 +000011088 // Greylist some idioms by putting them into a warning subcategory.
11089 if (ObjCMessageExpr *ME
11090 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11091 Selector Sel = ME->getSelector();
11092
John McCallb0e419e2009-11-12 00:06:05 +000011093 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011094 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011095 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11096
11097 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011098 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011099 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11100 }
John McCall0506e4a2009-11-11 02:41:58 +000011101
John McCalld5707ab2009-10-12 21:59:07 +000011102 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011103 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011104 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011105 return;
11106
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011107 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011108 Loc = Op->getOperatorLoc();
11109 } else {
11110 // Not an assignment.
11111 return;
11112 }
11113
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011114 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011115
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011116 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011117 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11118 Diag(Loc, diag::note_condition_assign_silence)
11119 << FixItHint::CreateInsertion(Open, "(")
11120 << FixItHint::CreateInsertion(Close, ")");
11121
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011122 if (IsOrAssign)
11123 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11124 << FixItHint::CreateReplacement(Loc, "!=");
11125 else
11126 Diag(Loc, diag::note_condition_assign_to_comparison)
11127 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011128}
11129
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011130/// \brief Redundant parentheses over an equality comparison can indicate
11131/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011132void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011133 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011134 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011135 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11136 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011137 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011138 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011139 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011140
Richard Trieuba63ce62011-09-09 01:45:06 +000011141 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011142
11143 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011144 if (opE->getOpcode() == BO_EQ &&
11145 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11146 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011147 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011148
Ted Kremenekae022092011-02-02 02:20:30 +000011149 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011150 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011151 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011152 << FixItHint::CreateRemoval(ParenERange.getBegin())
11153 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011154 Diag(Loc, diag::note_equality_comparison_to_assign)
11155 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011156 }
11157}
11158
John Wiegley01296292011-04-08 18:41:53 +000011159ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011160 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011161 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11162 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011163
John McCall0009fcc2011-04-26 20:42:42 +000011164 ExprResult result = CheckPlaceholderExpr(E);
11165 if (result.isInvalid()) return ExprError();
11166 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011167
John McCall0009fcc2011-04-26 20:42:42 +000011168 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011169 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011170 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11171
John Wiegley01296292011-04-08 18:41:53 +000011172 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11173 if (ERes.isInvalid())
11174 return ExprError();
11175 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011176
11177 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011178 if (!T->isScalarType()) { // C99 6.8.4.1p1
11179 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11180 << T << E->getSourceRange();
11181 return ExprError();
11182 }
John McCalld5707ab2009-10-12 21:59:07 +000011183 }
11184
John Wiegley01296292011-04-08 18:41:53 +000011185 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011186}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011187
John McCalldadc5752010-08-24 06:29:42 +000011188ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011189 Expr *SubExpr) {
11190 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011191 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011192
Richard Trieuba63ce62011-09-09 01:45:06 +000011193 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011194}
John McCall36e7fe32010-10-12 00:20:44 +000011195
John McCall31996342011-04-07 08:22:57 +000011196namespace {
John McCall2979fe02011-04-12 00:42:48 +000011197 /// A visitor for rebuilding a call to an __unknown_any expression
11198 /// to have an appropriate type.
11199 struct RebuildUnknownAnyFunction
11200 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11201
11202 Sema &S;
11203
11204 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11205
11206 ExprResult VisitStmt(Stmt *S) {
11207 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011208 }
11209
Richard Trieu10162ab2011-09-09 03:59:41 +000011210 ExprResult VisitExpr(Expr *E) {
11211 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11212 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011213 return ExprError();
11214 }
11215
11216 /// Rebuild an expression which simply semantically wraps another
11217 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011218 template <class T> ExprResult rebuildSugarExpr(T *E) {
11219 ExprResult SubResult = Visit(E->getSubExpr());
11220 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011221
Richard Trieu10162ab2011-09-09 03:59:41 +000011222 Expr *SubExpr = SubResult.take();
11223 E->setSubExpr(SubExpr);
11224 E->setType(SubExpr->getType());
11225 E->setValueKind(SubExpr->getValueKind());
11226 assert(E->getObjectKind() == OK_Ordinary);
11227 return E;
John McCall2979fe02011-04-12 00:42:48 +000011228 }
11229
Richard Trieu10162ab2011-09-09 03:59:41 +000011230 ExprResult VisitParenExpr(ParenExpr *E) {
11231 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011232 }
11233
Richard Trieu10162ab2011-09-09 03:59:41 +000011234 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11235 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011236 }
11237
Richard Trieu10162ab2011-09-09 03:59:41 +000011238 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11239 ExprResult SubResult = Visit(E->getSubExpr());
11240 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011241
Richard Trieu10162ab2011-09-09 03:59:41 +000011242 Expr *SubExpr = SubResult.take();
11243 E->setSubExpr(SubExpr);
11244 E->setType(S.Context.getPointerType(SubExpr->getType()));
11245 assert(E->getValueKind() == VK_RValue);
11246 assert(E->getObjectKind() == OK_Ordinary);
11247 return E;
John McCall2979fe02011-04-12 00:42:48 +000011248 }
11249
Richard Trieu10162ab2011-09-09 03:59:41 +000011250 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11251 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011252
Richard Trieu10162ab2011-09-09 03:59:41 +000011253 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011254
Richard Trieu10162ab2011-09-09 03:59:41 +000011255 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011256 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011257 !(isa<CXXMethodDecl>(VD) &&
11258 cast<CXXMethodDecl>(VD)->isInstance()))
11259 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011260
Richard Trieu10162ab2011-09-09 03:59:41 +000011261 return E;
John McCall2979fe02011-04-12 00:42:48 +000011262 }
11263
Richard Trieu10162ab2011-09-09 03:59:41 +000011264 ExprResult VisitMemberExpr(MemberExpr *E) {
11265 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011266 }
11267
Richard Trieu10162ab2011-09-09 03:59:41 +000011268 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11269 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011270 }
11271 };
11272}
11273
11274/// Given a function expression of unknown-any type, try to rebuild it
11275/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011276static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11277 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11278 if (Result.isInvalid()) return ExprError();
11279 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011280}
11281
11282namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011283 /// A visitor for rebuilding an expression of type __unknown_anytype
11284 /// into one which resolves the type directly on the referring
11285 /// expression. Strict preservation of the original source
11286 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011287 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011288 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011289
11290 Sema &S;
11291
11292 /// The current destination type.
11293 QualType DestType;
11294
Richard Trieu10162ab2011-09-09 03:59:41 +000011295 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11296 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011297
John McCall39439732011-04-09 22:50:59 +000011298 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011299 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011300 }
11301
Richard Trieu10162ab2011-09-09 03:59:41 +000011302 ExprResult VisitExpr(Expr *E) {
11303 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11304 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011305 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011306 }
11307
Richard Trieu10162ab2011-09-09 03:59:41 +000011308 ExprResult VisitCallExpr(CallExpr *E);
11309 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011310
John McCall39439732011-04-09 22:50:59 +000011311 /// Rebuild an expression which simply semantically wraps another
11312 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011313 template <class T> ExprResult rebuildSugarExpr(T *E) {
11314 ExprResult SubResult = Visit(E->getSubExpr());
11315 if (SubResult.isInvalid()) return ExprError();
11316 Expr *SubExpr = SubResult.take();
11317 E->setSubExpr(SubExpr);
11318 E->setType(SubExpr->getType());
11319 E->setValueKind(SubExpr->getValueKind());
11320 assert(E->getObjectKind() == OK_Ordinary);
11321 return E;
John McCall39439732011-04-09 22:50:59 +000011322 }
John McCall31996342011-04-07 08:22:57 +000011323
Richard Trieu10162ab2011-09-09 03:59:41 +000011324 ExprResult VisitParenExpr(ParenExpr *E) {
11325 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011326 }
11327
Richard Trieu10162ab2011-09-09 03:59:41 +000011328 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11329 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011330 }
11331
Richard Trieu10162ab2011-09-09 03:59:41 +000011332 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11333 const PointerType *Ptr = DestType->getAs<PointerType>();
11334 if (!Ptr) {
11335 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11336 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011337 return ExprError();
11338 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011339 assert(E->getValueKind() == VK_RValue);
11340 assert(E->getObjectKind() == OK_Ordinary);
11341 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011342
11343 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011344 DestType = Ptr->getPointeeType();
11345 ExprResult SubResult = Visit(E->getSubExpr());
11346 if (SubResult.isInvalid()) return ExprError();
11347 E->setSubExpr(SubResult.take());
11348 return E;
John McCall2979fe02011-04-12 00:42:48 +000011349 }
11350
Richard Trieu10162ab2011-09-09 03:59:41 +000011351 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011352
Richard Trieu10162ab2011-09-09 03:59:41 +000011353 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011354
Richard Trieu10162ab2011-09-09 03:59:41 +000011355 ExprResult VisitMemberExpr(MemberExpr *E) {
11356 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011357 }
John McCall39439732011-04-09 22:50:59 +000011358
Richard Trieu10162ab2011-09-09 03:59:41 +000011359 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11360 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011361 }
11362 };
11363}
11364
John McCall2d2e8702011-04-11 07:02:50 +000011365/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011366ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11367 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011368
11369 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011370 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011371 FK_FunctionPointer,
11372 FK_BlockPointer
11373 };
11374
Richard Trieu10162ab2011-09-09 03:59:41 +000011375 FnKind Kind;
11376 QualType CalleeType = CalleeExpr->getType();
11377 if (CalleeType == S.Context.BoundMemberTy) {
11378 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11379 Kind = FK_MemberFunction;
11380 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11381 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11382 CalleeType = Ptr->getPointeeType();
11383 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011384 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011385 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11386 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011387 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011388 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011389
11390 // Verify that this is a legal result type of a function.
11391 if (DestType->isArrayType() || DestType->isFunctionType()) {
11392 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011393 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011394 diagID = diag::err_block_returning_array_function;
11395
Richard Trieu10162ab2011-09-09 03:59:41 +000011396 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011397 << DestType->isFunctionType() << DestType;
11398 return ExprError();
11399 }
11400
11401 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011402 E->setType(DestType.getNonLValueExprType(S.Context));
11403 E->setValueKind(Expr::getValueKindForType(DestType));
11404 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011405
11406 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011407 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011408 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011409 Proto->arg_type_begin(),
11410 Proto->getNumArgs(),
11411 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011412 else
11413 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011414 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011415
11416 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011417 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011418 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011419 // Nothing to do.
11420 break;
11421
11422 case FK_FunctionPointer:
11423 DestType = S.Context.getPointerType(DestType);
11424 break;
11425
11426 case FK_BlockPointer:
11427 DestType = S.Context.getBlockPointerType(DestType);
11428 break;
11429 }
11430
11431 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011432 ExprResult CalleeResult = Visit(CalleeExpr);
11433 if (!CalleeResult.isUsable()) return ExprError();
11434 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011435
11436 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011437 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011438}
11439
Richard Trieu10162ab2011-09-09 03:59:41 +000011440ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011441 // Verify that this is a legal result type of a call.
11442 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011443 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011444 << DestType->isFunctionType() << DestType;
11445 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011446 }
11447
John McCall3f4138c2011-07-13 17:56:40 +000011448 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011449 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11450 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11451 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011452 }
John McCall2979fe02011-04-12 00:42:48 +000011453
John McCall2d2e8702011-04-11 07:02:50 +000011454 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011455 E->setType(DestType.getNonReferenceType());
11456 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011457
Richard Trieu10162ab2011-09-09 03:59:41 +000011458 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011459}
11460
Richard Trieu10162ab2011-09-09 03:59:41 +000011461ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011462 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011463 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011464 assert(E->getValueKind() == VK_RValue);
11465 assert(E->getObjectKind() == OK_Ordinary);
11466
11467 E->setType(DestType);
11468
11469 // Rebuild the sub-expression as the pointee (function) type.
11470 DestType = DestType->castAs<PointerType>()->getPointeeType();
11471
11472 ExprResult Result = Visit(E->getSubExpr());
11473 if (!Result.isUsable()) return ExprError();
11474
11475 E->setSubExpr(Result.take());
11476 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011477 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011478 assert(E->getValueKind() == VK_RValue);
11479 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011480
Sean Callanan12495112012-03-06 21:34:12 +000011481 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011482
Sean Callanan12495112012-03-06 21:34:12 +000011483 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011484
Sean Callanan12495112012-03-06 21:34:12 +000011485 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11486 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011487
Sean Callanan12495112012-03-06 21:34:12 +000011488 ExprResult Result = Visit(E->getSubExpr());
11489 if (!Result.isUsable()) return ExprError();
11490
11491 E->setSubExpr(Result.take());
11492 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011493 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011494 llvm_unreachable("Unhandled cast type!");
11495 }
John McCall2d2e8702011-04-11 07:02:50 +000011496}
11497
Richard Trieu10162ab2011-09-09 03:59:41 +000011498ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11499 ExprValueKind ValueKind = VK_LValue;
11500 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011501
11502 // We know how to make this work for certain kinds of decls:
11503
11504 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11506 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11507 DestType = Ptr->getPointeeType();
11508 ExprResult Result = resolveDecl(E, VD);
11509 if (Result.isInvalid()) return ExprError();
11510 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011511 CK_FunctionToPointerDecay, VK_RValue);
11512 }
11513
Richard Trieu10162ab2011-09-09 03:59:41 +000011514 if (!Type->isFunctionType()) {
11515 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11516 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011517 return ExprError();
11518 }
John McCall2d2e8702011-04-11 07:02:50 +000011519
Richard Trieu10162ab2011-09-09 03:59:41 +000011520 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11521 if (MD->isInstance()) {
11522 ValueKind = VK_RValue;
11523 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011524 }
11525
John McCall2d2e8702011-04-11 07:02:50 +000011526 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011527 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011528 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011529
11530 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011531 } else if (isa<VarDecl>(VD)) {
11532 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11533 Type = RefTy->getPointeeType();
11534 } else if (Type->isFunctionType()) {
11535 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11536 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011537 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011538 }
11539
11540 // - nothing else
11541 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011542 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11543 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011544 return ExprError();
11545 }
11546
Richard Trieu10162ab2011-09-09 03:59:41 +000011547 VD->setType(DestType);
11548 E->setType(Type);
11549 E->setValueKind(ValueKind);
11550 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011551}
11552
John McCall31996342011-04-07 08:22:57 +000011553/// Check a cast of an unknown-any type. We intentionally only
11554/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011555ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11556 Expr *CastExpr, CastKind &CastKind,
11557 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011558 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011559 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011560 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011561
Richard Trieuba63ce62011-09-09 01:45:06 +000011562 CastExpr = result.take();
11563 VK = CastExpr->getValueKind();
11564 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011565
Richard Trieuba63ce62011-09-09 01:45:06 +000011566 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011567}
11568
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011569ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11570 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11571}
11572
Richard Trieuba63ce62011-09-09 01:45:06 +000011573static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11574 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011575 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011576 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011577 E = E->IgnoreParenImpCasts();
11578 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11579 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011580 diagID = diag::err_uncasted_call_of_unknown_any;
11581 } else {
John McCall31996342011-04-07 08:22:57 +000011582 break;
John McCall2d2e8702011-04-11 07:02:50 +000011583 }
John McCall31996342011-04-07 08:22:57 +000011584 }
11585
John McCall2d2e8702011-04-11 07:02:50 +000011586 SourceLocation loc;
11587 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011588 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011589 loc = ref->getLocation();
11590 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011591 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011592 loc = mem->getMemberLoc();
11593 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011594 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011595 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011596 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011597 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011598 if (!d) {
11599 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11600 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11601 << orig->getSourceRange();
11602 return ExprError();
11603 }
John McCall2d2e8702011-04-11 07:02:50 +000011604 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011605 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11606 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011607 return ExprError();
11608 }
11609
11610 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011611
11612 // Never recoverable.
11613 return ExprError();
11614}
11615
John McCall36e7fe32010-10-12 00:20:44 +000011616/// Check for operands with placeholder types and complain if found.
11617/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011618ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011619 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11620 if (!placeholderType) return Owned(E);
11621
11622 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011623
John McCall31996342011-04-07 08:22:57 +000011624 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011625 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011626 // Try to resolve a single function template specialization.
11627 // This is obligatory.
11628 ExprResult result = Owned(E);
11629 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11630 return result;
11631
11632 // If that failed, try to recover with a call.
11633 } else {
11634 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11635 /*complain*/ true);
11636 return result;
11637 }
11638 }
John McCall31996342011-04-07 08:22:57 +000011639
John McCall0009fcc2011-04-26 20:42:42 +000011640 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011641 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011642 ExprResult result = Owned(E);
11643 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11644 /*complain*/ true);
11645 return result;
John McCall4124c492011-10-17 18:40:02 +000011646 }
11647
11648 // ARC unbridged casts.
11649 case BuiltinType::ARCUnbridgedCast: {
11650 Expr *realCast = stripARCUnbridgedCast(E);
11651 diagnoseARCUnbridgedCast(realCast);
11652 return Owned(realCast);
11653 }
John McCall0009fcc2011-04-26 20:42:42 +000011654
John McCall31996342011-04-07 08:22:57 +000011655 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011656 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011657 return diagnoseUnknownAnyExpr(*this, E);
11658
John McCall526ab472011-10-25 17:37:35 +000011659 // Pseudo-objects.
11660 case BuiltinType::PseudoObject:
11661 return checkPseudoObjectRValue(E);
11662
John McCalle314e272011-10-18 21:02:43 +000011663 // Everything else should be impossible.
11664#define BUILTIN_TYPE(Id, SingletonId) \
11665 case BuiltinType::Id:
11666#define PLACEHOLDER_TYPE(Id, SingletonId)
11667#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011668 break;
11669 }
11670
11671 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011672}
Richard Trieu2c850c02011-04-21 21:44:26 +000011673
Richard Trieuba63ce62011-09-09 01:45:06 +000011674bool Sema::CheckCaseExpression(Expr *E) {
11675 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011676 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011677 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11678 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011679 return false;
11680}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011681
11682/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11683ExprResult
11684Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11685 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11686 "Unknown Objective-C Boolean value!");
11687 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian29898f42012-04-16 21:03:30 +000011688 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011689}