blob: 5b4fb297419e33bff6cd9fdd4310befcdb862d22 [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
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000069static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70 // Warn if this is used but marked unused.
71 if (D->hasAttr<UnusedAttr>()) {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000072 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
Fariborz Jahanian66c93f42012-09-06 16:43:18 +000073 if (!DC->hasAttr<UnusedAttr>())
74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75 }
76}
77
Ted Kremenek6eb25622012-02-10 02:45:47 +000078static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000079 NamedDecl *D, SourceLocation Loc,
80 const ObjCInterfaceDecl *UnknownObjCClass) {
81 // See if this declaration is unavailable or deprecated.
82 std::string Message;
83 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000084 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85 if (Result == AR_Available) {
86 const DeclContext *DC = ECD->getDeclContext();
87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88 Result = TheEnumDecl->getAvailability(&Message);
89 }
Jordan Rose2bd991a2012-10-10 16:42:54 +000090
Fariborz Jahanian974c9482012-09-21 20:46:37 +000091 const ObjCPropertyDecl *ObjCPDecl = 0;
Jordan Rose2bd991a2012-10-10 16:42:54 +000092 if (Result == AR_Deprecated || Result == AR_Unavailable) {
93 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
94 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
95 AvailabilityResult PDeclResult = PD->getAvailability(0);
96 if (PDeclResult == Result)
97 ObjCPDecl = PD;
98 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +000099 }
Jordan Rose2bd991a2012-10-10 16:42:54 +0000100 }
Fariborz Jahanian25d09c22011-11-28 19:45:58 +0000101
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000102 switch (Result) {
103 case AR_Available:
104 case AR_NotYetIntroduced:
105 break;
106
107 case AR_Deprecated:
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000108 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000109 break;
110
111 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +0000112 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000113 if (Message.empty()) {
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000114 if (!UnknownObjCClass) {
Ted Kremenek6eb25622012-02-10 02:45:47 +0000115 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000116 if (ObjCPDecl)
117 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
118 << ObjCPDecl->getDeclName() << 1;
119 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000120 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000121 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000122 << D->getDeclName();
123 }
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000124 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000125 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000126 << D->getDeclName() << Message;
Fariborz Jahanian974c9482012-09-21 20:46:37 +0000127 S.Diag(D->getLocation(), diag::note_unavailable_here)
128 << isa<FunctionDecl>(D) << false;
129 if (ObjCPDecl)
130 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
131 << ObjCPDecl->getDeclName() << 1;
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000132 }
133 break;
134 }
135 return Result;
136}
137
Richard Smith852265f2012-03-30 20:53:28 +0000138/// \brief Emit a note explaining that this function is deleted or unavailable.
139void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
141
Richard Smith6f1e2c62012-04-02 20:59:25 +0000142 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
143 // If the method was explicitly defaulted, point at that declaration.
144 if (!Method->isImplicit())
145 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
146
147 // Try to diagnose why this special member function was implicitly
148 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000149 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000150 if (CSM != CXXInvalid)
151 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
152
153 return;
Richard Smith852265f2012-03-30 20:53:28 +0000154 }
155
156 Diag(Decl->getLocation(), diag::note_unavailable_here)
157 << 1 << Decl->isDeleted();
158}
159
Jordan Rose28cd12f2012-06-18 22:09:19 +0000160/// \brief Determine whether a FunctionDecl was ever declared with an
161/// explicit storage class.
162static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
163 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
164 E = D->redecls_end();
165 I != E; ++I) {
166 if (I->getStorageClassAsWritten() != SC_None)
167 return true;
168 }
169 return false;
170}
171
172/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rosede9e9762012-06-20 18:50:06 +0000173/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose28cd12f2012-06-18 22:09:19 +0000174///
Jordan Rose28cd12f2012-06-18 22:09:19 +0000175/// This is only a warning because we used to silently accept this code, but
Jordan Rosede9e9762012-06-20 18:50:06 +0000176/// in many cases it will not behave correctly. This is not enabled in C++ mode
177/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
178/// and so while there may still be user mistakes, most of the time we can't
179/// prove that there are errors.
Jordan Rose28cd12f2012-06-18 22:09:19 +0000180static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
181 const NamedDecl *D,
182 SourceLocation Loc) {
Jordan Rosede9e9762012-06-20 18:50:06 +0000183 // This is disabled under C++; there are too many ways for this to fire in
184 // contexts where the warning is a false positive, or where it is technically
185 // correct but benign.
186 if (S.getLangOpts().CPlusPlus)
187 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000188
189 // Check if this is an inlined function or method.
190 FunctionDecl *Current = S.getCurFunctionDecl();
191 if (!Current)
192 return;
193 if (!Current->isInlined())
194 return;
195 if (Current->getLinkage() != ExternalLinkage)
196 return;
197
198 // Check if the decl has internal linkage.
Jordan Rosede9e9762012-06-20 18:50:06 +0000199 if (D->getLinkage() != InternalLinkage)
Jordan Rose28cd12f2012-06-18 22:09:19 +0000200 return;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000201
Jordan Rose815fe262012-06-21 05:54:50 +0000202 // Downgrade from ExtWarn to Extension if
203 // (1) the supposedly external inline function is in the main file,
204 // and probably won't be included anywhere else.
205 // (2) the thing we're referencing is a pure function.
206 // (3) the thing we're referencing is another inline function.
207 // This last can give us false negatives, but it's better than warning on
208 // wrappers for simple C library functions.
209 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
210 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
211 if (!DowngradeWarning && UsedFn)
212 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
213
214 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
215 : diag::warn_internal_in_extern_inline)
216 << /*IsVar=*/!UsedFn << D;
Jordan Rose28cd12f2012-06-18 22:09:19 +0000217
218 // Suggest "static" on the inline function, if possible.
Jordan Rosede9e9762012-06-20 18:50:06 +0000219 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose28cd12f2012-06-18 22:09:19 +0000220 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
221 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
222 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
223 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
224 }
225
226 S.Diag(D->getCanonicalDecl()->getLocation(),
227 diag::note_internal_decl_declared_here)
228 << D;
229}
230
Douglas Gregor171c45a2009-02-18 21:56:37 +0000231/// \brief Determine whether the use of this declaration is valid, and
232/// emit any corresponding diagnostics.
233///
234/// This routine diagnoses various problems with referencing
235/// declarations that can occur when using a declaration. For example,
236/// it might warn if a deprecated or unavailable declaration is being
237/// used, or produce an error (and return true) if a C++0x deleted
238/// function is being used.
239///
240/// \returns true if there was an error (this declaration cannot be
241/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000242///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000243bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000244 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000245 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000246 // If there were any diagnostics suppressed by template argument deduction,
247 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000248 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000249 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
250 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000251 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000252 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
253 Diag(Suppressed[I].first, Suppressed[I].second);
254
255 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000256 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000257 // entry from the table, because we want to avoid ever emitting these
258 // diagnostics again.
259 Suppressed.clear();
260 }
261 }
262
Richard Smith30482bc2011-02-20 03:19:35 +0000263 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000264 if (ParsingInitForAutoVars.count(D)) {
265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << D->getDeclName();
267 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000268 }
269
Douglas Gregor171c45a2009-02-18 21:56:37 +0000270 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000272 if (FD->isDeleted()) {
273 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000274 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000275 return true;
276 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000277 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000278 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000279
Fariborz Jahanian66c93f42012-09-06 16:43:18 +0000280 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000281
Jordan Rose28cd12f2012-06-18 22:09:19 +0000282 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose2684c682012-06-15 18:19:48 +0000283
Douglas Gregor171c45a2009-02-18 21:56:37 +0000284 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000285}
286
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000287/// \brief Retrieve the message suffix that should be added to a
288/// diagnostic complaining about the given function being deleted or
289/// unavailable.
290std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
291 // FIXME: C++0x implicitly-deleted special member functions could be
292 // detected here so that we could improve diagnostics to say, e.g.,
293 // "base class 'A' had a deleted copy constructor".
294 if (FD->isDeleted())
295 return std::string();
296
297 std::string Message;
298 if (FD->getAvailability(&Message))
299 return ": " + Message;
300
301 return std::string();
302}
303
John McCallb46f2872011-09-09 07:56:05 +0000304/// DiagnoseSentinelCalls - This routine checks whether a call or
305/// message-send is to a declaration with the sentinel attribute, and
306/// if so, it checks that the requirements of the sentinel are
307/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000308void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000309 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000310 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000311 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000312 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000313
John McCallb46f2872011-09-09 07:56:05 +0000314 // The number of formal parameters of the declaration.
315 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000316
John McCallb46f2872011-09-09 07:56:05 +0000317 // The kind of declaration. This is also an index into a %select in
318 // the diagnostic.
319 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
320
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000322 numFormalParams = MD->param_size();
323 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000324 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000325 numFormalParams = FD->param_size();
326 calleeType = CT_Function;
327 } else if (isa<VarDecl>(D)) {
328 QualType type = cast<ValueDecl>(D)->getType();
329 const FunctionType *fn = 0;
330 if (const PointerType *ptr = type->getAs<PointerType>()) {
331 fn = ptr->getPointeeType()->getAs<FunctionType>();
332 if (!fn) return;
333 calleeType = CT_Function;
334 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
335 fn = ptr->getPointeeType()->castAs<FunctionType>();
336 calleeType = CT_Block;
337 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000338 return;
John McCallb46f2872011-09-09 07:56:05 +0000339 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000340
John McCallb46f2872011-09-09 07:56:05 +0000341 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
342 numFormalParams = proto->getNumArgs();
343 } else {
344 numFormalParams = 0;
345 }
346 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000347 return;
348 }
John McCallb46f2872011-09-09 07:56:05 +0000349
350 // "nullPos" is the number of formal parameters at the end which
351 // effectively count as part of the variadic arguments. This is
352 // useful if you would prefer to not have *any* formal parameters,
353 // but the language forces you to have at least one.
354 unsigned nullPos = attr->getNullPos();
355 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
356 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
357
358 // The number of arguments which should follow the sentinel.
359 unsigned numArgsAfterSentinel = attr->getSentinel();
360
361 // If there aren't enough arguments for all the formal parameters,
362 // the sentinel, and the args after the sentinel, complain.
363 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000364 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000365 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000366 return;
367 }
John McCallb46f2872011-09-09 07:56:05 +0000368
369 // Otherwise, find the sentinel expression.
370 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000371 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000372 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000373 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000374
John McCallb46f2872011-09-09 07:56:05 +0000375 // Pick a reasonable string to insert. Optimistically use 'nil' or
376 // 'NULL' if those are actually defined in the context. Only use
377 // 'nil' for ObjC methods, where it's much more likely that the
378 // variadic arguments form a list of object pointers.
379 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000380 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
381 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000382 if (calleeType == CT_Method &&
383 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000384 NullValue = "nil";
385 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
386 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000387 else
John McCallb46f2872011-09-09 07:56:05 +0000388 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000389
390 if (MissingNilLoc.isInvalid())
391 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
392 else
393 Diag(MissingNilLoc, diag::warn_missing_sentinel)
394 << calleeType
395 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000396 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000397}
398
Richard Trieuba63ce62011-09-09 01:45:06 +0000399SourceRange Sema::getExprRange(Expr *E) const {
400 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000401}
402
Chris Lattner513165e2008-07-25 21:10:04 +0000403//===----------------------------------------------------------------------===//
404// Standard Promotions and Conversions
405//===----------------------------------------------------------------------===//
406
Chris Lattner513165e2008-07-25 21:10:04 +0000407/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000408ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000409 // Handle any placeholder expressions which made it here.
410 if (E->getType()->isPlaceholderType()) {
411 ExprResult result = CheckPlaceholderExpr(E);
412 if (result.isInvalid()) return ExprError();
413 E = result.take();
414 }
415
Chris Lattner513165e2008-07-25 21:10:04 +0000416 QualType Ty = E->getType();
417 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
418
Chris Lattner513165e2008-07-25 21:10:04 +0000419 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000420 E = ImpCastExprToType(E, Context.getPointerType(Ty),
421 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000422 else if (Ty->isArrayType()) {
423 // In C90 mode, arrays only promote to pointers if the array expression is
424 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
425 // type 'array of type' is converted to an expression that has type 'pointer
426 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
427 // that has type 'array of type' ...". The relevant change is "an lvalue"
428 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000429 //
430 // C++ 4.2p1:
431 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
432 // T" can be converted to an rvalue of type "pointer to T".
433 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000434 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000435 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
436 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000437 }
John Wiegley01296292011-04-08 18:41:53 +0000438 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000439}
440
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000441static void CheckForNullPointerDereference(Sema &S, Expr *E) {
442 // Check to see if we are dereferencing a null pointer. If so,
443 // and if not volatile-qualified, this is undefined behavior that the
444 // optimizer will delete, so warn about it. People sometimes try to use this
445 // to get a deterministic trap and are surprised by clang's behavior. This
446 // only handles the pattern "*null", which is a very syntactic check.
447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
448 if (UO->getOpcode() == UO_Deref &&
449 UO->getSubExpr()->IgnoreParenCasts()->
450 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
451 !UO->getType().isVolatileQualified()) {
452 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
453 S.PDiag(diag::warn_indirection_through_null)
454 << UO->getSubExpr()->getSourceRange());
455 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
456 S.PDiag(diag::note_indirection_through_null));
457 }
458}
459
John Wiegley01296292011-04-08 18:41:53 +0000460ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000461 // Handle any placeholder expressions which made it here.
462 if (E->getType()->isPlaceholderType()) {
463 ExprResult result = CheckPlaceholderExpr(E);
464 if (result.isInvalid()) return ExprError();
465 E = result.take();
466 }
467
John McCallf3735e02010-12-01 04:43:34 +0000468 // C++ [conv.lval]p1:
469 // A glvalue of a non-function, non-array type T can be
470 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000471 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000472
John McCall27584242010-12-06 20:48:59 +0000473 QualType T = E->getType();
474 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000475
John McCall27584242010-12-06 20:48:59 +0000476 // We don't want to throw lvalue-to-rvalue casts on top of
477 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000478 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000479 (E->getType() == Context.OverloadTy ||
480 T->isDependentType() ||
481 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000482 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000483
484 // The C standard is actually really unclear on this point, and
485 // DR106 tells us what the result should be but not why. It's
486 // generally best to say that void types just doesn't undergo
487 // lvalue-to-rvalue at all. Note that expressions of unqualified
488 // 'void' type are never l-values, but qualified void can be.
489 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000490 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000491
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000492 CheckForNullPointerDereference(*this, E);
493
John McCall27584242010-12-06 20:48:59 +0000494 // C++ [conv.lval]p1:
495 // [...] If T is a non-class type, the type of the prvalue is the
496 // cv-unqualified version of T. Otherwise, the type of the
497 // rvalue is T.
498 //
499 // C99 6.3.2.1p2:
500 // If the lvalue has qualified type, the value has the unqualified
501 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000502 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000503 if (T.hasQualifiers())
504 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000505
Eli Friedman3bda6b12012-02-02 23:15:15 +0000506 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +0000507
508 // Loading a __weak object implicitly retains the value, so we need a cleanup to
509 // balance that.
510 if (getLangOpts().ObjCAutoRefCount &&
511 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
512 ExprNeedsCleanups = true;
Eli Friedman3bda6b12012-02-02 23:15:15 +0000513
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000514 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
515 E, 0, VK_RValue));
516
Douglas Gregorc79862f2012-04-12 17:51:55 +0000517 // C11 6.3.2.1p2:
518 // ... if the lvalue has atomic type, the value has the non-atomic version
519 // of the type of the lvalue ...
520 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
521 T = Atomic->getValueType().getUnqualifiedType();
522 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
523 Res.get(), 0, VK_RValue));
524 }
525
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000526 return Res;
John McCall27584242010-12-06 20:48:59 +0000527}
528
John Wiegley01296292011-04-08 18:41:53 +0000529ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
530 ExprResult Res = DefaultFunctionArrayConversion(E);
531 if (Res.isInvalid())
532 return ExprError();
533 Res = DefaultLvalueConversion(Res.take());
534 if (Res.isInvalid())
535 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000536 return Res;
Douglas Gregorb92a1562010-02-03 00:27:59 +0000537}
538
539
Chris Lattner513165e2008-07-25 21:10:04 +0000540/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000541/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000542/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000543/// apply if the array is an argument to the sizeof or address (&) operators.
544/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000545ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000546 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000547 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
548 if (Res.isInvalid())
549 return Owned(E);
550 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000551
John McCallf3735e02010-12-01 04:43:34 +0000552 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000553 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000554
555 // Half FP is a bit different: it's a storage-only type, meaning that any
556 // "use" of it should be promoted to float.
557 if (Ty->isHalfType())
558 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
559
John McCallf3735e02010-12-01 04:43:34 +0000560 // Try to perform integral promotions if the object has a theoretically
561 // promotable type.
562 if (Ty->isIntegralOrUnscopedEnumerationType()) {
563 // C99 6.3.1.1p2:
564 //
565 // The following may be used in an expression wherever an int or
566 // unsigned int may be used:
567 // - an object or expression with an integer type whose integer
568 // conversion rank is less than or equal to the rank of int
569 // and unsigned int.
570 // - A bit-field of type _Bool, int, signed int, or unsigned int.
571 //
572 // If an int can represent all values of the original type, the
573 // value is converted to an int; otherwise, it is converted to an
574 // unsigned int. These are called the integer promotions. All
575 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000576
John McCallf3735e02010-12-01 04:43:34 +0000577 QualType PTy = Context.isPromotableBitField(E);
578 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000579 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
580 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000581 }
582 if (Ty->isPromotableIntegerType()) {
583 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000584 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
585 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000586 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000587 }
John Wiegley01296292011-04-08 18:41:53 +0000588 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000589}
590
Chris Lattner2ce500f2008-07-25 22:25:12 +0000591/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000592/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000593/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000594ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
595 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000596 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000597
John Wiegley01296292011-04-08 18:41:53 +0000598 ExprResult Res = UsualUnaryConversions(E);
599 if (Res.isInvalid())
600 return Owned(E);
601 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000602
Chris Lattner2ce500f2008-07-25 22:25:12 +0000603 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000604 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000605 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
606
John McCall4bb057d2011-08-27 22:06:17 +0000607 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000608 // promotion, even on class types, but note:
609 // C++11 [conv.lval]p2:
610 // When an lvalue-to-rvalue conversion occurs in an unevaluated
611 // operand or a subexpression thereof the value contained in the
612 // referenced object is not accessed. Otherwise, if the glvalue
613 // has a class type, the conversion copy-initializes a temporary
614 // of type T from the glvalue and the result of the conversion
615 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000616 // FIXME: add some way to gate this entire thing for correctness in
617 // potentially potentially evaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +0000618 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman05e28012012-01-17 02:13:45 +0000619 ExprResult Temp = PerformCopyInitialization(
620 InitializedEntity::InitializeTemporary(E->getType()),
621 E->getExprLoc(),
622 Owned(E));
623 if (Temp.isInvalid())
624 return ExprError();
625 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000626 }
627
John Wiegley01296292011-04-08 18:41:53 +0000628 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000629}
630
Richard Smith55ce3522012-06-25 20:30:08 +0000631/// Determine the degree of POD-ness for an expression.
632/// Incomplete types are considered POD, since this check can be performed
633/// when we're in an unevaluated context.
634Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Rose3e0ec582012-07-19 18:10:23 +0000635 if (Ty->isIncompleteType()) {
636 if (Ty->isObjCObjectType())
637 return VAK_Invalid;
Richard Smith55ce3522012-06-25 20:30:08 +0000638 return VAK_Valid;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000639 }
640
641 if (Ty.isCXX98PODType(Context))
642 return VAK_Valid;
643
Richard Smith16488472012-11-16 00:53:38 +0000644 // C++11 [expr.call]p7:
645 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith55ce3522012-06-25 20:30:08 +0000646 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith16488472012-11-16 00:53:38 +0000647 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith55ce3522012-06-25 20:30:08 +0000648 // is conditionally-supported with implementation-defined semantics.
Richard Smith55ce3522012-06-25 20:30:08 +0000649 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
650 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith16488472012-11-16 00:53:38 +0000651 if (!Record->hasNonTrivialCopyConstructor() &&
652 !Record->hasNonTrivialMoveConstructor() &&
653 !Record->hasNonTrivialDestructor())
Richard Smith55ce3522012-06-25 20:30:08 +0000654 return VAK_ValidInCXX11;
655
656 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
657 return VAK_Valid;
658 return VAK_Invalid;
659}
660
661bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
662 // Don't allow one to pass an Objective-C interface to a vararg.
663 const QualType & Ty = E->getType();
664
665 // Complain about passing non-POD types through varargs.
666 switch (isValidVarArgType(Ty)) {
667 case VAK_Valid:
668 break;
669 case VAK_ValidInCXX11:
670 DiagRuntimeBehavior(E->getLocStart(), 0,
671 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
672 << E->getType() << CT);
673 break;
Jordan Rose3e0ec582012-07-19 18:10:23 +0000674 case VAK_Invalid: {
675 if (Ty->isObjCObjectType())
676 return DiagRuntimeBehavior(E->getLocStart(), 0,
677 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
678 << Ty << CT);
679
Richard Smith55ce3522012-06-25 20:30:08 +0000680 return DiagRuntimeBehavior(E->getLocStart(), 0,
681 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
682 << getLangOpts().CPlusPlus0x << Ty << CT);
683 }
Jordan Rose3e0ec582012-07-19 18:10:23 +0000684 }
Richard Smith55ce3522012-06-25 20:30:08 +0000685 // c++ rules are enforced elsewhere.
686 return false;
687}
688
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000689/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Rose3e0ec582012-07-19 18:10:23 +0000690/// will create a trap if the resulting type is not a POD type.
John Wiegley01296292011-04-08 18:41:53 +0000691ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000692 FunctionDecl *FDecl) {
Richard Smith7659b122012-06-27 20:29:39 +0000693 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall4124c492011-10-17 18:40:02 +0000694 // Strip the unbridged-cast placeholder expression off, if applicable.
695 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
696 (CT == VariadicMethod ||
697 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
698 E = stripARCUnbridgedCast(E);
699
700 // Otherwise, do normal placeholder checking.
701 } else {
702 ExprResult ExprRes = CheckPlaceholderExpr(E);
703 if (ExprRes.isInvalid())
704 return ExprError();
705 E = ExprRes.take();
706 }
707 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000708
John McCall4124c492011-10-17 18:40:02 +0000709 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000710 if (ExprRes.isInvalid())
711 return ExprError();
712 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000713
Richard Smith55ce3522012-06-25 20:30:08 +0000714 // Diagnostics regarding non-POD argument types are
715 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith56471fd2012-06-27 20:23:58 +0000716 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith55ce3522012-06-25 20:30:08 +0000717 // Turn this into a trap.
718 CXXScopeSpec SS;
719 SourceLocation TemplateKWLoc;
720 UnqualifiedId Name;
721 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
722 E->getLocStart());
723 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
724 Name, true, false);
725 if (TrapFn.isInvalid())
726 return ExprError();
John McCall31168b02011-06-15 23:02:42 +0000727
Richard Smith55ce3522012-06-25 20:30:08 +0000728 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
729 E->getLocStart(), MultiExprArg(),
730 E->getLocEnd());
731 if (Call.isInvalid())
732 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000733
Richard Smith55ce3522012-06-25 20:30:08 +0000734 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
735 Call.get(), E);
736 if (Comma.isInvalid())
737 return ExprError();
738 return Comma.get();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000739 }
Richard Smith55ce3522012-06-25 20:30:08 +0000740
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000742 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000743 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000744 return ExprError();
Richard Smith55ce3522012-06-25 20:30:08 +0000745
John Wiegley01296292011-04-08 18:41:53 +0000746 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000747}
748
Richard Trieu7aa58f12011-09-02 20:58:51 +0000749/// \brief Converts an integer to complex float type. Helper function of
750/// UsualArithmeticConversions()
751///
752/// \return false if the integer expression is an integer type and is
753/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000754static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
755 ExprResult &ComplexExpr,
756 QualType IntTy,
757 QualType ComplexTy,
758 bool SkipCast) {
759 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
760 if (SkipCast) return false;
761 if (IntTy->isIntegerType()) {
762 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
763 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
764 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000765 CK_FloatingRealToComplex);
766 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000767 assert(IntTy->isComplexIntegerType());
768 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000769 CK_IntegralComplexToFloatingComplex);
770 }
771 return false;
772}
773
774/// \brief Takes two complex float types and converts them to the same type.
775/// Helper function of UsualArithmeticConversions()
776static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000777handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
778 ExprResult &RHS, QualType LHSType,
779 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000780 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000781 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782
783 if (order < 0) {
784 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000785 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000786 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
787 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000788 }
789 if (order > 0)
790 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000791 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
792 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000793}
794
795/// \brief Converts otherExpr to complex float and promotes complexExpr if
796/// necessary. Helper function of UsualArithmeticConversions()
797static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000798 ExprResult &ComplexExpr,
799 ExprResult &OtherExpr,
800 QualType ComplexTy,
801 QualType OtherTy,
802 bool ConvertComplexExpr,
803 bool ConvertOtherExpr) {
804 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000805
806 // If just the complexExpr is complex, the otherExpr needs to be converted,
807 // and the complexExpr might need to be promoted.
808 if (order > 0) { // complexExpr is wider
809 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 if (ConvertOtherExpr) {
811 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
812 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
813 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000814 CK_FloatingRealToComplex);
815 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000816 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000817 }
818
819 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000820 QualType result = (order == 0 ? ComplexTy :
821 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000822
823 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000824 if (ConvertOtherExpr)
825 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000826 CK_FloatingRealToComplex);
827
828 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000829 if (ConvertComplexExpr && order < 0)
830 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000831 CK_FloatingComplexCast);
832
833 return result;
834}
835
836/// \brief Handle arithmetic conversion with complex types. Helper function of
837/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000838static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
839 ExprResult &RHS, QualType LHSType,
840 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000841 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000842 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000843 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000844 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000845 return LHSType;
846 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000847 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000848 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000849
850 // This handles complex/complex, complex/float, or float/complex.
851 // When both operands are complex, the shorter operand is converted to the
852 // type of the longer, and that is the type of the result. This corresponds
853 // to what is done when combining two real floating-point operands.
854 // The fun begins when size promotion occur across type domains.
855 // From H&S 6.3.4: When one operand is complex and the other is a real
856 // floating-point type, the less precise type is converted, within it's
857 // real or complex domain, to the precision of the other type. For example,
858 // when combining a "long double" with a "double _Complex", the
859 // "double _Complex" is promoted to "long double _Complex".
860
Richard Trieu5065cdd2011-09-06 18:25:09 +0000861 bool LHSComplexFloat = LHSType->isComplexType();
862 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000863
864 // If both are complex, just cast to the more precise type.
865 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000866 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
867 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000868 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000869
870 // If only one operand is complex, promote it if necessary and convert the
871 // other operand to complex.
872 if (LHSComplexFloat)
873 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000874 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000875 /*convertOtherExpr*/ true);
876
877 assert(RHSComplexFloat);
878 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000879 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000880 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881}
882
883/// \brief Hande arithmetic conversion from integer to float. Helper function
884/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000885static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
886 ExprResult &IntExpr,
887 QualType FloatTy, QualType IntTy,
888 bool ConvertFloat, bool ConvertInt) {
889 if (IntTy->isIntegerType()) {
890 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000891 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000892 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000893 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000894 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000895 }
896
897 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000898 assert(IntTy->isComplexIntegerType());
899 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000900
901 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000902 if (ConvertInt)
903 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000904 CK_IntegralComplexToFloatingComplex);
905
906 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000907 if (ConvertFloat)
908 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000909 CK_FloatingRealToComplex);
910
911 return result;
912}
913
914/// \brief Handle arithmethic conversion with floating point types. Helper
915/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000916static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
917 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000918 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000919 bool LHSFloat = LHSType->isRealFloatingType();
920 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000921
922 // If we have two real floating types, convert the smaller operand
923 // to the bigger result.
924 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000925 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000926 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000927 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
928 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000929 }
930
931 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000932 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000933 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
934 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000935 }
936
937 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000938 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000939 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000940 /*convertInt=*/ true);
941 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000942 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000943 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000944 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000945}
946
947/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000948/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000949// FIXME: if the operands are (int, _Complex long), we currently
950// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000951static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
952 ExprResult &RHS, QualType LHSType,
953 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000954 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000955 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
956 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000957
Richard Trieucfe3f212011-09-06 18:38:41 +0000958 if (LHSComplexInt && RHSComplexInt) {
959 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
960 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000961 assert(order && "inequal types with equal element ordering");
962 if (order > 0) {
963 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000964 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
965 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000966 }
967
Richard Trieuba63ce62011-09-09 01:45:06 +0000968 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000969 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
970 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000971 }
972
Richard Trieucfe3f212011-09-06 18:38:41 +0000973 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000974 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000975 // FIXME: This needs to take integer ranks into account
976 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
977 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000978 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
979 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000980 }
981
Richard Trieucfe3f212011-09-06 18:38:41 +0000982 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000983 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000984 // FIXME: This needs to take integer ranks into account
985 if (!IsCompAssign) {
986 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
987 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000988 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000989 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000990 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000991}
992
993/// \brief Handle integer arithmetic conversions. Helper function of
994/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000995static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
996 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000997 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000998 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000999 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1000 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1001 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1002 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001003 // Same signedness; use the higher-ranked type
1004 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001005 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1006 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001007 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001008 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1009 return RHSType;
1010 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001011 // The unsigned type has greater than or equal rank to the
1012 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001013 if (RHSSigned) {
1014 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1015 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001017 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1018 return RHSType;
1019 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +00001020 // The two types are different widths; if we are here, that
1021 // means the signed type is larger than the unsigned type, so
1022 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001023 if (LHSSigned) {
1024 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1025 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +00001026 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001027 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1028 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +00001029 } else {
1030 // The signed type is higher-ranked than the unsigned type,
1031 // but isn't actually any bigger (like unsigned int and long
1032 // on most 32-bit systems). Use the unsigned type corresponding
1033 // to the signed type.
1034 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001035 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1036 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +00001037 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001038 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +00001039 return result;
1040 }
1041}
1042
Chris Lattner513165e2008-07-25 21:10:04 +00001043/// UsualArithmeticConversions - Performs various conversions that are common to
1044/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +00001045/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +00001046/// responsible for emitting appropriate error diagnostics.
1047/// FIXME: verify the conversion rules for "complex int" are consistent with
1048/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001049QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00001050 bool IsCompAssign) {
1051 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001052 LHS = UsualUnaryConversions(LHS.take());
1053 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001054 return QualType();
1055 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00001056
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001057 RHS = UsualUnaryConversions(RHS.take());
1058 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001059 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001060
Mike Stump11289f42009-09-09 15:08:12 +00001061 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +00001062 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001063 QualType LHSType =
1064 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1065 QualType RHSType =
1066 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001067
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001068 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1069 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1070 LHSType = AtomicLHS->getValueType();
1071
Douglas Gregora11693b2008-11-12 17:17:38 +00001072 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001073 if (LHSType == RHSType)
1074 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +00001075
1076 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1077 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001078 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001079 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +00001080
John McCalld005ac92010-11-13 08:17:45 +00001081 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001082 QualType LHSUnpromotedType = LHSType;
1083 if (LHSType->isPromotableIntegerType())
1084 LHSType = Context.getPromotedIntegerType(LHSType);
1085 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001086 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001087 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001088 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001089 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001090
John McCalld005ac92010-11-13 08:17:45 +00001091 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001092 if (LHSType == RHSType)
1093 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001094
1095 // At this point, we have two different arithmetic types.
1096
1097 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001098 if (LHSType->isComplexType() || RHSType->isComplexType())
1099 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001100 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001101
1102 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001103 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1104 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001105 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001106
1107 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001108 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001109 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001110 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001111
1112 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001113 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001114 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001115}
1116
Chris Lattner513165e2008-07-25 21:10:04 +00001117//===----------------------------------------------------------------------===//
1118// Semantic Analysis for various Expression Types
1119//===----------------------------------------------------------------------===//
1120
1121
Peter Collingbourne91147592011-04-15 00:35:48 +00001122ExprResult
1123Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1124 SourceLocation DefaultLoc,
1125 SourceLocation RParenLoc,
1126 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001127 MultiTypeArg ArgTypes,
1128 MultiExprArg ArgExprs) {
1129 unsigned NumAssocs = ArgTypes.size();
1130 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001131
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001132 ParsedType *ParsedTypes = ArgTypes.data();
1133 Expr **Exprs = ArgExprs.data();
Peter Collingbourne91147592011-04-15 00:35:48 +00001134
1135 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1136 for (unsigned i = 0; i < NumAssocs; ++i) {
1137 if (ParsedTypes[i])
1138 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1139 else
1140 Types[i] = 0;
1141 }
1142
1143 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1144 ControllingExpr, Types, Exprs,
1145 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001146 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001147 return ER;
1148}
1149
1150ExprResult
1151Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1152 SourceLocation DefaultLoc,
1153 SourceLocation RParenLoc,
1154 Expr *ControllingExpr,
1155 TypeSourceInfo **Types,
1156 Expr **Exprs,
1157 unsigned NumAssocs) {
1158 bool TypeErrorFound = false,
1159 IsResultDependent = ControllingExpr->isTypeDependent(),
1160 ContainsUnexpandedParameterPack
1161 = ControllingExpr->containsUnexpandedParameterPack();
1162
1163 for (unsigned i = 0; i < NumAssocs; ++i) {
1164 if (Exprs[i]->containsUnexpandedParameterPack())
1165 ContainsUnexpandedParameterPack = true;
1166
1167 if (Types[i]) {
1168 if (Types[i]->getType()->containsUnexpandedParameterPack())
1169 ContainsUnexpandedParameterPack = true;
1170
1171 if (Types[i]->getType()->isDependentType()) {
1172 IsResultDependent = true;
1173 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001174 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001175 // complete object type other than a variably modified type."
1176 unsigned D = 0;
1177 if (Types[i]->getType()->isIncompleteType())
1178 D = diag::err_assoc_type_incomplete;
1179 else if (!Types[i]->getType()->isObjectType())
1180 D = diag::err_assoc_type_nonobject;
1181 else if (Types[i]->getType()->isVariablyModifiedType())
1182 D = diag::err_assoc_type_variably_modified;
1183
1184 if (D != 0) {
1185 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1186 << Types[i]->getTypeLoc().getSourceRange()
1187 << Types[i]->getType();
1188 TypeErrorFound = true;
1189 }
1190
Benjamin Kramere56f3932011-12-23 17:00:35 +00001191 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001192 // selection shall specify compatible types."
1193 for (unsigned j = i+1; j < NumAssocs; ++j)
1194 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1195 Context.typesAreCompatible(Types[i]->getType(),
1196 Types[j]->getType())) {
1197 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1198 diag::err_assoc_compatible_types)
1199 << Types[j]->getTypeLoc().getSourceRange()
1200 << Types[j]->getType()
1201 << Types[i]->getType();
1202 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1203 diag::note_compat_assoc)
1204 << Types[i]->getTypeLoc().getSourceRange()
1205 << Types[i]->getType();
1206 TypeErrorFound = true;
1207 }
1208 }
1209 }
1210 }
1211 if (TypeErrorFound)
1212 return ExprError();
1213
1214 // If we determined that the generic selection is result-dependent, don't
1215 // try to compute the result expression.
1216 if (IsResultDependent)
1217 return Owned(new (Context) GenericSelectionExpr(
1218 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001219 llvm::makeArrayRef(Types, NumAssocs),
1220 llvm::makeArrayRef(Exprs, NumAssocs),
1221 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
Peter Collingbourne91147592011-04-15 00:35:48 +00001222
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001223 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001224 unsigned DefaultIndex = -1U;
1225 for (unsigned i = 0; i < NumAssocs; ++i) {
1226 if (!Types[i])
1227 DefaultIndex = i;
1228 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1229 Types[i]->getType()))
1230 CompatIndices.push_back(i);
1231 }
1232
Benjamin Kramere56f3932011-12-23 17:00:35 +00001233 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001234 // type compatible with at most one of the types named in its generic
1235 // association list."
1236 if (CompatIndices.size() > 1) {
1237 // We strip parens here because the controlling expression is typically
1238 // parenthesized in macro definitions.
1239 ControllingExpr = ControllingExpr->IgnoreParens();
1240 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1241 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1242 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001243 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001244 E = CompatIndices.end(); I != E; ++I) {
1245 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1246 diag::note_compat_assoc)
1247 << Types[*I]->getTypeLoc().getSourceRange()
1248 << Types[*I]->getType();
1249 }
1250 return ExprError();
1251 }
1252
Benjamin Kramere56f3932011-12-23 17:00:35 +00001253 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001254 // its controlling expression shall have type compatible with exactly one of
1255 // the types named in its generic association list."
1256 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1257 // We strip parens here because the controlling expression is typically
1258 // parenthesized in macro definitions.
1259 ControllingExpr = ControllingExpr->IgnoreParens();
1260 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1261 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1262 return ExprError();
1263 }
1264
Benjamin Kramere56f3932011-12-23 17:00:35 +00001265 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001266 // type name that is compatible with the type of the controlling expression,
1267 // then the result expression of the generic selection is the expression
1268 // in that generic association. Otherwise, the result expression of the
1269 // generic selection is the expression in the default generic association."
1270 unsigned ResultIndex =
1271 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1272
1273 return Owned(new (Context) GenericSelectionExpr(
1274 Context, KeyLoc, ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001275 llvm::makeArrayRef(Types, NumAssocs),
1276 llvm::makeArrayRef(Exprs, NumAssocs),
1277 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
Peter Collingbourne91147592011-04-15 00:35:48 +00001278 ResultIndex));
1279}
1280
Richard Smith75b67d62012-03-08 01:34:56 +00001281/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1282/// location of the token and the offset of the ud-suffix within it.
1283static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1284 unsigned Offset) {
1285 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001286 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001287}
1288
Richard Smithbcc22fc2012-03-09 08:00:36 +00001289/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1290/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1291static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1292 IdentifierInfo *UDSuffix,
1293 SourceLocation UDSuffixLoc,
1294 ArrayRef<Expr*> Args,
1295 SourceLocation LitEndLoc) {
1296 assert(Args.size() <= 2 && "too many arguments for literal operator");
1297
1298 QualType ArgTy[2];
1299 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1300 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1301 if (ArgTy[ArgIdx]->isArrayType())
1302 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1303 }
1304
1305 DeclarationName OpName =
1306 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1307 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1308 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1309
1310 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1311 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1312 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1313 return ExprError();
1314
1315 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1316}
1317
Steve Naroff83895f72007-09-16 03:34:24 +00001318/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001319/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1320/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1321/// multiple tokens. However, the common case is that StringToks points to one
1322/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001323///
John McCalldadc5752010-08-24 06:29:42 +00001324ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001325Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1326 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001327 assert(NumStringToks && "Must have at least one string!");
1328
Chris Lattner8a24e582009-01-16 18:51:42 +00001329 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001330 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001331 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001332
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001333 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001334 for (unsigned i = 0; i != NumStringToks; ++i)
1335 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001336
Chris Lattner36fc8792008-02-11 00:02:17 +00001337 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001338 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001339 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001340 else if (Literal.isUTF16())
1341 StrTy = Context.Char16Ty;
1342 else if (Literal.isUTF32())
1343 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001344 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001345 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001346
Douglas Gregorfb65e592011-07-27 05:40:30 +00001347 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1348 if (Literal.isWide())
1349 Kind = StringLiteral::Wide;
1350 else if (Literal.isUTF8())
1351 Kind = StringLiteral::UTF8;
1352 else if (Literal.isUTF16())
1353 Kind = StringLiteral::UTF16;
1354 else if (Literal.isUTF32())
1355 Kind = StringLiteral::UTF32;
1356
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001357 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001358 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001359 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001360
Chris Lattner36fc8792008-02-11 00:02:17 +00001361 // Get an array type for the string, according to C99 6.4.5. This includes
1362 // the nul terminator character as well as the string length for pascal
1363 // strings.
1364 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001365 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001366 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattner5b183d82006-11-10 05:03:26 +00001368 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001369 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1370 Kind, Literal.Pascal, StrTy,
1371 &StringTokLocs[0],
1372 StringTokLocs.size());
1373 if (Literal.getUDSuffix().empty())
1374 return Owned(Lit);
1375
1376 // We're building a user-defined literal.
1377 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001378 SourceLocation UDSuffixLoc =
1379 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1380 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001381
Richard Smithbcc22fc2012-03-09 08:00:36 +00001382 // Make sure we're allowed user-defined literals here.
1383 if (!UDLScope)
1384 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1385
Richard Smithc67fdd42012-03-07 08:35:16 +00001386 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1387 // operator "" X (str, len)
1388 QualType SizeType = Context.getSizeType();
1389 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1390 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1391 StringTokLocs[0]);
1392 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001393 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1394 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001395}
1396
John McCalldadc5752010-08-24 06:29:42 +00001397ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001399 SourceLocation Loc,
1400 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001401 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001402 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001403}
1404
John McCallf4cd4f92011-02-09 01:13:10 +00001405/// BuildDeclRefExpr - Build an expression that references a
1406/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001407ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001408Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001409 const DeclarationNameInfo &NameInfo,
1410 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001411 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001412 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1413 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1414 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1415 CalleeTarget = IdentifyCUDATarget(Callee);
1416 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1417 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1418 << CalleeTarget << D->getIdentifier() << CallerTarget;
1419 Diag(D->getLocation(), diag::note_previous_decl)
1420 << D->getIdentifier();
1421 return ExprError();
1422 }
1423 }
1424
John McCall113bee02012-03-10 09:33:50 +00001425 bool refersToEnclosingScope =
1426 (CurContext != D->getDeclContext() &&
1427 D->getDeclContext()->isFunctionOrMethod());
1428
Eli Friedmanfa0df832012-02-02 03:46:19 +00001429 DeclRefExpr *E = DeclRefExpr::Create(Context,
1430 SS ? SS->getWithLocInContext(Context)
1431 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001432 SourceLocation(),
1433 D, refersToEnclosingScope,
1434 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Eli Friedmanfa0df832012-02-02 03:46:19 +00001436 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001437
Jordan Rose657b5f42012-09-28 22:21:35 +00001438 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1439 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1440 DiagnosticsEngine::Level Level =
1441 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1442 E->getLocStart());
1443 if (Level != DiagnosticsEngine::Ignored)
1444 getCurFunction()->recordUseOfWeak(E);
1445 }
1446
John McCall086a4642010-11-24 05:12:34 +00001447 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001448 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1449 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001450 E->setObjectKind(OK_BitField);
1451
1452 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001453}
1454
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001455/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001456/// possibly a list of template arguments.
1457///
1458/// If this produces template arguments, it is permitted to call
1459/// DecomposeTemplateName.
1460///
1461/// This actually loses a lot of source location information for
1462/// non-standard name kinds; we should consider preserving that in
1463/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001464void
1465Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1466 TemplateArgumentListInfo &Buffer,
1467 DeclarationNameInfo &NameInfo,
1468 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001469 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1470 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1471 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1472
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001473 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall10eae182009-11-30 22:42:35 +00001474 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001475 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001476
John McCall3e56fd42010-08-23 07:28:44 +00001477 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001478 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001479 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001480 TemplateArgs = &Buffer;
1481 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001482 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001483 TemplateArgs = 0;
1484 }
1485}
1486
John McCalld681c392009-12-16 08:11:27 +00001487/// Diagnose an empty lookup.
1488///
1489/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001490bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001491 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001492 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001493 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001494 DeclarationName Name = R.getLookupName();
1495
John McCalld681c392009-12-16 08:11:27 +00001496 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001497 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001498 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1499 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001500 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001501 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001502 diagnostic_suggest = diag::err_undeclared_use_suggest;
1503 }
John McCalld681c392009-12-16 08:11:27 +00001504
Douglas Gregor598b08f2009-12-31 05:20:13 +00001505 // If the original lookup was an unqualified lookup, fake an
1506 // unqualified lookup. This is useful when (for example) the
1507 // original lookup would not have found something because it was a
1508 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001509 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1510 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001511 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001512 if (isa<CXXRecordDecl>(DC)) {
1513 LookupQualifiedName(R, DC);
1514
1515 if (!R.empty()) {
1516 // Don't give errors about ambiguities in this lookup.
1517 R.suppressDiagnostics();
1518
Francois Pichet857f9d62011-11-17 03:44:24 +00001519 // During a default argument instantiation the CurContext points
1520 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1521 // function parameter list, hence add an explicit check.
1522 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1523 ActiveTemplateInstantiations.back().Kind ==
1524 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001525 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1526 bool isInstance = CurMethod &&
1527 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001528 DC == CurMethod->getParent() && !isDefaultArgument;
1529
John McCalld681c392009-12-16 08:11:27 +00001530
1531 // Give a code modification hint to insert 'this->'.
1532 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1533 // Actually quite difficult!
Nico Weberdf7dffb2012-06-20 20:21:42 +00001534 if (getLangOpts().MicrosoftMode)
1535 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001536 if (isInstance) {
Nico Weber3c10fb12012-06-22 16:39:39 +00001537 Diag(R.getNameLoc(), diagnostic) << Name
1538 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001539 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1540 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber3c10fb12012-06-22 16:39:39 +00001541
1542
1543 CXXMethodDecl *DepMethod;
1544 if (CurMethod->getTemplatedKind() ==
1545 FunctionDecl::TK_FunctionTemplateSpecialization)
1546 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1547 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1548 else
1549 DepMethod = cast<CXXMethodDecl>(
1550 CurMethod->getInstantiatedFromMemberFunction());
1551 assert(DepMethod && "No template pattern found");
1552
1553 QualType DepThisType = DepMethod->getThisType(Context);
1554 CheckCXXThisCapture(R.getNameLoc());
1555 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1556 R.getNameLoc(), DepThisType, false);
1557 TemplateArgumentListInfo TList;
1558 if (ULE->hasExplicitTemplateArgs())
1559 ULE->copyTemplateArgumentsInto(TList);
1560
1561 CXXScopeSpec SS;
1562 SS.Adopt(ULE->getQualifierLoc());
1563 CXXDependentScopeMemberExpr *DepExpr =
1564 CXXDependentScopeMemberExpr::Create(
1565 Context, DepThis, DepThisType, true, SourceLocation(),
1566 SS.getWithLocInContext(Context),
1567 ULE->getTemplateKeywordLoc(), 0,
1568 R.getLookupNameInfo(),
1569 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1570 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001571 } else {
John McCalld681c392009-12-16 08:11:27 +00001572 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001573 }
John McCalld681c392009-12-16 08:11:27 +00001574
1575 // Do we really want to note all of these?
1576 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1577 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1578
Francois Pichet857f9d62011-11-17 03:44:24 +00001579 // Return true if we are inside a default argument instantiation
1580 // and the found name refers to an instance member function, otherwise
1581 // the function calling DiagnoseEmptyLookup will try to create an
1582 // implicit member call and this is wrong for default argument.
1583 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1584 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1585 return true;
1586 }
1587
John McCalld681c392009-12-16 08:11:27 +00001588 // Tell the callee to try to recover.
1589 return false;
1590 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001591
1592 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001593 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001594
1595 // In Microsoft mode, if we are performing lookup from within a friend
1596 // function definition declared at class scope then we must set
1597 // DC to the lexical parent to be able to search into the parent
1598 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001599 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001600 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1601 DC->getLexicalParent()->isRecord())
1602 DC = DC->getLexicalParent();
1603 else
1604 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001605 }
1606
Douglas Gregor598b08f2009-12-31 05:20:13 +00001607 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001608 TypoCorrection Corrected;
1609 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001610 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001611 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1612 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001613 R.setLookupName(Corrected.getCorrection());
1614
Hans Wennborg38198de2011-07-12 08:45:31 +00001615 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001616 if (Corrected.isOverloaded()) {
1617 OverloadCandidateSet OCS(R.getNameLoc());
1618 OverloadCandidateSet::iterator Best;
1619 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1620 CDEnd = Corrected.end();
1621 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001622 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001623 dyn_cast<FunctionTemplateDecl>(*CD))
1624 AddTemplateOverloadCandidate(
1625 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001626 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001627 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1628 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1629 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001630 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001631 }
1632 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1633 case OR_Success:
1634 ND = Best->Function;
1635 break;
1636 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001637 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001638 }
1639 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001640 R.addDecl(ND);
1641 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001642 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001643 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1644 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001645 else
1646 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001647 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001648 << SS.getRange()
David Blaikie04ea41c2012-10-12 20:00:44 +00001649 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1650 CorrectedStr);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001651 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001652 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001653 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001654
1655 // Tell the callee to try to recover.
1656 return false;
1657 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001658
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001659 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001660 // FIXME: If we ended up with a typo for a type name or
1661 // Objective-C class name, we're in trouble because the parser
1662 // is in the wrong place to recover. Suggest the typo
1663 // correction, but don't make it a fix-it since we're not going
1664 // to recover well anyway.
1665 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001666 Diag(R.getNameLoc(), diagnostic_suggest)
1667 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001668 else
1669 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001670 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001671 << SS.getRange();
1672
1673 // Don't try to recover; it won't work.
1674 return true;
1675 }
1676 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001677 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001678 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001679 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001680 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001681 else
Douglas Gregor25363982010-01-01 00:15:04 +00001682 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001683 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001684 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001685 return true;
1686 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001687 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001688 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001689
1690 // Emit a special diagnostic for failed member lookups.
1691 // FIXME: computing the declaration context might fail here (?)
1692 if (!SS.isEmpty()) {
1693 Diag(R.getNameLoc(), diag::err_no_member)
1694 << Name << computeDeclContext(SS, false)
1695 << SS.getRange();
1696 return true;
1697 }
1698
John McCalld681c392009-12-16 08:11:27 +00001699 // Give up, we can't recover.
1700 Diag(R.getNameLoc(), diagnostic) << Name;
1701 return true;
1702}
1703
John McCalldadc5752010-08-24 06:29:42 +00001704ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001705 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001706 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001707 UnqualifiedId &Id,
1708 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001709 bool IsAddressOfOperand,
1710 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001711 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001712 "cannot be direct & operand and have a trailing lparen");
1713
1714 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001715 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001716
John McCall10eae182009-11-30 22:42:35 +00001717 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001718
1719 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001720 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001721 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001722 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001723
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001724 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001725 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001726 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001727
John McCalle66edc12009-11-24 19:00:30 +00001728 // C++ [temp.dep.expr]p3:
1729 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001730 // -- an identifier that was declared with a dependent type,
1731 // (note: handled after lookup)
1732 // -- a template-id that is dependent,
1733 // (note: handled in BuildTemplateIdExpr)
1734 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001735 // -- a nested-name-specifier that contains a class-name that
1736 // names a dependent type.
1737 // Determine whether this is a member of an unknown specialization;
1738 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001739 bool DependentID = false;
1740 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1741 Name.getCXXNameType()->isDependentType()) {
1742 DependentID = true;
1743 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001744 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001745 if (RequireCompleteDeclContext(SS, DC))
1746 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001747 } else {
1748 DependentID = true;
1749 }
1750 }
1751
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001752 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001753 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1754 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001755
John McCalle66edc12009-11-24 19:00:30 +00001756 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001757 LookupResult R(*this, NameInfo,
1758 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1759 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001760 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001761 // Lookup the template name again to correctly establish the context in
1762 // which it was found. This is really unfortunate as we already did the
1763 // lookup to determine that it was a template name in the first place. If
1764 // this becomes a performance hit, we can work harder to preserve those
1765 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001766 bool MemberOfUnknownSpecialization;
1767 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1768 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001769
1770 if (MemberOfUnknownSpecialization ||
1771 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001772 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1773 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001774 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001775 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001776 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001777
Douglas Gregora5226932011-02-04 13:35:07 +00001778 // If the result might be in a dependent base class, this is a dependent
1779 // id-expression.
1780 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001781 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1782 IsAddressOfOperand, TemplateArgs);
1783
John McCalle66edc12009-11-24 19:00:30 +00001784 // If this reference is in an Objective-C method, then we need to do
1785 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001786 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001787 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001788 if (E.isInvalid())
1789 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001790
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001791 if (Expr *Ex = E.takeAs<Expr>())
1792 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001793 }
Chris Lattner59a25942008-03-31 00:36:02 +00001794 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001795
John McCalle66edc12009-11-24 19:00:30 +00001796 if (R.isAmbiguous())
1797 return ExprError();
1798
Douglas Gregor171c45a2009-02-18 21:56:37 +00001799 // Determine whether this name might be a candidate for
1800 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001801 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001802
John McCalle66edc12009-11-24 19:00:30 +00001803 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001804 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001805 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001806 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001807 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1808 if (D) R.addDecl(D);
1809 }
1810
1811 // If this name wasn't predeclared and if this is not a function
1812 // call, diagnose the problem.
1813 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001814
1815 // In Microsoft mode, if we are inside a template class member function
1816 // and we can't resolve an identifier then assume the identifier is type
1817 // dependent. The goal is to postpone name lookup to instantiation time
1818 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001819 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001820 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001821 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1822 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001823
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001824 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001825 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001826 return ExprError();
1827
1828 assert(!R.empty() &&
1829 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001830
1831 // If we found an Objective-C instance variable, let
1832 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001833 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001834 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1835 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001836 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001837 // In a hopelessly buggy code, Objective-C instance variable
1838 // lookup fails and no expression will be built to reference it.
1839 if (!E.isInvalid() && !E.get())
1840 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001841 return E;
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001842 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001843 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
John McCalle66edc12009-11-24 19:00:30 +00001846 // This is guaranteed from this point on.
1847 assert(!R.empty() || ADL);
1848
John McCall2d74de92009-12-01 22:10:20 +00001849 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001850 // C++ [class.mfct.non-static]p3:
1851 // When an id-expression that is not part of a class member access
1852 // syntax and not used to form a pointer to member is used in the
1853 // body of a non-static member function of class X, if name lookup
1854 // resolves the name in the id-expression to a non-static non-type
1855 // member of some class C, the id-expression is transformed into a
1856 // class member access expression using (*this) as the
1857 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001858 //
1859 // But we don't actually need to do this for '&' operands if R
1860 // resolved to a function or overloaded function set, because the
1861 // expression is ill-formed if it actually works out to be a
1862 // non-static member function:
1863 //
1864 // C++ [expr.ref]p4:
1865 // Otherwise, if E1.E2 refers to a non-static member function. . .
1866 // [t]he expression can be used only as the left-hand operand of a
1867 // member function call.
1868 //
1869 // There are other safeguards against such uses, but it's important
1870 // to get this right here so that we don't end up making a
1871 // spuriously dependent expression if we're inside a dependent
1872 // instance method.
John McCall57500772009-12-16 12:17:52 +00001873 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001874 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001875 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001876 MightBeImplicitMember = true;
1877 else if (!SS.isEmpty())
1878 MightBeImplicitMember = false;
1879 else if (R.isOverloadedResult())
1880 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001881 else if (R.isUnresolvableResult())
1882 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001883 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001884 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1885 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001886
1887 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001888 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1889 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001890 }
1891
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001892 if (TemplateArgs || TemplateKWLoc.isValid())
1893 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001894
John McCalle66edc12009-11-24 19:00:30 +00001895 return BuildDeclarationNameExpr(SS, R, ADL);
1896}
1897
John McCall10eae182009-11-30 22:42:35 +00001898/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1899/// declaration name, generally during template instantiation.
1900/// There's a large number of things which don't need to be done along
1901/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001902ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001903Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Richard Smithdb2630f2012-10-21 03:28:35 +00001904 const DeclarationNameInfo &NameInfo,
1905 bool IsAddressOfOperand) {
Richard Smith40c180d2012-10-23 19:56:01 +00001906 DeclContext *DC = computeDeclContext(SS, false);
1907 if (!DC)
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001908 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1909 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001910
John McCall0b66eb32010-05-01 00:40:08 +00001911 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001912 return ExprError();
1913
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001914 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001915 LookupQualifiedName(R, DC);
1916
1917 if (R.isAmbiguous())
1918 return ExprError();
1919
Richard Smith40c180d2012-10-23 19:56:01 +00001920 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1921 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1922 NameInfo, /*TemplateArgs=*/0);
1923
John McCalle66edc12009-11-24 19:00:30 +00001924 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001925 Diag(NameInfo.getLoc(), diag::err_no_member)
1926 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001927 return ExprError();
1928 }
1929
Richard Smithdb2630f2012-10-21 03:28:35 +00001930 // Defend against this resolving to an implicit member access. We usually
1931 // won't get here if this might be a legitimate a class member (we end up in
1932 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1933 // a pointer-to-member or in an unevaluated context in C++11.
1934 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1935 return BuildPossibleImplicitMemberExpr(SS,
1936 /*TemplateKWLoc=*/SourceLocation(),
1937 R, /*TemplateArgs=*/0);
1938
1939 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCalle66edc12009-11-24 19:00:30 +00001940}
1941
1942/// LookupInObjCMethod - The parser has read a name in, and Sema has
1943/// detected that we're currently inside an ObjC method. Perform some
1944/// additional lookup.
1945///
1946/// Ideally, most of this would be done by lookup, but there's
1947/// actually quite a lot of extra work involved.
1948///
1949/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001950ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001951Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001952 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001953 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001954 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001955
John McCalle66edc12009-11-24 19:00:30 +00001956 // There are two cases to handle here. 1) scoped lookup could have failed,
1957 // in which case we should look for an ivar. 2) scoped lookup could have
1958 // found a decl, but that decl is outside the current instance method (i.e.
1959 // a global variable). In these two cases, we do a lookup for an ivar with
1960 // this name, if the lookup sucedes, we replace it our current decl.
1961
1962 // If we're in a class method, we don't normally want to look for
1963 // ivars. But if we don't find anything else, and there's an
1964 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001965 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001966
1967 bool LookForIvars;
1968 if (Lookup.empty())
1969 LookForIvars = true;
1970 else if (IsClassMethod)
1971 LookForIvars = false;
1972 else
1973 LookForIvars = (Lookup.isSingleResult() &&
1974 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001975 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001976 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001977 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001978 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001979 ObjCIvarDecl *IV = 0;
1980 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001981 // Diagnose using an ivar in a class method.
1982 if (IsClassMethod)
1983 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1984 << IV->getDeclName());
1985
1986 // If we're referencing an invalid decl, just return this as a silent
1987 // error node. The error diagnostic was already emitted on the decl.
1988 if (IV->isInvalidDecl())
1989 return ExprError();
1990
1991 // Check if referencing a field with __attribute__((deprecated)).
1992 if (DiagnoseUseOfDecl(IV, Loc))
1993 return ExprError();
1994
1995 // Diagnose the use of an ivar outside of the declaring class.
1996 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001997 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001998 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001999 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2000
2001 // FIXME: This should use a new expr for a direct reference, don't
2002 // turn this into Self->ivar, just return a BareIVarExpr or something.
2003 IdentifierInfo &II = Context.Idents.get("self");
2004 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002005 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002006 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00002007 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00002008 SourceLocation TemplateKWLoc;
2009 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002010 SelfName, false, false);
2011 if (SelfExpr.isInvalid())
2012 return ExprError();
2013
John Wiegley01296292011-04-08 18:41:53 +00002014 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2015 if (SelfExpr.isInvalid())
2016 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002017
Eli Friedmanfa0df832012-02-02 03:46:19 +00002018 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00002019
2020 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2021 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2022 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose657b5f42012-09-28 22:21:35 +00002023
2024 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2025 Loc,
2026 SelfExpr.take(),
2027 true, true);
2028
2029 if (getLangOpts().ObjCAutoRefCount) {
2030 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2031 DiagnosticsEngine::Level Level =
2032 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2033 if (Level != DiagnosticsEngine::Ignored)
2034 getCurFunction()->recordUseOfWeak(Result);
2035 }
Fariborz Jahanian4a675082012-10-03 17:55:29 +00002036 if (CurContext->isClosure())
2037 Diag(Loc, diag::warn_implicitly_retains_self)
2038 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose657b5f42012-09-28 22:21:35 +00002039 }
2040
2041 return Owned(Result);
John McCalle66edc12009-11-24 19:00:30 +00002042 }
Chris Lattner87313662010-04-12 05:10:17 +00002043 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002044 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002045 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2046 ObjCInterfaceDecl *ClassDeclared;
2047 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2048 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00002049 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00002050 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2051 }
John McCalle66edc12009-11-24 19:00:30 +00002052 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00002053 } else if (Lookup.isSingleResult() &&
2054 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2055 // If accessing a stand-alone ivar in a class method, this is an error.
2056 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2057 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2058 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00002059 }
2060
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002061 if (Lookup.empty() && II && AllowBuiltinCreation) {
2062 // FIXME. Consolidate this with similar code in LookupName.
2063 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002064 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002065 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2066 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2067 S, Lookup.isForRedeclaration(),
2068 Lookup.getNameLoc());
2069 if (D) Lookup.addDecl(D);
2070 }
2071 }
2072 }
John McCalle66edc12009-11-24 19:00:30 +00002073 // Sentinel value saying that we didn't do anything special.
2074 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002075}
John McCalld14a8642009-11-21 08:51:07 +00002076
John McCall16df1e52010-03-30 21:47:33 +00002077/// \brief Cast a base object to a member's actual type.
2078///
2079/// Logically this happens in three phases:
2080///
2081/// * First we cast from the base type to the naming class.
2082/// The naming class is the class into which we were looking
2083/// when we found the member; it's the qualifier type if a
2084/// qualifier was provided, and otherwise it's the base type.
2085///
2086/// * Next we cast from the naming class to the declaring class.
2087/// If the member we found was brought into a class's scope by
2088/// a using declaration, this is that class; otherwise it's
2089/// the class declaring the member.
2090///
2091/// * Finally we cast from the declaring class to the "true"
2092/// declaring class of the member. This conversion does not
2093/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002094ExprResult
2095Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002096 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002097 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002098 NamedDecl *Member) {
2099 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2100 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002101 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002102
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002103 QualType DestRecordType;
2104 QualType DestType;
2105 QualType FromRecordType;
2106 QualType FromType = From->getType();
2107 bool PointerConversions = false;
2108 if (isa<FieldDecl>(Member)) {
2109 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002110
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002111 if (FromType->getAs<PointerType>()) {
2112 DestType = Context.getPointerType(DestRecordType);
2113 FromRecordType = FromType->getPointeeType();
2114 PointerConversions = true;
2115 } else {
2116 DestType = DestRecordType;
2117 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002118 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002119 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2120 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002121 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002122
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002123 DestType = Method->getThisType(Context);
2124 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002125
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002126 if (FromType->getAs<PointerType>()) {
2127 FromRecordType = FromType->getPointeeType();
2128 PointerConversions = true;
2129 } else {
2130 FromRecordType = FromType;
2131 DestType = DestRecordType;
2132 }
2133 } else {
2134 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002135 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002136 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002137
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002138 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002139 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002140
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002141 // If the unqualified types are the same, no conversion is necessary.
2142 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002143 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002144
John McCall16df1e52010-03-30 21:47:33 +00002145 SourceRange FromRange = From->getSourceRange();
2146 SourceLocation FromLoc = FromRange.getBegin();
2147
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002148 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002149
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002150 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002151 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002152 // class name.
2153 //
2154 // If the member was a qualified name and the qualified referred to a
2155 // specific base subobject type, we'll cast to that intermediate type
2156 // first and then to the object in which the member is declared. That allows
2157 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2158 //
2159 // class Base { public: int x; };
2160 // class Derived1 : public Base { };
2161 // class Derived2 : public Base { };
2162 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2163 //
2164 // void VeryDerived::f() {
2165 // x = 17; // error: ambiguous base subobjects
2166 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2167 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002168 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002169 QualType QType = QualType(Qualifier->getAsType(), 0);
2170 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2171 assert(QType->isRecordType() && "lookup done with non-record type");
2172
2173 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2174
2175 // In C++98, the qualifier type doesn't actually have to be a base
2176 // type of the object type, in which case we just ignore it.
2177 // Otherwise build the appropriate casts.
2178 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002179 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002180 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002181 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002182 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002183
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002184 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002185 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002186 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2187 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002188
2189 FromType = QType;
2190 FromRecordType = QRecordType;
2191
2192 // If the qualifier type was the same as the destination type,
2193 // we're done.
2194 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002195 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002196 }
2197 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002198
John McCall16df1e52010-03-30 21:47:33 +00002199 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002200
John McCall16df1e52010-03-30 21:47:33 +00002201 // If we actually found the member through a using declaration, cast
2202 // down to the using declaration's type.
2203 //
2204 // Pointer equality is fine here because only one declaration of a
2205 // class ever has member declarations.
2206 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2207 assert(isa<UsingShadowDecl>(FoundDecl));
2208 QualType URecordType = Context.getTypeDeclType(
2209 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2210
2211 // We only need to do this if the naming-class to declaring-class
2212 // conversion is non-trivial.
2213 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2214 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002215 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002216 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002217 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002218 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002219
John McCall16df1e52010-03-30 21:47:33 +00002220 QualType UType = URecordType;
2221 if (PointerConversions)
2222 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002223 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2224 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002225 FromType = UType;
2226 FromRecordType = URecordType;
2227 }
2228
2229 // We don't do access control for the conversion from the
2230 // declaring class to the true declaring class.
2231 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002232 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002233
John McCallcf142162010-08-07 06:22:56 +00002234 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002235 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2236 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002237 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002238 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002239
John Wiegley01296292011-04-08 18:41:53 +00002240 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2241 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002242}
Douglas Gregor3256d042009-06-30 15:47:41 +00002243
John McCalle66edc12009-11-24 19:00:30 +00002244bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002245 const LookupResult &R,
2246 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002247 // Only when used directly as the postfix-expression of a call.
2248 if (!HasTrailingLParen)
2249 return false;
2250
2251 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002252 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002253 return false;
2254
2255 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002256 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002257 return false;
2258
2259 // Turn off ADL when we find certain kinds of declarations during
2260 // normal lookup:
2261 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2262 NamedDecl *D = *I;
2263
2264 // C++0x [basic.lookup.argdep]p3:
2265 // -- a declaration of a class member
2266 // Since using decls preserve this property, we check this on the
2267 // original decl.
John McCall57500772009-12-16 12:17:52 +00002268 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002269 return false;
2270
2271 // C++0x [basic.lookup.argdep]p3:
2272 // -- a block-scope function declaration that is not a
2273 // using-declaration
2274 // NOTE: we also trigger this for function templates (in fact, we
2275 // don't check the decl type at all, since all other decl types
2276 // turn off ADL anyway).
2277 if (isa<UsingShadowDecl>(D))
2278 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2279 else if (D->getDeclContext()->isFunctionOrMethod())
2280 return false;
2281
2282 // C++0x [basic.lookup.argdep]p3:
2283 // -- a declaration that is neither a function or a function
2284 // template
2285 // And also for builtin functions.
2286 if (isa<FunctionDecl>(D)) {
2287 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2288
2289 // But also builtin functions.
2290 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2291 return false;
2292 } else if (!isa<FunctionTemplateDecl>(D))
2293 return false;
2294 }
2295
2296 return true;
2297}
2298
2299
John McCalld14a8642009-11-21 08:51:07 +00002300/// Diagnoses obvious problems with the use of the given declaration
2301/// as an expression. This is only actually called for lookups that
2302/// were not overloaded, and it doesn't promise that the declaration
2303/// will in fact be used.
2304static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002305 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002306 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2307 return true;
2308 }
2309
2310 if (isa<ObjCInterfaceDecl>(D)) {
2311 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2312 return true;
2313 }
2314
2315 if (isa<NamespaceDecl>(D)) {
2316 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2317 return true;
2318 }
2319
2320 return false;
2321}
2322
John McCalldadc5752010-08-24 06:29:42 +00002323ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002324Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002325 LookupResult &R,
2326 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002327 // If this is a single, fully-resolved result and we don't need ADL,
2328 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002329 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002330 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2331 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002332
2333 // We only need to check the declaration if there's exactly one
2334 // result, because in the overloaded case the results can only be
2335 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002336 if (R.isSingleResult() &&
2337 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002338 return ExprError();
2339
John McCall58cc69d2010-01-27 01:50:18 +00002340 // Otherwise, just build an unresolved lookup expression. Suppress
2341 // any lookup-related diagnostics; we'll hash these out later, when
2342 // we've picked a target.
2343 R.suppressDiagnostics();
2344
John McCalld14a8642009-11-21 08:51:07 +00002345 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002346 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002347 SS.getWithLocInContext(Context),
2348 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002349 NeedsADL, R.isOverloadedResult(),
2350 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002351
2352 return Owned(ULE);
2353}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002354
John McCalld14a8642009-11-21 08:51:07 +00002355/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002356ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002357Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002358 const DeclarationNameInfo &NameInfo,
2359 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002360 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002361 assert(!isa<FunctionTemplateDecl>(D) &&
2362 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002363
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002364 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002365 if (CheckDeclInExpr(*this, Loc, D))
2366 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002367
Douglas Gregore7488b92009-12-01 16:58:18 +00002368 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2369 // Specifically diagnose references to class templates that are missing
2370 // a template argument list.
2371 Diag(Loc, diag::err_template_decl_ref)
2372 << Template << SS.getRange();
2373 Diag(Template->getLocation(), diag::note_template_decl_here);
2374 return ExprError();
2375 }
2376
2377 // Make sure that we're referring to a value.
2378 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2379 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002380 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002381 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002382 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002383 return ExprError();
2384 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002385
Douglas Gregor171c45a2009-02-18 21:56:37 +00002386 // Check whether this declaration can be used. Note that we suppress
2387 // this check when we're going to perform argument-dependent lookup
2388 // on this function name, because this might not be the function
2389 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002390 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002391 return ExprError();
2392
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002393 // Only create DeclRefExpr's for valid Decl's.
2394 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002395 return ExprError();
2396
John McCallf3a88602011-02-03 08:15:49 +00002397 // Handle members of anonymous structs and unions. If we got here,
2398 // and the reference is to a class member indirect field, then this
2399 // must be the subject of a pointer-to-member expression.
2400 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2401 if (!indirectField->isCXXClassMember())
2402 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2403 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002404
Eli Friedman9bb33f52012-02-03 02:04:35 +00002405 {
John McCallf4cd4f92011-02-09 01:13:10 +00002406 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002407 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002408
2409 switch (D->getKind()) {
2410 // Ignore all the non-ValueDecl kinds.
2411#define ABSTRACT_DECL(kind)
2412#define VALUE(type, base)
2413#define DECL(type, base) \
2414 case Decl::type:
2415#include "clang/AST/DeclNodes.inc"
2416 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002417
2418 // These shouldn't make it here.
2419 case Decl::ObjCAtDefsField:
2420 case Decl::ObjCIvar:
2421 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002422
2423 // Enum constants are always r-values and never references.
2424 // Unresolved using declarations are dependent.
2425 case Decl::EnumConstant:
2426 case Decl::UnresolvedUsingValue:
2427 valueKind = VK_RValue;
2428 break;
2429
2430 // Fields and indirect fields that got here must be for
2431 // pointer-to-member expressions; we just call them l-values for
2432 // internal consistency, because this subexpression doesn't really
2433 // exist in the high-level semantics.
2434 case Decl::Field:
2435 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002436 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002437 "building reference to field in C?");
2438
2439 // These can't have reference type in well-formed programs, but
2440 // for internal consistency we do this anyway.
2441 type = type.getNonReferenceType();
2442 valueKind = VK_LValue;
2443 break;
2444
2445 // Non-type template parameters are either l-values or r-values
2446 // depending on the type.
2447 case Decl::NonTypeTemplateParm: {
2448 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2449 type = reftype->getPointeeType();
2450 valueKind = VK_LValue; // even if the parameter is an r-value reference
2451 break;
2452 }
2453
2454 // For non-references, we need to strip qualifiers just in case
2455 // the template parameter was declared as 'const int' or whatever.
2456 valueKind = VK_RValue;
2457 type = type.getUnqualifiedType();
2458 break;
2459 }
2460
2461 case Decl::Var:
2462 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002464 !type.hasQualifiers() &&
2465 type->isVoidType()) {
2466 valueKind = VK_RValue;
2467 break;
2468 }
2469 // fallthrough
2470
2471 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002472 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002473 // These are always l-values.
2474 valueKind = VK_LValue;
2475 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002476
Douglas Gregor812d8f62012-02-18 05:51:20 +00002477 // FIXME: Does the addition of const really only apply in
2478 // potentially-evaluated contexts? Since the variable isn't actually
2479 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie131fcb42012-08-06 22:47:24 +00002480 if (!isUnevaluatedContext()) {
Douglas Gregor812d8f62012-02-18 05:51:20 +00002481 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2482 if (!CapturedType.isNull())
2483 type = CapturedType;
2484 }
2485
John McCallf4cd4f92011-02-09 01:13:10 +00002486 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002487 }
2488
John McCallf4cd4f92011-02-09 01:13:10 +00002489 case Decl::Function: {
Eli Friedman34866c72012-08-31 00:14:07 +00002490 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2491 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2492 type = Context.BuiltinFnTy;
2493 valueKind = VK_RValue;
2494 break;
2495 }
2496 }
2497
John McCall2979fe02011-04-12 00:42:48 +00002498 const FunctionType *fty = type->castAs<FunctionType>();
2499
2500 // If we're referring to a function with an __unknown_anytype
2501 // result type, make the entire expression __unknown_anytype.
2502 if (fty->getResultType() == Context.UnknownAnyTy) {
2503 type = Context.UnknownAnyTy;
2504 valueKind = VK_RValue;
2505 break;
2506 }
2507
John McCallf4cd4f92011-02-09 01:13:10 +00002508 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002509 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002510 valueKind = VK_LValue;
2511 break;
2512 }
2513
2514 // C99 DR 316 says that, if a function type comes from a
2515 // function definition (without a prototype), that type is only
2516 // used for checking compatibility. Therefore, when referencing
2517 // the function, we pretend that we don't have the full function
2518 // type.
John McCall2979fe02011-04-12 00:42:48 +00002519 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2520 isa<FunctionProtoType>(fty))
2521 type = Context.getFunctionNoProtoType(fty->getResultType(),
2522 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002523
2524 // Functions are r-values in C.
2525 valueKind = VK_RValue;
2526 break;
2527 }
2528
2529 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002530 // If we're referring to a method with an __unknown_anytype
2531 // result type, make the entire expression __unknown_anytype.
2532 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002533 if (const FunctionProtoType *proto
2534 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002535 if (proto->getResultType() == Context.UnknownAnyTy) {
2536 type = Context.UnknownAnyTy;
2537 valueKind = VK_RValue;
2538 break;
2539 }
2540
John McCallf4cd4f92011-02-09 01:13:10 +00002541 // C++ methods are l-values if static, r-values if non-static.
2542 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2543 valueKind = VK_LValue;
2544 break;
2545 }
2546 // fallthrough
2547
2548 case Decl::CXXConversion:
2549 case Decl::CXXDestructor:
2550 case Decl::CXXConstructor:
2551 valueKind = VK_RValue;
2552 break;
2553 }
2554
2555 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2556 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002557}
Chris Lattnere168f762006-11-10 05:29:30 +00002558
John McCall2979fe02011-04-12 00:42:48 +00002559ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002560 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002561
Chris Lattnere168f762006-11-10 05:29:30 +00002562 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002563 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002564 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2565 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber3a691a32012-06-23 02:07:59 +00002566 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattner6307f192008-08-10 01:53:14 +00002567 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002568 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002569
Chris Lattnera81a0272008-01-12 08:14:25 +00002570 // Pre-defined identifiers are of type char[x], where x is the length of the
2571 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002572
Anders Carlsson2fb08242009-09-08 18:24:21 +00002573 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002574 if (!currentDecl && getCurBlock())
2575 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002576 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002577 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002578 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002579 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002580
Anders Carlsson0b209a82009-09-11 01:22:35 +00002581 QualType ResTy;
2582 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2583 ResTy = Context.DependentTy;
2584 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002585 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002586
Anders Carlsson0b209a82009-09-11 01:22:35 +00002587 llvm::APInt LengthI(32, Length + 1);
Nico Weber3052abd2012-06-29 16:39:58 +00002588 if (IT == PredefinedExpr::LFunction)
Nico Weber3a691a32012-06-23 02:07:59 +00002589 ResTy = Context.WCharTy.withConst();
2590 else
2591 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002592 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2593 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002594 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002595}
2596
Richard Smithbcc22fc2012-03-09 08:00:36 +00002597ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002598 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002599 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002600 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002601 if (Invalid)
2602 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002603
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002604 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002605 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002606 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002607 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002608
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002609 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002610 if (Literal.isWide())
2611 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002612 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002613 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002614 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002615 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002616 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002617 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002618 else
2619 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002620
Douglas Gregorfb65e592011-07-27 05:40:30 +00002621 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2622 if (Literal.isWide())
2623 Kind = CharacterLiteral::Wide;
2624 else if (Literal.isUTF16())
2625 Kind = CharacterLiteral::UTF16;
2626 else if (Literal.isUTF32())
2627 Kind = CharacterLiteral::UTF32;
2628
Richard Smith75b67d62012-03-08 01:34:56 +00002629 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2630 Tok.getLocation());
2631
2632 if (Literal.getUDSuffix().empty())
2633 return Owned(Lit);
2634
2635 // We're building a user-defined literal.
2636 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2637 SourceLocation UDSuffixLoc =
2638 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2639
Richard Smithbcc22fc2012-03-09 08:00:36 +00002640 // Make sure we're allowed user-defined literals here.
2641 if (!UDLScope)
2642 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2643
Richard Smith75b67d62012-03-08 01:34:56 +00002644 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2645 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002646 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2647 llvm::makeArrayRef(&Lit, 1),
2648 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002649}
2650
Ted Kremeneke65b0862012-03-06 20:05:56 +00002651ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2652 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2653 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2654 Context.IntTy, Loc));
2655}
2656
Richard Smith39570d002012-03-08 08:45:32 +00002657static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2658 QualType Ty, SourceLocation Loc) {
2659 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2660
2661 using llvm::APFloat;
2662 APFloat Val(Format);
2663
2664 APFloat::opStatus result = Literal.GetFloatValue(Val);
2665
2666 // Overflow is always an error, but underflow is only an error if
2667 // we underflowed to zero (APFloat reports denormals as underflow).
2668 if ((result & APFloat::opOverflow) ||
2669 ((result & APFloat::opUnderflow) && Val.isZero())) {
2670 unsigned diagnostic;
2671 SmallString<20> buffer;
2672 if (result & APFloat::opOverflow) {
2673 diagnostic = diag::warn_float_overflow;
2674 APFloat::getLargest(Format).toString(buffer);
2675 } else {
2676 diagnostic = diag::warn_float_underflow;
2677 APFloat::getSmallest(Format).toString(buffer);
2678 }
2679
2680 S.Diag(Loc, diagnostic)
2681 << Ty
2682 << StringRef(buffer.data(), buffer.size());
2683 }
2684
2685 bool isExact = (result == APFloat::opOK);
2686 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2687}
2688
Richard Smithbcc22fc2012-03-09 08:00:36 +00002689ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002690 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002691 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002692 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002693 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002694 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002695 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002696
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002697 SmallString<128> SpellingBuffer;
2698 // NumericLiteralParser wants to overread by one character. Add padding to
2699 // the buffer in case the token is copied to the buffer. If getSpelling()
2700 // returns a StringRef to the memory buffer, it should have a null char at
2701 // the EOF, so it is also safe.
2702 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002703
Chris Lattner67ca9252007-05-21 01:08:44 +00002704 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002705 bool Invalid = false;
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002706 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002707 if (Invalid)
2708 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002709
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002710 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002711 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002712 return ExprError();
2713
Richard Smith39570d002012-03-08 08:45:32 +00002714 if (Literal.hasUDSuffix()) {
2715 // We're building a user-defined literal.
2716 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2717 SourceLocation UDSuffixLoc =
2718 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2719
Richard Smithbcc22fc2012-03-09 08:00:36 +00002720 // Make sure we're allowed user-defined literals here.
2721 if (!UDLScope)
2722 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002723
Richard Smithbcc22fc2012-03-09 08:00:36 +00002724 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002725 if (Literal.isFloatingLiteral()) {
2726 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2727 // long double, the literal is treated as a call of the form
2728 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002729 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002730 } else {
2731 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2732 // unsigned long long, the literal is treated as a call of the form
2733 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002734 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002735 }
2736
Richard Smithbcc22fc2012-03-09 08:00:36 +00002737 DeclarationName OpName =
2738 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2739 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2740 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2741
2742 // Perform literal operator lookup to determine if we're building a raw
2743 // literal or a cooked one.
2744 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2745 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2746 /*AllowRawAndTemplate*/true)) {
2747 case LOLR_Error:
2748 return ExprError();
2749
2750 case LOLR_Cooked: {
2751 Expr *Lit;
2752 if (Literal.isFloatingLiteral()) {
2753 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2754 } else {
2755 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2756 if (Literal.GetIntegerValue(ResultVal))
2757 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2758 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2759 Tok.getLocation());
2760 }
2761 return BuildLiteralOperatorCall(R, OpNameInfo,
2762 llvm::makeArrayRef(&Lit, 1),
2763 Tok.getLocation());
2764 }
2765
2766 case LOLR_Raw: {
2767 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2768 // literal is treated as a call of the form
2769 // operator "" X ("n")
2770 SourceLocation TokLoc = Tok.getLocation();
2771 unsigned Length = Literal.getUDSuffixOffset();
2772 QualType StrTy = Context.getConstantArrayType(
2773 Context.CharTy, llvm::APInt(32, Length + 1),
2774 ArrayType::Normal, 0);
2775 Expr *Lit = StringLiteral::Create(
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002776 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smithbcc22fc2012-03-09 08:00:36 +00002777 /*Pascal*/false, StrTy, &TokLoc, 1);
2778 return BuildLiteralOperatorCall(R, OpNameInfo,
2779 llvm::makeArrayRef(&Lit, 1), TokLoc);
2780 }
2781
2782 case LOLR_Template:
2783 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2784 // template), L is treated as a call fo the form
2785 // operator "" X <'c1', 'c2', ... 'ck'>()
2786 // where n is the source character sequence c1 c2 ... ck.
2787 TemplateArgumentListInfo ExplicitArgs;
2788 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2789 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2790 llvm::APSInt Value(CharBits, CharIsUnsigned);
2791 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +00002792 Value = TokSpelling[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002793 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002794 TemplateArgumentLocInfo ArgInfo;
2795 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2796 }
2797 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2798 Tok.getLocation(), &ExplicitArgs);
2799 }
2800
2801 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002802 }
2803
Chris Lattner1c20a172007-08-26 03:42:43 +00002804 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002805
Chris Lattner1c20a172007-08-26 03:42:43 +00002806 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002807 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002808 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002809 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002810 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002811 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002812 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002813 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002814
Richard Smith39570d002012-03-08 08:45:32 +00002815 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002816
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002817 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002818 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002819 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002820 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002821 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002822 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002823 }
2824 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002825 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002826 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002827 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002828 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002829
Dmitri Gribenko1cd23052012-09-24 18:19:21 +00002830 // 'long long' is a C99 or C++11 feature.
2831 if (!getLangOpts().C99 && Literal.isLongLong) {
2832 if (getLangOpts().CPlusPlus)
2833 Diag(Tok.getLocation(),
2834 getLangOpts().CPlusPlus0x ?
2835 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2836 else
2837 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2838 }
Neil Boothac582c52007-08-29 22:00:19 +00002839
Chris Lattner67ca9252007-05-21 01:08:44 +00002840 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002841 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2842 // The microsoft literal suffix extensions support 128-bit literals, which
2843 // may be wider than [u]intmax_t.
Richard Smithe6a56db2012-11-29 05:41:51 +00002844 // FIXME: Actually, they don't. We seem to have accidentally invented the
2845 // i128 suffix.
2846 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2847 PP.getTargetInfo().hasInt128Type())
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002848 MaxWidth = 128;
2849 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002850
Chris Lattner67ca9252007-05-21 01:08:44 +00002851 if (Literal.GetIntegerValue(ResultVal)) {
2852 // If this value didn't fit into uintmax_t, warn and force to ull.
2853 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002854 Ty = Context.UnsignedLongLongTy;
2855 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002856 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002857 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002858 // If this value fits into a ULL, try to figure out what else it fits into
2859 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002860
Chris Lattner67ca9252007-05-21 01:08:44 +00002861 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2862 // be an unsigned int.
2863 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2864
2865 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002866 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002867 if (!Literal.isLong && !Literal.isLongLong) {
2868 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002869 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002870
Chris Lattner67ca9252007-05-21 01:08:44 +00002871 // Does it fit in a unsigned int?
2872 if (ResultVal.isIntN(IntSize)) {
2873 // Does it fit in a signed int?
2874 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002875 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002876 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002877 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002878 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002879 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002880 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002881
Chris Lattner67ca9252007-05-21 01:08:44 +00002882 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002883 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002884 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002885
Chris Lattner67ca9252007-05-21 01:08:44 +00002886 // Does it fit in a unsigned long?
2887 if (ResultVal.isIntN(LongSize)) {
2888 // Does it fit in a signed long?
2889 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002890 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002891 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002892 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002893 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002894 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002895 }
2896
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002897 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002898 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002899 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002900
Chris Lattner67ca9252007-05-21 01:08:44 +00002901 // Does it fit in a unsigned long long?
2902 if (ResultVal.isIntN(LongLongSize)) {
2903 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002904 // To be compatible with MSVC, hex integer literals ending with the
2905 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002906 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002907 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002908 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002909 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002910 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002911 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002912 }
2913 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002914
2915 // If it doesn't fit in unsigned long long, and we're using Microsoft
2916 // extensions, then its a 128-bit integer literal.
Richard Smithe6a56db2012-11-29 05:41:51 +00002917 if (Ty.isNull() && Literal.isMicrosoftInteger &&
2918 PP.getTargetInfo().hasInt128Type()) {
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002919 if (Literal.isUnsigned)
2920 Ty = Context.UnsignedInt128Ty;
2921 else
2922 Ty = Context.Int128Ty;
2923 Width = 128;
2924 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002925
Chris Lattner67ca9252007-05-21 01:08:44 +00002926 // If we still couldn't decide a type, we probably have something that
2927 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002928 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002929 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002930 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002931 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002932 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002933
Chris Lattner55258cf2008-05-09 05:59:00 +00002934 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002935 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002936 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002937 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002938 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002939
Chris Lattner1c20a172007-08-26 03:42:43 +00002940 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2941 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002942 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002943 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002944
2945 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002946}
2947
Richard Trieuba63ce62011-09-09 01:45:06 +00002948ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002949 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002950 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002951}
2952
Chandler Carruth62da79c2011-05-26 08:53:12 +00002953static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2954 SourceLocation Loc,
2955 SourceRange ArgRange) {
2956 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2957 // scalar or vector data type argument..."
2958 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2959 // type (C99 6.2.5p18) or void.
2960 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2961 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2962 << T << ArgRange;
2963 return true;
2964 }
2965
2966 assert((T->isVoidType() || !T->isIncompleteType()) &&
2967 "Scalar types should always be complete");
2968 return false;
2969}
2970
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002971static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2972 SourceLocation Loc,
2973 SourceRange ArgRange,
2974 UnaryExprOrTypeTrait TraitKind) {
2975 // C99 6.5.3.4p1:
2976 if (T->isFunctionType()) {
2977 // alignof(function) is allowed as an extension.
2978 if (TraitKind == UETT_SizeOf)
2979 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2980 return false;
2981 }
2982
2983 // Allow sizeof(void)/alignof(void) as an extension.
2984 if (T->isVoidType()) {
2985 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2986 return false;
2987 }
2988
2989 return true;
2990}
2991
2992static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2993 SourceLocation Loc,
2994 SourceRange ArgRange,
2995 UnaryExprOrTypeTrait TraitKind) {
John McCallf2538342012-07-31 05:14:30 +00002996 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2997 // runtime doesn't allow it.
2998 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002999 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3000 << T << (TraitKind == UETT_SizeOf)
3001 << ArgRange;
3002 return true;
3003 }
3004
3005 return false;
3006}
3007
Chandler Carruth14502c22011-05-26 08:53:10 +00003008/// \brief Check the constrains on expression operands to unary type expression
3009/// and type traits.
3010///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003011/// Completes any types necessary and validates the constraints on the operand
3012/// expression. The logic mostly mirrors the type-based overload, but may modify
3013/// the expression as it completes the type for that expression through template
3014/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00003015bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00003016 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003017 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00003018
3019 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3020 // the result is the size of the referenced type."
3021 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3022 // result shall be the alignment of the referenced type."
3023 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3024 ExprTy = Ref->getPointeeType();
3025
3026 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003027 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3028 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00003029
3030 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003031 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3032 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003033 return false;
3034
Richard Trieuba63ce62011-09-09 01:45:06 +00003035 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003036 diag::err_sizeof_alignof_incomplete_type,
3037 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003038 return true;
3039
3040 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00003041 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00003042 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3043 ExprTy = Ref->getPointeeType();
3044
Richard Trieuba63ce62011-09-09 01:45:06 +00003045 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3046 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00003047 return true;
3048
Nico Weber0870deb2011-06-15 02:47:03 +00003049 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003050 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00003051 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3052 QualType OType = PVD->getOriginalType();
3053 QualType Type = PVD->getType();
3054 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003055 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00003056 << Type << OType;
3057 Diag(PVD->getLocation(), diag::note_declared_at);
3058 }
3059 }
3060 }
3061 }
3062
Chandler Carruth7c430c02011-05-27 01:33:31 +00003063 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003064}
3065
3066/// \brief Check the constraints on operands to unary expression and type
3067/// traits.
3068///
3069/// This will complete any types necessary, and validate the various constraints
3070/// on those operands.
3071///
Steve Naroff71b59a92007-06-04 22:22:31 +00003072/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003073/// C99 6.3.2.1p[2-4] all state:
3074/// Except when it is the operand of the sizeof operator ...
3075///
3076/// C++ [expr.sizeof]p4
3077/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3078/// standard conversions are not applied to the operand of sizeof.
3079///
3080/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00003081bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003082 SourceLocation OpLoc,
3083 SourceRange ExprRange,
3084 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003085 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003086 return false;
3087
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003088 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3089 // the result is the size of the referenced type."
3090 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3091 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00003092 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3093 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003094
Chandler Carruth62da79c2011-05-26 08:53:12 +00003095 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00003096 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003097
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003098 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00003099 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003100 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003101 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003102
Richard Trieuba63ce62011-09-09 01:45:06 +00003103 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003104 diag::err_sizeof_alignof_incomplete_type,
3105 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003106 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003107
Richard Trieuba63ce62011-09-09 01:45:06 +00003108 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003109 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003110 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003111
Chris Lattner62975a72009-04-24 00:30:45 +00003112 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003113}
3114
Chandler Carruth14502c22011-05-26 08:53:10 +00003115static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003116 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003117
Mike Stump11289f42009-09-09 15:08:12 +00003118 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003119 if (isa<DeclRefExpr>(E))
3120 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003121
3122 // Cannot know anything else if the expression is dependent.
3123 if (E->isTypeDependent())
3124 return false;
3125
Douglas Gregor71235ec2009-05-02 02:18:30 +00003126 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003127 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3128 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003129 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003130 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003131
3132 // Alignment of a field access is always okay, so long as it isn't a
3133 // bit-field.
3134 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003135 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003136 return false;
3137
Chandler Carruth14502c22011-05-26 08:53:10 +00003138 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003139}
3140
Chandler Carruth14502c22011-05-26 08:53:10 +00003141bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003142 E = E->IgnoreParens();
3143
3144 // Cannot know anything else if the expression is dependent.
3145 if (E->isTypeDependent())
3146 return false;
3147
Chandler Carruth14502c22011-05-26 08:53:10 +00003148 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003149}
3150
Douglas Gregor0950e412009-03-13 21:01:28 +00003151/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003152ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003153Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3154 SourceLocation OpLoc,
3155 UnaryExprOrTypeTrait ExprKind,
3156 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003157 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003158 return ExprError();
3159
John McCallbcd03502009-12-07 02:54:59 +00003160 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003161
Douglas Gregor0950e412009-03-13 21:01:28 +00003162 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003163 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003164 return ExprError();
3165
3166 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003167 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3168 Context.getSizeType(),
3169 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003170}
3171
3172/// \brief Build a sizeof or alignof expression given an expression
3173/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003174ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003175Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3176 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003177 ExprResult PE = CheckPlaceholderExpr(E);
3178 if (PE.isInvalid())
3179 return ExprError();
3180
3181 E = PE.get();
3182
Douglas Gregor0950e412009-03-13 21:01:28 +00003183 // Verify that the operand is valid.
3184 bool isInvalid = false;
3185 if (E->isTypeDependent()) {
3186 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003187 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003188 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003189 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003190 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003191 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003192 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003193 isInvalid = true;
3194 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003195 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003196 }
3197
3198 if (isInvalid)
3199 return ExprError();
3200
Eli Friedmane0afc982012-01-21 01:01:51 +00003201 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Kramerd81108f2012-11-14 15:08:31 +00003202 PE = TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +00003203 if (PE.isInvalid()) return ExprError();
3204 E = PE.take();
3205 }
3206
Douglas Gregor0950e412009-03-13 21:01:28 +00003207 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003208 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003209 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003210 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003211}
3212
Peter Collingbournee190dee2011-03-11 19:24:49 +00003213/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3214/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003215/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003216ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003217Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003218 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003219 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003220 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003221 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003222
Richard Trieuba63ce62011-09-09 01:45:06 +00003223 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003224 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003225 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003226 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003227 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003228
Douglas Gregor0950e412009-03-13 21:01:28 +00003229 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003230 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003231 return Result;
Chris Lattnere168f762006-11-10 05:29:30 +00003232}
3233
John Wiegley01296292011-04-08 18:41:53 +00003234static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003235 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003236 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003237 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003238
John McCall34376a62010-12-04 03:47:34 +00003239 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003240 if (V.get()->getObjectKind() != OK_Ordinary) {
3241 V = S.DefaultLvalueConversion(V.take());
3242 if (V.isInvalid())
3243 return QualType();
3244 }
John McCall34376a62010-12-04 03:47:34 +00003245
Chris Lattnere267f5d2007-08-26 05:39:26 +00003246 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003247 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003248 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003249
Chris Lattnere267f5d2007-08-26 05:39:26 +00003250 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003251 if (V.get()->getType()->isArithmeticType())
3252 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003253
John McCall36226622010-10-12 02:09:17 +00003254 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003255 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003256 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003257 if (PR.get() != V.get()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003258 V = PR;
Richard Trieuba63ce62011-09-09 01:45:06 +00003259 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003260 }
3261
Chris Lattnere267f5d2007-08-26 05:39:26 +00003262 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003263 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003264 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003265 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003266}
3267
3268
Chris Lattnere168f762006-11-10 05:29:30 +00003269
John McCalldadc5752010-08-24 06:29:42 +00003270ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003271Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003272 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003273 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003274 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003275 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003276 case tok::plusplus: Opc = UO_PostInc; break;
3277 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003278 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003279
Sebastian Redla9351792012-02-11 23:51:47 +00003280 // Since this might is a postfix expression, get rid of ParenListExprs.
3281 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3282 if (Result.isInvalid()) return ExprError();
3283 Input = Result.take();
3284
John McCallb268a282010-08-23 23:25:46 +00003285 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003286}
3287
John McCallf2538342012-07-31 05:14:30 +00003288/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3289///
3290/// \return true on error
3291static bool checkArithmeticOnObjCPointer(Sema &S,
3292 SourceLocation opLoc,
3293 Expr *op) {
3294 assert(op->getType()->isObjCObjectPointerType());
3295 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3296 return false;
3297
3298 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3299 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3300 << op->getSourceRange();
3301 return true;
3302}
3303
John McCalldadc5752010-08-24 06:29:42 +00003304ExprResult
John McCallb268a282010-08-23 23:25:46 +00003305Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3306 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003307 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003308 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003309 if (Result.isInvalid()) return ExprError();
3310 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003311
John McCallb268a282010-08-23 23:25:46 +00003312 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003313
David Blaikiebbafb8a2012-03-11 07:00:24 +00003314 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003315 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003316 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003317 Context.DependentTy,
3318 VK_LValue, OK_Ordinary,
3319 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003320 }
3321
David Blaikiebbafb8a2012-03-11 07:00:24 +00003322 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003323 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003324 LHSExp->getType()->isEnumeralType() ||
3325 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003326 RHSExp->getType()->isEnumeralType()) &&
3327 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003328 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003329 }
3330
John McCallb268a282010-08-23 23:25:46 +00003331 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003332}
3333
John McCalldadc5752010-08-24 06:29:42 +00003334ExprResult
John McCallb268a282010-08-23 23:25:46 +00003335Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003336 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003337 Expr *LHSExp = Base;
3338 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003339
Chris Lattner36d572b2007-07-16 00:14:47 +00003340 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003341 if (!LHSExp->getType()->getAs<VectorType>()) {
3342 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3343 if (Result.isInvalid())
3344 return ExprError();
3345 LHSExp = Result.take();
3346 }
3347 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3348 if (Result.isInvalid())
3349 return ExprError();
3350 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003351
Chris Lattner36d572b2007-07-16 00:14:47 +00003352 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003353 ExprValueKind VK = VK_LValue;
3354 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003355
Steve Naroffc1aadb12007-03-28 21:49:40 +00003356 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003357 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003358 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003359 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003360 Expr *BaseExpr, *IndexExpr;
3361 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003362 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3363 BaseExpr = LHSExp;
3364 IndexExpr = RHSExp;
3365 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003366 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003367 BaseExpr = LHSExp;
3368 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003369 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003370 } else if (const ObjCObjectPointerType *PTy =
John McCallf2538342012-07-31 05:14:30 +00003371 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003372 BaseExpr = LHSExp;
3373 IndexExpr = RHSExp;
John McCallf2538342012-07-31 05:14:30 +00003374
3375 // Use custom logic if this should be the pseudo-object subscript
3376 // expression.
3377 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3378 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3379
Steve Naroff7cae42b2009-07-10 23:34:53 +00003380 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003381 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3382 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3383 << ResultType << BaseExpr->getSourceRange();
3384 return ExprError();
3385 }
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003386 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3387 // Handle the uncommon case of "123[Ptr]".
3388 BaseExpr = RHSExp;
3389 IndexExpr = LHSExp;
3390 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003391 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003392 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003393 // Handle the uncommon case of "123[Ptr]".
3394 BaseExpr = RHSExp;
3395 IndexExpr = LHSExp;
3396 ResultType = PTy->getPointeeType();
John McCallf2538342012-07-31 05:14:30 +00003397 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3398 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3399 << ResultType << BaseExpr->getSourceRange();
3400 return ExprError();
3401 }
John McCall9dd450b2009-09-21 23:43:11 +00003402 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003403 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003404 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003405 VK = LHSExp->getValueKind();
3406 if (VK != VK_RValue)
3407 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003408
Chris Lattner36d572b2007-07-16 00:14:47 +00003409 // FIXME: need to deal with const...
3410 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003411 } else if (LHSTy->isArrayType()) {
3412 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003413 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003414 // wasn't promoted because of the C90 rule that doesn't
3415 // allow promoting non-lvalue arrays. Warn, then
3416 // force the promotion here.
3417 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3418 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003419 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3420 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003421 LHSTy = LHSExp->getType();
3422
3423 BaseExpr = LHSExp;
3424 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003425 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003426 } else if (RHSTy->isArrayType()) {
3427 // Same as previous, except for 123[f().a] case
3428 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3429 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003430 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3431 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003432 RHSTy = RHSExp->getType();
3433
3434 BaseExpr = RHSExp;
3435 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003436 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003437 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003438 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3439 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003440 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003441 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003442 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003443 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3444 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003445
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003446 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003447 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3448 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003449 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3450
Douglas Gregorac1fb652009-03-24 19:52:54 +00003451 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003452 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3453 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003454 // incomplete types are not object types.
3455 if (ResultType->isFunctionType()) {
3456 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3457 << ResultType << BaseExpr->getSourceRange();
3458 return ExprError();
3459 }
Mike Stump11289f42009-09-09 15:08:12 +00003460
David Blaikiebbafb8a2012-03-11 07:00:24 +00003461 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003462 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003463 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3464 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003465
3466 // C forbids expressions of unqualified void type from being l-values.
3467 // See IsCForbiddenLValueType.
3468 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003469 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003470 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003471 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003472 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003473
John McCall4bc41ae2010-11-18 19:01:18 +00003474 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003475 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003476
Mike Stump4e1f26a2009-02-19 03:04:26 +00003477 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003478 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003479}
3480
John McCalldadc5752010-08-24 06:29:42 +00003481ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003482 FunctionDecl *FD,
3483 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003484 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003485 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003486 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003487 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003488 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003489 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003490 return ExprError();
3491 }
3492
3493 if (Param->hasUninstantiatedDefaultArg()) {
3494 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003495
Richard Smith505df232012-07-22 23:45:10 +00003496 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3497 Param);
3498
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003499 // Instantiate the expression.
3500 MultiLevelTemplateArgumentList ArgList
3501 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003502
Nico Weber44887f62010-11-29 18:19:25 +00003503 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003504 = ArgList.getInnermost();
Richard Smith80934652012-07-16 01:09:10 +00003505 InstantiatingTemplate Inst(*this, CallLoc, Param,
3506 ArrayRef<TemplateArgument>(Innermost.first,
3507 Innermost.second));
Richard Smith8a874c92012-07-08 02:38:24 +00003508 if (Inst)
3509 return ExprError();
Anders Carlsson355933d2009-08-25 03:49:14 +00003510
Nico Weber44887f62010-11-29 18:19:25 +00003511 ExprResult Result;
3512 {
3513 // C++ [dcl.fct.default]p5:
3514 // The names in the [default argument] expression are bound, and
3515 // the semantic constraints are checked, at the point where the
3516 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003517 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003518 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003519 Result = SubstExpr(UninstExpr, ArgList);
3520 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003521 if (Result.isInvalid())
3522 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003524 // Check the expression as an initializer for the parameter.
3525 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003526 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003527 InitializationKind Kind
3528 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003529 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003530 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003531
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003532 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003533 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003534 if (Result.isInvalid())
3535 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003536
David Blaikief68e8092012-04-30 18:21:31 +00003537 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003538 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003539 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003540 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003541 }
3542
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003543 // If the default expression creates temporaries, we need to
3544 // push them to the current stack of expression temporaries so they'll
3545 // be properly destroyed.
3546 // FIXME: We should really be rebuilding the default argument with new
3547 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003548 // We don't need to do that with block decls, though, because
3549 // blocks in default argument expression can never capture anything.
3550 if (isa<ExprWithCleanups>(Param->getInit())) {
3551 // Set the "needs cleanups" bit regardless of whether there are
3552 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003553 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003554
3555 // Append all the objects to the cleanup list. Right now, this
3556 // should always be a no-op, because blocks in default argument
3557 // expressions should never be able to capture anything.
3558 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3559 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003560 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003561
3562 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003563 // Just mark all of the declarations in this potentially-evaluated expression
3564 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003565 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3566 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003567 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003568}
3569
Richard Smith55ce3522012-06-25 20:30:08 +00003570
3571Sema::VariadicCallType
3572Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3573 Expr *Fn) {
3574 if (Proto && Proto->isVariadic()) {
3575 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3576 return VariadicConstructor;
3577 else if (Fn && Fn->getType()->isBlockPointerType())
3578 return VariadicBlock;
3579 else if (FDecl) {
3580 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3581 if (Method->isInstance())
3582 return VariadicMethod;
3583 }
3584 return VariadicFunction;
3585 }
3586 return VariadicDoesNotApply;
3587}
3588
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003589/// ConvertArgumentsForCall - Converts the arguments specified in
3590/// Args/NumArgs to the parameter types of the function FDecl with
3591/// function prototype Proto. Call is the call expression itself, and
3592/// Fn is the function expression. For a C++ member function, this
3593/// routine does not attempt to convert the object argument. Returns
3594/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003595bool
3596Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003597 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003598 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003599 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003600 SourceLocation RParenLoc,
3601 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003602 // Bail out early if calling a builtin with custom typechecking.
3603 // We don't need to do this in the
3604 if (FDecl)
3605 if (unsigned ID = FDecl->getBuiltinID())
3606 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3607 return false;
3608
Mike Stump4e1f26a2009-02-19 03:04:26 +00003609 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003610 // assignment, to the types of the corresponding parameter, ...
3611 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003612 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003613 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003614 unsigned FnKind = Fn->getType()->isBlockPointerType()
3615 ? 1 /* block */
3616 : (IsExecConfig ? 3 /* kernel function (exec config) */
3617 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003618
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003619 // If too few arguments are available (and we don't have default
3620 // arguments for the remaining parameters), don't make the call.
3621 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003622 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003623 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3624 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3625 ? diag::err_typecheck_call_too_few_args_one
3626 : diag::err_typecheck_call_too_few_args_at_least_one)
3627 << FnKind
3628 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3629 else
3630 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3631 ? diag::err_typecheck_call_too_few_args
3632 : diag::err_typecheck_call_too_few_args_at_least)
3633 << FnKind
3634 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003635
3636 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003637 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003638 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3639 << FDecl;
3640
3641 return true;
3642 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003643 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003644 }
3645
3646 // If too many are passed and not variadic, error on the extras and drop
3647 // them.
3648 if (NumArgs > NumArgsInProto) {
3649 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003650 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3651 Diag(Args[NumArgsInProto]->getLocStart(),
3652 MinArgs == NumArgsInProto
3653 ? diag::err_typecheck_call_too_many_args_one
3654 : diag::err_typecheck_call_too_many_args_at_most_one)
3655 << FnKind
3656 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3657 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3658 Args[NumArgs-1]->getLocEnd());
3659 else
3660 Diag(Args[NumArgsInProto]->getLocStart(),
3661 MinArgs == NumArgsInProto
3662 ? diag::err_typecheck_call_too_many_args
3663 : diag::err_typecheck_call_too_many_args_at_most)
3664 << FnKind
3665 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3666 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3667 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003668
3669 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003670 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003671 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3672 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003673
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003674 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003675 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003676 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003677 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003678 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003679 SmallVector<Expr *, 8> AllArgs;
Richard Smith55ce3522012-06-25 20:30:08 +00003680 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3681
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003682 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003683 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003684 if (Invalid)
3685 return true;
3686 unsigned TotalNumArgs = AllArgs.size();
3687 for (unsigned i = 0; i < TotalNumArgs; ++i)
3688 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003689
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003690 return false;
3691}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003692
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003693bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3694 FunctionDecl *FDecl,
3695 const FunctionProtoType *Proto,
3696 unsigned FirstProtoArg,
3697 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003698 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003699 VariadicCallType CallType,
3700 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003701 unsigned NumArgsInProto = Proto->getNumArgs();
3702 unsigned NumArgsToCheck = NumArgs;
3703 bool Invalid = false;
3704 if (NumArgs != NumArgsInProto)
3705 // Use default arguments for missing arguments
3706 NumArgsToCheck = NumArgsInProto;
3707 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003708 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003709 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003710 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003711
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003712 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003713 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003714 if (ArgIx < NumArgs) {
3715 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003716
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003717 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003718 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003719 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003720 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003721
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003722 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003723 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003724 if (FDecl && i < FDecl->getNumParams())
3725 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003726
John McCall4124c492011-10-17 18:40:02 +00003727 // Strip the unbridged-cast placeholder expression off, if applicable.
3728 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3729 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3730 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3731 Arg = stripARCUnbridgedCast(Arg);
3732
Rafael Espindola8778c282012-11-29 16:09:03 +00003733 InitializedEntity Entity = Param ?
3734 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3735 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3736 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003737 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003738 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003739 Owned(Arg),
3740 /*TopLevelOfInitList=*/false,
3741 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003742 if (ArgE.isInvalid())
3743 return true;
3744
3745 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003746 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003747 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003748
John McCalldadc5752010-08-24 06:29:42 +00003749 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003750 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003751 if (ArgExpr.isInvalid())
3752 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003753
Anders Carlsson355933d2009-08-25 03:49:14 +00003754 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003755 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003756
3757 // Check for array bounds violations for each argument to the call. This
3758 // check only triggers warnings when the argument isn't a more complex Expr
3759 // with its own checking, such as a BinaryOperator.
3760 CheckArrayAccess(Arg);
3761
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003762 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3763 CheckStaticArrayArgument(CallLoc, Param, Arg);
3764
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003765 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003766 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003767
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003768 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003769 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003770 // Assume that extern "C" functions with variadic arguments that
3771 // return __unknown_anytype aren't *really* variadic.
3772 if (Proto->getResultType() == Context.UnknownAnyTy &&
3773 FDecl && FDecl->isExternC()) {
3774 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3775 ExprResult arg;
3776 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3777 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3778 else
3779 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3780 Invalid |= arg.isInvalid();
3781 AllArgs.push_back(arg.take());
3782 }
3783
3784 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3785 } else {
3786 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003787 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3788 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003789 Invalid |= Arg.isInvalid();
3790 AllArgs.push_back(Arg.take());
3791 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003792 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003793
3794 // Check for array bounds violations.
3795 for (unsigned i = ArgIx; i != NumArgs; ++i)
3796 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003797 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003798 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003799}
3800
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003801static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3802 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3803 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3804 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3805 << ATL->getLocalSourceRange();
3806}
3807
3808/// CheckStaticArrayArgument - If the given argument corresponds to a static
3809/// array parameter, check that it is non-null, and that if it is formed by
3810/// array-to-pointer decay, the underlying array is sufficiently large.
3811///
3812/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3813/// array type derivation, then for each call to the function, the value of the
3814/// corresponding actual argument shall provide access to the first element of
3815/// an array with at least as many elements as specified by the size expression.
3816void
3817Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3818 ParmVarDecl *Param,
3819 const Expr *ArgExpr) {
3820 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003821 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003822 return;
3823
3824 QualType OrigTy = Param->getOriginalType();
3825
3826 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3827 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3828 return;
3829
3830 if (ArgExpr->isNullPointerConstant(Context,
3831 Expr::NPC_NeverValueDependent)) {
3832 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3833 DiagnoseCalleeStaticArrayParam(*this, Param);
3834 return;
3835 }
3836
3837 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3838 if (!CAT)
3839 return;
3840
3841 const ConstantArrayType *ArgCAT =
3842 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3843 if (!ArgCAT)
3844 return;
3845
3846 if (ArgCAT->getSize().ult(CAT->getSize())) {
3847 Diag(CallLoc, diag::warn_static_array_too_small)
3848 << ArgExpr->getSourceRange()
3849 << (unsigned) ArgCAT->getSize().getZExtValue()
3850 << (unsigned) CAT->getSize().getZExtValue();
3851 DiagnoseCalleeStaticArrayParam(*this, Param);
3852 }
3853}
3854
John McCall2979fe02011-04-12 00:42:48 +00003855/// Given a function expression of unknown-any type, try to rebuild it
3856/// to have a function type.
3857static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3858
Steve Naroff83895f72007-09-16 03:34:24 +00003859/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003860/// This provides the location of the left/right parens and a list of comma
3861/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003862ExprResult
John McCallb268a282010-08-23 23:25:46 +00003863Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003864 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003865 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003866 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003867 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003868 if (Result.isInvalid()) return ExprError();
3869 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003870
David Blaikiebbafb8a2012-03-11 07:00:24 +00003871 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003872 // If this is a pseudo-destructor expression, build the call immediately.
3873 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003874 if (!ArgExprs.empty()) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003875 // Pseudo-destructor calls should not have any arguments.
3876 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003877 << FixItHint::CreateRemoval(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003878 SourceRange(ArgExprs[0]->getLocStart(),
3879 ArgExprs.back()->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003880 }
Mike Stump11289f42009-09-09 15:08:12 +00003881
Benjamin Kramerc215e762012-08-24 11:54:20 +00003882 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3883 Context.VoidTy, VK_RValue,
3884 RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003885 }
Mike Stump11289f42009-09-09 15:08:12 +00003886
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003887 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003888 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003889 // FIXME: Will need to cache the results of name lookup (including ADL) in
3890 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003891 bool Dependent = false;
3892 if (Fn->isTypeDependent())
3893 Dependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003894 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003895 Dependent = true;
3896
Peter Collingbourne41f85462011-02-09 21:07:24 +00003897 if (Dependent) {
3898 if (ExecConfig) {
3899 return Owned(new (Context) CUDAKernelCallExpr(
Benjamin Kramerc215e762012-08-24 11:54:20 +00003900 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003901 Context.DependentTy, VK_RValue, RParenLoc));
3902 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003903 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003904 Context.DependentTy, VK_RValue,
3905 RParenLoc));
3906 }
3907 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003908
3909 // Determine whether this is a call to an object (C++ [over.call.object]).
3910 if (Fn->getType()->isRecordType())
Benjamin Kramerc215e762012-08-24 11:54:20 +00003911 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3912 ArgExprs.data(),
3913 ArgExprs.size(), RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003914
John McCall2979fe02011-04-12 00:42:48 +00003915 if (Fn->getType() == Context.UnknownAnyTy) {
3916 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3917 if (result.isInvalid()) return ExprError();
3918 Fn = result.take();
3919 }
3920
John McCall0009fcc2011-04-26 20:42:42 +00003921 if (Fn->getType() == Context.BoundMemberTy) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003922 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3923 ArgExprs.size(), RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003924 }
John McCall0009fcc2011-04-26 20:42:42 +00003925 }
John McCall10eae182009-11-30 22:42:35 +00003926
John McCall0009fcc2011-04-26 20:42:42 +00003927 // Check for overloaded calls. This can happen even in C due to extensions.
3928 if (Fn->getType() == Context.OverloadTy) {
3929 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3930
Douglas Gregorcda22702011-10-13 18:10:35 +00003931 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003932 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003933 OverloadExpr *ovl = find.Expression;
3934 if (isa<UnresolvedLookupExpr>(ovl)) {
3935 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Benjamin Kramerc215e762012-08-24 11:54:20 +00003936 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3937 ArgExprs.size(), RParenLoc, ExecConfig);
John McCall0009fcc2011-04-26 20:42:42 +00003938 } else {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003939 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3940 ArgExprs.size(), RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003941 }
3942 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003943 }
3944
Douglas Gregore254f902009-02-04 00:32:51 +00003945 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003946 if (Fn->getType() == Context.UnknownAnyTy) {
3947 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3948 if (result.isInvalid()) return ExprError();
3949 Fn = result.take();
3950 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003951
Eli Friedmane14b1992009-12-26 03:35:45 +00003952 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003953
John McCall57500772009-12-16 12:17:52 +00003954 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003955 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3956 if (UnOp->getOpcode() == UO_AddrOf)
3957 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3958
John McCall57500772009-12-16 12:17:52 +00003959 if (isa<DeclRefExpr>(NakedFn))
3960 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003961 else if (isa<MemberExpr>(NakedFn))
3962 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003963
Benjamin Kramerc215e762012-08-24 11:54:20 +00003964 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3965 ArgExprs.size(), RParenLoc, ExecConfig,
3966 IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003967}
3968
3969ExprResult
3970Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003971 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003972 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3973 if (!ConfigDecl)
3974 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3975 << "cudaConfigureCall");
3976 QualType ConfigQTy = ConfigDecl->getType();
3977
3978 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003979 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003980 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003981
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003982 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3983 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003984}
3985
Tanya Lattner55808c12011-06-04 00:47:47 +00003986/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3987///
3988/// __builtin_astype( value, dst type )
3989///
Richard Trieuba63ce62011-09-09 01:45:06 +00003990ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003991 SourceLocation BuiltinLoc,
3992 SourceLocation RParenLoc) {
3993 ExprValueKind VK = VK_RValue;
3994 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003995 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3996 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003997 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3998 return ExprError(Diag(BuiltinLoc,
3999 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00004000 << DstTy
4001 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00004002 << E->getSourceRange());
4003 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00004004 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00004005}
4006
John McCall57500772009-12-16 12:17:52 +00004007/// BuildResolvedCallExpr - Build a call to a resolved expression,
4008/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004009/// unary-convert to an expression of function-pointer or
4010/// block-pointer type.
4011///
4012/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004013ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004014Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4015 SourceLocation LParenLoc,
4016 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004017 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004018 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00004019 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedman34866c72012-08-31 00:14:07 +00004020 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCall2d74de92009-12-01 22:10:20 +00004021
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004022 // Promote the function operand.
Eli Friedman34866c72012-08-31 00:14:07 +00004023 // We special-case function promotion here because we only allow promoting
4024 // builtin functions to function pointers in the callee of a call.
4025 ExprResult Result;
4026 if (BuiltinID &&
4027 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4028 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4029 CK_BuiltinFnToFnPtr).take();
4030 } else {
4031 Result = UsualUnaryConversions(Fn);
4032 }
John Wiegley01296292011-04-08 18:41:53 +00004033 if (Result.isInvalid())
4034 return ExprError();
4035 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004036
Chris Lattner08464942007-12-28 05:29:59 +00004037 // Make the call expr early, before semantic checks. This guarantees cleanup
4038 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004039 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00004040 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00004041 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4042 cast<CallExpr>(Config),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004043 llvm::makeArrayRef(Args,NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00004044 Context.BoolTy,
4045 VK_RValue,
4046 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00004047 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00004048 TheCall = new (Context) CallExpr(Context, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004049 llvm::makeArrayRef(Args, NumArgs),
Peter Collingbourne41f85462011-02-09 21:07:24 +00004050 Context.BoolTy,
4051 VK_RValue,
4052 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004053
John McCallbebede42011-02-26 05:39:39 +00004054 // Bail out early if calling a builtin with custom typechecking.
4055 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4056 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4057
John McCall31996342011-04-07 08:22:57 +00004058 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004059 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004060 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004061 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4062 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004063 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004064 if (FuncT == 0)
4065 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4066 << Fn->getType() << Fn->getSourceRange());
4067 } else if (const BlockPointerType *BPT =
4068 Fn->getType()->getAs<BlockPointerType>()) {
4069 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4070 } else {
John McCall31996342011-04-07 08:22:57 +00004071 // Handle calls to expressions of unknown-any type.
4072 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004073 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004074 if (rewrite.isInvalid()) return ExprError();
4075 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004076 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004077 goto retry;
4078 }
4079
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004080 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4081 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004082 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004083
David Blaikiebbafb8a2012-03-11 07:00:24 +00004084 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004085 if (Config) {
4086 // CUDA: Kernel calls must be to global functions
4087 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4088 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4089 << FDecl->getName() << Fn->getSourceRange());
4090
4091 // CUDA: Kernel function must have 'void' return type
4092 if (!FuncT->getResultType()->isVoidType())
4093 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4094 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00004095 } else {
4096 // CUDA: Calls to global functions must be configured
4097 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4098 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4099 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004100 }
4101 }
4102
Eli Friedman3164fb12009-03-22 22:00:50 +00004103 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004104 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004105 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004106 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004107 return ExprError();
4108
Chris Lattner08464942007-12-28 05:29:59 +00004109 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004110 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004111 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004112
Richard Smith55ce3522012-06-25 20:30:08 +00004113 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4114 if (Proto) {
John McCallb268a282010-08-23 23:25:46 +00004115 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00004116 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004117 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004118 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004119 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004120
Douglas Gregord8e97de2009-04-02 15:37:10 +00004121 if (FDecl) {
4122 // Check if we have too few/too many template arguments, based
4123 // on our knowledge of the function definition.
4124 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004125 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith55ce3522012-06-25 20:30:08 +00004126 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004127 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004128 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4129 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00004130 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00004131
4132 // If the function we're calling isn't a function prototype, but we have
4133 // a function prototype from a prior declaratiom, use that prototype.
4134 if (!FDecl->hasPrototype())
4135 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00004136 }
4137
Steve Naroff0b661582007-08-28 23:30:39 +00004138 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00004139 for (unsigned i = 0; i != NumArgs; i++) {
4140 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00004141
4142 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00004143 InitializedEntity Entity
4144 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00004145 Proto->getArgType(i),
4146 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00004147 ExprResult ArgE = PerformCopyInitialization(Entity,
4148 SourceLocation(),
4149 Owned(Arg));
4150 if (ArgE.isInvalid())
4151 return true;
4152
4153 Arg = ArgE.takeAs<Expr>();
4154
4155 } else {
John Wiegley01296292011-04-08 18:41:53 +00004156 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4157
4158 if (ArgE.isInvalid())
4159 return true;
4160
4161 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00004162 }
4163
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004164 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00004165 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004166 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00004167 return ExprError();
4168
Chris Lattner08464942007-12-28 05:29:59 +00004169 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00004170 }
Steve Naroffae4143e2007-04-26 20:39:23 +00004171 }
Chris Lattner08464942007-12-28 05:29:59 +00004172
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004173 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4174 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004175 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4176 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004177
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00004178 // Check for sentinels
4179 if (NDecl)
4180 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004181
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004182 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004183 if (FDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004184 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004185 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCallbebede42011-02-26 05:39:39 +00004187 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00004188 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004189 } else if (NDecl) {
Richard Smith55ce3522012-06-25 20:30:08 +00004190 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004191 return ExprError();
4192 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004193
John McCallb268a282010-08-23 23:25:46 +00004194 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00004195}
4196
John McCalldadc5752010-08-24 06:29:42 +00004197ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004198Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004199 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004200 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004201 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004202 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004203
4204 TypeSourceInfo *TInfo;
4205 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4206 if (!TInfo)
4207 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4208
John McCallb268a282010-08-23 23:25:46 +00004209 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004210}
4211
John McCalldadc5752010-08-24 06:29:42 +00004212ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004213Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004214 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004215 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004216
Eli Friedman37a186d2008-05-20 05:22:08 +00004217 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004218 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004219 diag::err_illegal_decl_array_incomplete_type,
4220 SourceRange(LParenLoc,
4221 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004222 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004224 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004225 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004226 } else if (!literalType->isDependentType() &&
4227 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004228 diag::err_typecheck_decl_incomplete_type,
4229 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004230 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004231
Douglas Gregor85dabae2009-12-16 01:38:02 +00004232 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004233 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004234 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004235 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004236 SourceRange(LParenLoc, RParenLoc),
4237 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004238 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004239 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4240 &literalType);
Eli Friedmana553d4a2009-12-22 02:35:53 +00004241 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004242 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004243 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004244
Chris Lattner79413952008-12-04 23:50:19 +00004245 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004246 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004247 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004248 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004249 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004250
John McCall7decc9e2010-11-18 06:31:45 +00004251 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004252 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004253
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004254 return MaybeBindToTemporary(
4255 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004256 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004257}
4258
John McCalldadc5752010-08-24 06:29:42 +00004259ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004260Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004261 SourceLocation RBraceLoc) {
John McCall526ab472011-10-25 17:37:35 +00004262 // Immediately handle non-overload placeholders. Overloads can be
4263 // resolved contextually, but everything else here can't.
Benjamin Kramerc215e762012-08-24 11:54:20 +00004264 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4265 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4266 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall526ab472011-10-25 17:37:35 +00004267
4268 // Ignore failures; dropping the entire initializer list because
4269 // of one failure would be terrible for indexing/etc.
4270 if (result.isInvalid()) continue;
4271
Benjamin Kramerc215e762012-08-24 11:54:20 +00004272 InitArgList[I] = result.take();
John McCall526ab472011-10-25 17:37:35 +00004273 }
4274 }
4275
Steve Naroff30d242c2007-09-15 18:49:24 +00004276 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004277 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004278
Benjamin Kramerc215e762012-08-24 11:54:20 +00004279 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4280 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004281 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004282 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004283}
4284
John McCallcd78e802011-09-10 01:16:55 +00004285/// Do an explicit extend of the given block pointer if we're in ARC.
4286static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4287 assert(E.get()->getType()->isBlockPointerType());
4288 assert(E.get()->isRValue());
4289
4290 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004291 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004292
4293 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004294 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004295 /*base path*/ 0, VK_RValue);
4296 S.ExprNeedsCleanups = true;
4297}
4298
4299/// Prepare a conversion of the given expression to an ObjC object
4300/// pointer type.
4301CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4302 QualType type = E.get()->getType();
4303 if (type->isObjCObjectPointerType()) {
4304 return CK_BitCast;
4305 } else if (type->isBlockPointerType()) {
4306 maybeExtendBlockObject(*this, E);
4307 return CK_BlockPointerToObjCPointerCast;
4308 } else {
4309 assert(type->isPointerType());
4310 return CK_CPointerToObjCPointerCast;
4311 }
4312}
4313
John McCalld7646252010-11-14 08:17:51 +00004314/// Prepares for a scalar cast, performing all the necessary stages
4315/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004316CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004317 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4318 // Also, callers should have filtered out the invalid cases with
4319 // pointers. Everything else should be possible.
4320
John Wiegley01296292011-04-08 18:41:53 +00004321 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004322 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004323 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004324
John McCall9320b872011-09-09 05:25:32 +00004325 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004326 case Type::STK_MemberPointer:
4327 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004328
John McCall9320b872011-09-09 05:25:32 +00004329 case Type::STK_CPointer:
4330 case Type::STK_BlockPointer:
4331 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004332 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004333 case Type::STK_CPointer:
4334 return CK_BitCast;
4335 case Type::STK_BlockPointer:
4336 return (SrcKind == Type::STK_BlockPointer
4337 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4338 case Type::STK_ObjCObjectPointer:
4339 if (SrcKind == Type::STK_ObjCObjectPointer)
4340 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004341 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004342 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004343 maybeExtendBlockObject(*this, Src);
4344 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004345 case Type::STK_Bool:
4346 return CK_PointerToBoolean;
4347 case Type::STK_Integral:
4348 return CK_PointerToIntegral;
4349 case Type::STK_Floating:
4350 case Type::STK_FloatingComplex:
4351 case Type::STK_IntegralComplex:
4352 case Type::STK_MemberPointer:
4353 llvm_unreachable("illegal cast from pointer");
4354 }
David Blaikie8a40f702012-01-17 06:56:22 +00004355 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004356
John McCall8cb679e2010-11-15 09:13:47 +00004357 case Type::STK_Bool: // casting from bool is like casting from an integer
4358 case Type::STK_Integral:
4359 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004360 case Type::STK_CPointer:
4361 case Type::STK_ObjCObjectPointer:
4362 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004363 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004364 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004365 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004366 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004367 case Type::STK_Bool:
4368 return CK_IntegralToBoolean;
4369 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004370 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004371 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004372 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004373 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004374 Src = ImpCastExprToType(Src.take(),
4375 DestTy->castAs<ComplexType>()->getElementType(),
4376 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004377 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004378 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004379 Src = ImpCastExprToType(Src.take(),
4380 DestTy->castAs<ComplexType>()->getElementType(),
4381 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004382 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004383 case Type::STK_MemberPointer:
4384 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004385 }
David Blaikie8a40f702012-01-17 06:56:22 +00004386 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004387
John McCall8cb679e2010-11-15 09:13:47 +00004388 case Type::STK_Floating:
4389 switch (DestTy->getScalarTypeKind()) {
4390 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004391 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004392 case Type::STK_Bool:
4393 return CK_FloatingToBoolean;
4394 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004395 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004396 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004397 Src = ImpCastExprToType(Src.take(),
4398 DestTy->castAs<ComplexType>()->getElementType(),
4399 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004400 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004401 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004402 Src = ImpCastExprToType(Src.take(),
4403 DestTy->castAs<ComplexType>()->getElementType(),
4404 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004405 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004406 case Type::STK_CPointer:
4407 case Type::STK_ObjCObjectPointer:
4408 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004409 llvm_unreachable("valid float->pointer cast?");
4410 case Type::STK_MemberPointer:
4411 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004412 }
David Blaikie8a40f702012-01-17 06:56:22 +00004413 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004414
John McCall8cb679e2010-11-15 09:13:47 +00004415 case Type::STK_FloatingComplex:
4416 switch (DestTy->getScalarTypeKind()) {
4417 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004418 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004419 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004420 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004421 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004422 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4423 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004424 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004425 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004426 return CK_FloatingCast;
4427 }
John McCall8cb679e2010-11-15 09:13:47 +00004428 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004429 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004430 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004431 Src = ImpCastExprToType(Src.take(),
4432 SrcTy->castAs<ComplexType>()->getElementType(),
4433 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004434 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004435 case Type::STK_CPointer:
4436 case Type::STK_ObjCObjectPointer:
4437 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004438 llvm_unreachable("valid complex float->pointer cast?");
4439 case Type::STK_MemberPointer:
4440 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004441 }
David Blaikie8a40f702012-01-17 06:56:22 +00004442 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004443
John McCall8cb679e2010-11-15 09:13:47 +00004444 case Type::STK_IntegralComplex:
4445 switch (DestTy->getScalarTypeKind()) {
4446 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004447 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004448 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004449 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004450 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004451 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4452 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004453 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004454 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004455 return CK_IntegralCast;
4456 }
John McCall8cb679e2010-11-15 09:13:47 +00004457 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004458 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004459 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004460 Src = ImpCastExprToType(Src.take(),
4461 SrcTy->castAs<ComplexType>()->getElementType(),
4462 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004463 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004464 case Type::STK_CPointer:
4465 case Type::STK_ObjCObjectPointer:
4466 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004467 llvm_unreachable("valid complex int->pointer cast?");
4468 case Type::STK_MemberPointer:
4469 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004470 }
David Blaikie8a40f702012-01-17 06:56:22 +00004471 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004472 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004473
John McCalld7646252010-11-14 08:17:51 +00004474 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004475}
4476
Anders Carlsson525b76b2009-10-16 02:48:28 +00004477bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004478 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004479 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004480
Anders Carlssonde71adf2007-11-27 05:51:55 +00004481 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004482 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004483 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004484 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004485 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004486 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004487 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004488 } else
4489 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004490 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004491 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004492
John McCalle3027922010-08-25 11:45:40 +00004493 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004494 return false;
4495}
4496
John Wiegley01296292011-04-08 18:41:53 +00004497ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4498 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004499 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004500
Anders Carlsson43d70f82009-10-16 05:23:41 +00004501 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004502
Nate Begemanc8961a42009-06-27 22:05:55 +00004503 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4504 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004505 // In OpenCL, casts between vectors of different types are not allowed.
4506 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004507 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004508 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004509 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004510 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004511 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004512 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004513 return ExprError();
4514 }
John McCalle3027922010-08-25 11:45:40 +00004515 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004516 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004517 }
4518
Nate Begemanbd956c42009-06-28 02:36:38 +00004519 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004520 // conversion will take place first from scalar to elt type, and then
4521 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004522 if (SrcTy->isPointerType())
4523 return Diag(R.getBegin(),
4524 diag::err_invalid_conversion_between_vector_and_scalar)
4525 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004526
4527 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004528 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004529 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004530 if (CastExprRes.isInvalid())
4531 return ExprError();
4532 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004533
John McCalle3027922010-08-25 11:45:40 +00004534 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004535 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004536}
4537
John McCalldadc5752010-08-24 06:29:42 +00004538ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004539Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4540 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004541 SourceLocation RParenLoc, Expr *CastExpr) {
4542 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004543 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004544
Richard Trieuba63ce62011-09-09 01:45:06 +00004545 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004546 if (D.isInvalidType())
4547 return ExprError();
4548
David Blaikiebbafb8a2012-03-11 07:00:24 +00004549 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004550 // Check that there are no default arguments (C++ only).
4551 CheckExtraCXXDefaultArguments(D);
4552 }
4553
John McCall42856de2011-10-01 05:17:03 +00004554 checkUnusedDeclAttributes(D);
4555
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004556 QualType castType = castTInfo->getType();
4557 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004558
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004559 bool isVectorLiteral = false;
4560
4561 // Check for an altivec or OpenCL literal,
4562 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004563 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4564 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004565 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004566 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004567 if (PLE && PLE->getNumExprs() == 0) {
4568 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4569 return ExprError();
4570 }
4571 if (PE || PLE->getNumExprs() == 1) {
4572 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4573 if (!E->getType()->isVectorType())
4574 isVectorLiteral = true;
4575 }
4576 else
4577 isVectorLiteral = true;
4578 }
4579
4580 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4581 // then handle it as such.
4582 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004583 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004584
Nate Begeman5ec4b312009-08-10 23:49:36 +00004585 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004586 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4587 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004588 if (isa<ParenListExpr>(CastExpr)) {
4589 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004590 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004591 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004592 }
John McCallebe54742010-01-15 18:56:44 +00004593
Richard Trieuba63ce62011-09-09 01:45:06 +00004594 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004595}
4596
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004597ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4598 SourceLocation RParenLoc, Expr *E,
4599 TypeSourceInfo *TInfo) {
4600 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4601 "Expected paren or paren list expression");
4602
4603 Expr **exprs;
4604 unsigned numExprs;
4605 Expr *subExpr;
4606 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4607 exprs = PE->getExprs();
4608 numExprs = PE->getNumExprs();
4609 } else {
4610 subExpr = cast<ParenExpr>(E)->getSubExpr();
4611 exprs = &subExpr;
4612 numExprs = 1;
4613 }
4614
4615 QualType Ty = TInfo->getType();
4616 assert(Ty->isVectorType() && "Expected vector type");
4617
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004618 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004619 const VectorType *VTy = Ty->getAs<VectorType>();
4620 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4621
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004622 // '(...)' form of vector initialization in AltiVec: the number of
4623 // initializers must be one or must match the size of the vector.
4624 // If a single value is specified in the initializer then it will be
4625 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004626 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004627 // The number of initializers must be one or must match the size of the
4628 // vector. If a single value is specified in the initializer then it will
4629 // be replicated to all the components of the vector
4630 if (numExprs == 1) {
4631 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004632 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4633 if (Literal.isInvalid())
4634 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004635 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004636 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004637 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4638 }
4639 else if (numExprs < numElems) {
4640 Diag(E->getExprLoc(),
4641 diag::err_incorrect_number_of_vector_initializers);
4642 return ExprError();
4643 }
4644 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004645 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004646 }
Tanya Lattner83559382011-07-15 23:07:01 +00004647 else {
4648 // For OpenCL, when the number of initializers is a single value,
4649 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004650 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004651 VTy->getVectorKind() == VectorType::GenericVector &&
4652 numExprs == 1) {
4653 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004654 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4655 if (Literal.isInvalid())
4656 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004657 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004658 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004659 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4660 }
4661
Benjamin Kramer8001f742012-02-14 12:06:21 +00004662 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004663 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004664 // FIXME: This means that pretty-printing the final AST will produce curly
4665 // braces instead of the original commas.
4666 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004667 initExprs, RParenLoc);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004668 initE->setType(Ty);
4669 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4670}
4671
Sebastian Redla9351792012-02-11 23:51:47 +00004672/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4673/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004674ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004675Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4676 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004677 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004678 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004679
John McCalldadc5752010-08-24 06:29:42 +00004680 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004681
Nate Begeman5ec4b312009-08-10 23:49:36 +00004682 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004683 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4684 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004685
John McCallb268a282010-08-23 23:25:46 +00004686 if (Result.isInvalid()) return ExprError();
4687
4688 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004689}
4690
Sebastian Redla9351792012-02-11 23:51:47 +00004691ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4692 SourceLocation R,
4693 MultiExprArg Val) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00004694 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4695 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004696 return Owned(expr);
4697}
4698
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004699/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004700/// constant and the other is not a pointer. Returns true if a diagnostic is
4701/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004702bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004703 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004704 Expr *NullExpr = LHSExpr;
4705 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004706 Expr::NullPointerConstantKind NullKind =
4707 NullExpr->isNullPointerConstant(Context,
4708 Expr::NPC_ValueDependentIsNotNull);
4709
4710 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004711 NullExpr = RHSExpr;
4712 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004713 NullKind =
4714 NullExpr->isNullPointerConstant(Context,
4715 Expr::NPC_ValueDependentIsNotNull);
4716 }
4717
4718 if (NullKind == Expr::NPCK_NotNull)
4719 return false;
4720
David Blaikie1c7c8f72012-08-08 17:33:31 +00004721 if (NullKind == Expr::NPCK_ZeroExpression)
4722 return false;
4723
4724 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004725 // In this case, check to make sure that we got here from a "NULL"
4726 // string in the source code.
4727 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004728 SourceLocation loc = NullExpr->getExprLoc();
4729 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004730 return false;
4731 }
4732
4733 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4734 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4735 << NonPointerExpr->getType() << DiagType
4736 << NonPointerExpr->getSourceRange();
4737 return true;
4738}
4739
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004740/// \brief Return false if the condition expression is valid, true otherwise.
4741static bool checkCondition(Sema &S, Expr *Cond) {
4742 QualType CondTy = Cond->getType();
4743
4744 // C99 6.5.15p2
4745 if (CondTy->isScalarType()) return false;
4746
4747 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004748 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004749 return false;
4750
4751 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004752 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004753 diag::err_typecheck_cond_expect_scalar :
4754 diag::err_typecheck_cond_expect_scalar_or_vector)
4755 << CondTy;
4756 return true;
4757}
4758
4759/// \brief Return false if the two expressions can be converted to a vector,
4760/// true otherwise
4761static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4762 ExprResult &RHS,
4763 QualType CondTy) {
4764 // Both operands should be of scalar type.
4765 if (!LHS.get()->getType()->isScalarType()) {
4766 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4767 << CondTy;
4768 return true;
4769 }
4770 if (!RHS.get()->getType()->isScalarType()) {
4771 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4772 << CondTy;
4773 return true;
4774 }
4775
4776 // Implicity convert these scalars to the type of the condition.
4777 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4778 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4779 return false;
4780}
4781
4782/// \brief Handle when one or both operands are void type.
4783static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4784 ExprResult &RHS) {
4785 Expr *LHSExpr = LHS.get();
4786 Expr *RHSExpr = RHS.get();
4787
4788 if (!LHSExpr->getType()->isVoidType())
4789 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4790 << RHSExpr->getSourceRange();
4791 if (!RHSExpr->getType()->isVoidType())
4792 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4793 << LHSExpr->getSourceRange();
4794 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4795 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4796 return S.Context.VoidTy;
4797}
4798
4799/// \brief Return false if the NullExpr can be promoted to PointerTy,
4800/// true otherwise.
4801static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4802 QualType PointerTy) {
4803 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4804 !NullExpr.get()->isNullPointerConstant(S.Context,
4805 Expr::NPC_ValueDependentIsNull))
4806 return true;
4807
4808 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4809 return false;
4810}
4811
4812/// \brief Checks compatibility between two pointers and return the resulting
4813/// type.
4814static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4815 ExprResult &RHS,
4816 SourceLocation Loc) {
4817 QualType LHSTy = LHS.get()->getType();
4818 QualType RHSTy = RHS.get()->getType();
4819
4820 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4821 // Two identical pointers types are always compatible.
4822 return LHSTy;
4823 }
4824
4825 QualType lhptee, rhptee;
4826
4827 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004828 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4829 lhptee = LHSBTy->getPointeeType();
4830 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004831 } else {
John McCall9320b872011-09-09 05:25:32 +00004832 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4833 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004834 }
4835
Eli Friedman57a75392012-04-05 22:30:04 +00004836 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4837 // differently qualified versions of compatible types, the result type is
4838 // a pointer to an appropriately qualified version of the composite
4839 // type.
4840
4841 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4842 // clause doesn't make sense for our extensions. E.g. address space 2 should
4843 // be incompatible with address space 3: they may live on different devices or
4844 // anything.
4845 Qualifiers lhQual = lhptee.getQualifiers();
4846 Qualifiers rhQual = rhptee.getQualifiers();
4847
4848 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4849 lhQual.removeCVRQualifiers();
4850 rhQual.removeCVRQualifiers();
4851
4852 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4853 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4854
4855 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4856
4857 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004858 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4859 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4860 << RHS.get()->getSourceRange();
4861 // In this situation, we assume void* type. No especially good
4862 // reason, but this is what gcc does, and we do have to pick
4863 // to get a consistent AST.
4864 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4865 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4866 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4867 return incompatTy;
4868 }
4869
4870 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004871 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4872 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004873
Eli Friedman57a75392012-04-05 22:30:04 +00004874 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4875 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4876 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004877}
4878
4879/// \brief Return the resulting type when the operands are both block pointers.
4880static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4881 ExprResult &LHS,
4882 ExprResult &RHS,
4883 SourceLocation Loc) {
4884 QualType LHSTy = LHS.get()->getType();
4885 QualType RHSTy = RHS.get()->getType();
4886
4887 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4888 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4889 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4890 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4891 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4892 return destType;
4893 }
4894 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4895 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4896 << RHS.get()->getSourceRange();
4897 return QualType();
4898 }
4899
4900 // We have 2 block pointer types.
4901 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4902}
4903
4904/// \brief Return the resulting type when the operands are both pointers.
4905static QualType
4906checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4907 ExprResult &RHS,
4908 SourceLocation Loc) {
4909 // get the pointer types
4910 QualType LHSTy = LHS.get()->getType();
4911 QualType RHSTy = RHS.get()->getType();
4912
4913 // get the "pointed to" types
4914 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4915 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4916
4917 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4918 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4919 // Figure out necessary qualifiers (C99 6.5.15p6)
4920 QualType destPointee
4921 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4922 QualType destType = S.Context.getPointerType(destPointee);
4923 // Add qualifiers if necessary.
4924 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4925 // Promote to void*.
4926 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4927 return destType;
4928 }
4929 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4930 QualType destPointee
4931 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4932 QualType destType = S.Context.getPointerType(destPointee);
4933 // Add qualifiers if necessary.
4934 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4935 // Promote to void*.
4936 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4937 return destType;
4938 }
4939
4940 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4941}
4942
4943/// \brief Return false if the first expression is not an integer and the second
4944/// expression is not a pointer, true otherwise.
4945static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4946 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004947 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004948 if (!PointerExpr->getType()->isPointerType() ||
4949 !Int.get()->getType()->isIntegerType())
4950 return false;
4951
Richard Trieuba63ce62011-09-09 01:45:06 +00004952 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4953 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004954
4955 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4956 << Expr1->getType() << Expr2->getType()
4957 << Expr1->getSourceRange() << Expr2->getSourceRange();
4958 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4959 CK_IntegralToPointer);
4960 return true;
4961}
4962
Richard Trieud33e46e2011-09-06 20:06:39 +00004963/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4964/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004965/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004966QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4967 ExprResult &RHS, ExprValueKind &VK,
4968 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004969 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004970
Richard Trieud33e46e2011-09-06 20:06:39 +00004971 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4972 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004973 LHS = LHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004974
Richard Trieud33e46e2011-09-06 20:06:39 +00004975 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4976 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004977 RHS = RHSResult;
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004978
Sebastian Redl1a99f442009-04-16 17:51:27 +00004979 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004980 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004981 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004982
4983 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004984 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004985
John Wiegley01296292011-04-08 18:41:53 +00004986 Cond = UsualUnaryConversions(Cond.take());
4987 if (Cond.isInvalid())
4988 return QualType();
4989 LHS = UsualUnaryConversions(LHS.take());
4990 if (LHS.isInvalid())
4991 return QualType();
4992 RHS = UsualUnaryConversions(RHS.take());
4993 if (RHS.isInvalid())
4994 return QualType();
4995
4996 QualType CondTy = Cond.get()->getType();
4997 QualType LHSTy = LHS.get()->getType();
4998 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004999
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005000 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005001 if (checkCondition(*this, Cond.get()))
5002 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005003
Chris Lattnere2949f42008-01-06 22:42:25 +00005004 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005005 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005006 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00005007
Nate Begemanabb5a732010-09-20 22:41:17 +00005008 // OpenCL: If the condition is a vector, and both operands are scalar,
5009 // attempt to implicity convert them to the vector type to act like the
5010 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005011 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005012 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00005013 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00005014
Chris Lattnere2949f42008-01-06 22:42:25 +00005015 // If both operands have arithmetic type, do the usual arithmetic conversions
5016 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005017 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5018 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005019 if (LHS.isInvalid() || RHS.isInvalid())
5020 return QualType();
5021 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005022 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005023
Chris Lattnere2949f42008-01-06 22:42:25 +00005024 // If both operands are the same structure or union type, the result is that
5025 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005026 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5027 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005028 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005029 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005030 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005031 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005032 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005033 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005034
Chris Lattnere2949f42008-01-06 22:42:25 +00005035 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005036 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005037 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005038 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00005039 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005040
Steve Naroff039ad3c2008-01-08 01:11:38 +00005041 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5042 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005043 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5044 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005045
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005046 // All objective-c pointer type analysis is done here.
5047 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5048 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005049 if (LHS.isInvalid() || RHS.isInvalid())
5050 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005051 if (!compositeType.isNull())
5052 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005053
5054
Steve Naroff05efa972009-07-01 14:36:47 +00005055 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005056 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5057 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5058 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005059
Steve Naroff05efa972009-07-01 14:36:47 +00005060 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005061 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5062 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5063 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005064
John McCalle84af4e2010-11-13 01:35:44 +00005065 // GCC compatibility: soften pointer/integer mismatch. Note that
5066 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005067 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5068 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00005069 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00005070 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5071 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00005072 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00005073
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005074 // Emit a better diagnostic if one of the expressions is a null pointer
5075 // constant and the other is not a pointer type. In this case, the user most
5076 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005077 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005078 return QualType();
5079
Chris Lattnere2949f42008-01-06 22:42:25 +00005080 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005081 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00005082 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5083 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005084 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005085}
5086
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005087/// FindCompositeObjCPointerType - Helper method to find composite type of
5088/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005089QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005090 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005091 QualType LHSTy = LHS.get()->getType();
5092 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005093
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005094 // Handle things like Class and struct objc_class*. Here we case the result
5095 // to the pseudo-builtin, because that will be implicitly cast back to the
5096 // redefinition type if an attempt is made to access its fields.
5097 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005098 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005099 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005100 return LHSTy;
5101 }
5102 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005103 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005104 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005105 return RHSTy;
5106 }
5107 // And the same for struct objc_object* / id
5108 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005109 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005110 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005111 return LHSTy;
5112 }
5113 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00005114 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00005115 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005116 return RHSTy;
5117 }
5118 // And the same for struct objc_selector* / SEL
5119 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005120 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005121 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005122 return LHSTy;
5123 }
5124 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00005125 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005126 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005127 return RHSTy;
5128 }
5129 // Check constraints for Objective-C object pointers types.
5130 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005131
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005132 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5133 // Two identical object pointer types are always compatible.
5134 return LHSTy;
5135 }
John McCall9320b872011-09-09 05:25:32 +00005136 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5137 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005138 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005139
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005140 // If both operands are interfaces and either operand can be
5141 // assigned to the other, use that type as the composite
5142 // type. This allows
5143 // xxx ? (A*) a : (B*) b
5144 // where B is a subclass of A.
5145 //
5146 // Additionally, as for assignment, if either type is 'id'
5147 // allow silent coercion. Finally, if the types are
5148 // incompatible then make sure to use 'id' as the composite
5149 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005150
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005151 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5152 // It could return the composite type.
5153 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5154 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5155 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5156 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5157 } else if ((LHSTy->isObjCQualifiedIdType() ||
5158 RHSTy->isObjCQualifiedIdType()) &&
5159 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5160 // Need to handle "id<xx>" explicitly.
5161 // GCC allows qualified id and any Objective-C type to devolve to
5162 // id. Currently localizing to here until clear this should be
5163 // part of ObjCQualifiedIdTypesAreCompatible.
5164 compositeType = Context.getObjCIdType();
5165 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5166 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005167 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005168 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5169 ;
5170 else {
5171 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5172 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00005173 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005174 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00005175 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5176 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005177 return incompatTy;
5178 }
5179 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005180 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5181 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005182 return compositeType;
5183 }
5184 // Check Objective-C object pointer types and 'void *'
5185 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005186 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005187 // ARC forbids the implicit conversion of object pointers to 'void *',
5188 // so these types are not compatible.
5189 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5191 LHS = RHS = true;
5192 return QualType();
5193 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005194 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5195 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5196 QualType destPointee
5197 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5198 QualType destType = Context.getPointerType(destPointee);
5199 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005200 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005201 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005202 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005203 return destType;
5204 }
5205 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005206 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005207 // ARC forbids the implicit conversion of object pointers to 'void *',
5208 // so these types are not compatible.
5209 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5210 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5211 LHS = RHS = true;
5212 return QualType();
5213 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005214 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5215 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5216 QualType destPointee
5217 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5218 QualType destType = Context.getPointerType(destPointee);
5219 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005220 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005221 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005222 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005223 return destType;
5224 }
5225 return QualType();
5226}
5227
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005228/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005229/// ParenRange in parentheses.
5230static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005231 const PartialDiagnostic &Note,
5232 SourceRange ParenRange) {
5233 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5234 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5235 EndLoc.isValid()) {
5236 Self.Diag(Loc, Note)
5237 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5238 << FixItHint::CreateInsertion(EndLoc, ")");
5239 } else {
5240 // We can't display the parentheses, so just show the bare note.
5241 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005242 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005243}
5244
5245static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5246 return Opc >= BO_Mul && Opc <= BO_Shr;
5247}
5248
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005249/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5250/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005251/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5252/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005253static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005254 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005255 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5256 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005257 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005258 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005259
5260 // Built-in binary operator.
5261 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5262 if (IsArithmeticOp(OP->getOpcode())) {
5263 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005264 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005265 return true;
5266 }
5267 }
5268
5269 // Overloaded operator.
5270 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5271 if (Call->getNumArgs() != 2)
5272 return false;
5273
5274 // Make sure this is really a binary operator that is safe to pass into
5275 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5276 OverloadedOperatorKind OO = Call->getOperator();
5277 if (OO < OO_Plus || OO > OO_Arrow)
5278 return false;
5279
5280 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5281 if (IsArithmeticOp(OpKind)) {
5282 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005283 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005284 return true;
5285 }
5286 }
5287
5288 return false;
5289}
5290
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005291static bool IsLogicOp(BinaryOperatorKind Opc) {
5292 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5293}
5294
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005295/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5296/// or is a logical expression such as (x==y) which has int type, but is
5297/// commonly interpreted as boolean.
5298static bool ExprLooksBoolean(Expr *E) {
5299 E = E->IgnoreParenImpCasts();
5300
5301 if (E->getType()->isBooleanType())
5302 return true;
5303 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5304 return IsLogicOp(OP->getOpcode());
5305 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5306 return OP->getOpcode() == UO_LNot;
5307
5308 return false;
5309}
5310
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005311/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5312/// and binary operator are mixed in a way that suggests the programmer assumed
5313/// the conditional operator has higher precedence, for example:
5314/// "int x = a + someBinaryCondition ? 1 : 2".
5315static void DiagnoseConditionalPrecedence(Sema &Self,
5316 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005317 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005318 Expr *LHSExpr,
5319 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005320 BinaryOperatorKind CondOpcode;
5321 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005322
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005323 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005324 return;
5325 if (!ExprLooksBoolean(CondRHS))
5326 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005327
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005328 // The condition is an arithmetic binary expression, with a right-
5329 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005330
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005331 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005332 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005333 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005334
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005335 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00005336 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005337 << BinaryOperator::getOpcodeStr(CondOpcode),
5338 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005339
5340 SuggestParentheses(Self, OpLoc,
5341 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005342 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005343}
5344
Steve Naroff83895f72007-09-16 03:34:24 +00005345/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005346/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005347ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005348 SourceLocation ColonLoc,
5349 Expr *CondExpr, Expr *LHSExpr,
5350 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005351 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5352 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005353 OpaqueValueExpr *opaqueValue = 0;
5354 Expr *commonExpr = 0;
5355 if (LHSExpr == 0) {
5356 commonExpr = CondExpr;
5357
5358 // We usually want to apply unary conversions *before* saving, except
5359 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005360 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005361 && !commonExpr->isTypeDependent()
5362 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5363 && commonExpr->isGLValue()
5364 && commonExpr->isOrdinaryOrBitFieldObject()
5365 && RHSExpr->isOrdinaryOrBitFieldObject()
5366 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005367 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5368 if (commonRes.isInvalid())
5369 return ExprError();
5370 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005371 }
5372
5373 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5374 commonExpr->getType(),
5375 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005376 commonExpr->getObjectKind(),
5377 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005378 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005379 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005380
John McCall7decc9e2010-11-18 06:31:45 +00005381 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005382 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005383 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5384 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005385 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005386 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5387 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005388 return ExprError();
5389
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005390 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5391 RHS.get());
5392
John McCallc07a0c72011-02-17 10:25:35 +00005393 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005394 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5395 LHS.take(), ColonLoc,
5396 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005397
5398 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005399 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005400 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5401 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005402}
5403
John McCallaba90822011-01-31 23:13:11 +00005404// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005405// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005406// routine is it effectively iqnores the qualifiers on the top level pointee.
5407// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5408// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005409static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005410checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5411 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5412 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005413
Steve Naroff1f4d7272007-05-11 04:00:31 +00005414 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005415 const Type *lhptee, *rhptee;
5416 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005417 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5418 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005419
John McCallaba90822011-01-31 23:13:11 +00005420 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005421
5422 // C99 6.5.16.1p1: This following citation is common to constraints
5423 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5424 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005425 Qualifiers lq;
5426
John McCall31168b02011-06-15 23:02:42 +00005427 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5428 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5429 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5430 // Ignore lifetime for further calculation.
5431 lhq.removeObjCLifetime();
5432 rhq.removeObjCLifetime();
5433 }
5434
John McCall4fff8f62011-02-01 00:10:29 +00005435 if (!lhq.compatiblyIncludes(rhq)) {
5436 // Treat address-space mismatches as fatal. TODO: address subspaces
5437 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5438 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5439
John McCall31168b02011-06-15 23:02:42 +00005440 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005441 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005442 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005443 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005444 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005445 && (lhptee->isVoidType() || rhptee->isVoidType()))
5446 ; // keep old
5447
John McCall31168b02011-06-15 23:02:42 +00005448 // Treat lifetime mismatches as fatal.
5449 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5450 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5451
John McCall4fff8f62011-02-01 00:10:29 +00005452 // For GCC compatibility, other qualifier mismatches are treated
5453 // as still compatible in C.
5454 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5455 }
Steve Naroff3f597292007-05-11 22:18:03 +00005456
Mike Stump4e1f26a2009-02-19 03:04:26 +00005457 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5458 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005459 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005460 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005461 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005462 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005463
Chris Lattner0a788432008-01-03 22:56:36 +00005464 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005465 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005466 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005467 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005468
Chris Lattner0a788432008-01-03 22:56:36 +00005469 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005470 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005471 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005472
5473 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005474 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005475 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005476 }
John McCall4fff8f62011-02-01 00:10:29 +00005477
Mike Stump4e1f26a2009-02-19 03:04:26 +00005478 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005479 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005480 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5481 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005482 // Check if the pointee types are compatible ignoring the sign.
5483 // We explicitly check for char so that we catch "char" vs
5484 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005485 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005486 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005487 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005488 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005489
Chris Lattnerec3a1562009-10-17 20:33:28 +00005490 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005491 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005492 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005493 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005494
John McCall4fff8f62011-02-01 00:10:29 +00005495 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005496 // Types are compatible ignoring the sign. Qualifier incompatibility
5497 // takes priority over sign incompatibility because the sign
5498 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005499 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005500 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005501
John McCallaba90822011-01-31 23:13:11 +00005502 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005503 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005504
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005505 // If we are a multi-level pointer, it's possible that our issue is simply
5506 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5507 // the eventual target type is the same and the pointers have the same
5508 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005509 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005510 do {
John McCall4fff8f62011-02-01 00:10:29 +00005511 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5512 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005513 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005514
John McCall4fff8f62011-02-01 00:10:29 +00005515 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005516 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005517 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005518
Eli Friedman80160bd2009-03-22 23:59:44 +00005519 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005520 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005521 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005522 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005523 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5524 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005525 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005526}
5527
John McCallaba90822011-01-31 23:13:11 +00005528/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005529/// block pointer types are compatible or whether a block and normal pointer
5530/// are compatible. It is more restrict than comparing two function pointer
5531// types.
John McCallaba90822011-01-31 23:13:11 +00005532static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005533checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5534 QualType RHSType) {
5535 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5536 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005537
Steve Naroff081c7422008-09-04 15:10:53 +00005538 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005539
Steve Naroff081c7422008-09-04 15:10:53 +00005540 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005541 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5542 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005543
John McCallaba90822011-01-31 23:13:11 +00005544 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005545 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005546 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005547
John McCallaba90822011-01-31 23:13:11 +00005548 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005549
Steve Naroff081c7422008-09-04 15:10:53 +00005550 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005551 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5552 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005553
Richard Trieua871b972011-09-06 20:21:22 +00005554 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005555 return Sema::IncompatibleBlockPointer;
5556
Steve Naroff081c7422008-09-04 15:10:53 +00005557 return ConvTy;
5558}
5559
John McCallaba90822011-01-31 23:13:11 +00005560/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005561/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005562static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005563checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5564 QualType RHSType) {
5565 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5566 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005567
Richard Trieua871b972011-09-06 20:21:22 +00005568 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005569 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005570 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5571 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005572 return Sema::IncompatiblePointer;
5573 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005574 }
Richard Trieua871b972011-09-06 20:21:22 +00005575 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005576 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5577 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005578 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005579 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005580 }
Richard Trieua871b972011-09-06 20:21:22 +00005581 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5582 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005583
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005584 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5585 // make an exception for id<P>
5586 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005587 return Sema::CompatiblePointerDiscardsQualifiers;
5588
Richard Trieua871b972011-09-06 20:21:22 +00005589 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005590 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005591 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005592 return Sema::IncompatibleObjCQualifiedId;
5593 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005594}
5595
John McCall29600e12010-11-16 02:32:08 +00005596Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005597Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005598 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005599 // Fake up an opaque expression. We don't actually care about what
5600 // cast operations are required, so if CheckAssignmentConstraints
5601 // adds casts to this they'll be wasted, but fortunately that doesn't
5602 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005603 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5604 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005605 CastKind K = CK_Invalid;
5606
Richard Trieua871b972011-09-06 20:21:22 +00005607 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005608}
5609
Mike Stump4e1f26a2009-02-19 03:04:26 +00005610/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5611/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005612/// pointers. Here are some objectionable examples that GCC considers warnings:
5613///
5614/// int a, *pint;
5615/// short *pshort;
5616/// struct foo *pfoo;
5617///
5618/// pint = pshort; // warning: assignment from incompatible pointer type
5619/// a = pint; // warning: assignment makes integer from pointer without a cast
5620/// pint = a; // warning: assignment makes pointer from integer without a cast
5621/// pint = pfoo; // warning: assignment from incompatible pointer type
5622///
5623/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005624/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005625///
John McCall8cb679e2010-11-15 09:13:47 +00005626/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005627Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005628Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005629 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005630 QualType RHSType = RHS.get()->getType();
5631 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005632
Chris Lattnera52c2f22008-01-04 23:18:45 +00005633 // Get canonical types. We're not formatting these types, just comparing
5634 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005635 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5636 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005637
Eli Friedman0dfb8892011-10-06 23:00:33 +00005638
John McCalle5255932011-01-31 22:28:28 +00005639 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005640 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005641 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005642 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005643 }
5644
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005645 // If we have an atomic type, try a non-atomic assignment, then just add an
5646 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005647 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005648 Sema::AssignConvertType result =
5649 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5650 if (result != Compatible)
5651 return result;
5652 if (Kind != CK_NoOp)
5653 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5654 Kind = CK_NonAtomicToAtomic;
5655 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005656 }
5657
Douglas Gregor6b754842008-10-28 00:22:11 +00005658 // If the left-hand side is a reference type, then we are in a
5659 // (rare!) case where we've allowed the use of references in C,
5660 // e.g., as a parameter type in a built-in function. In this case,
5661 // just make sure that the type referenced is compatible with the
5662 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005663 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005664 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005665 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5666 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005667 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005668 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005669 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005670 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005671 }
John McCalle5255932011-01-31 22:28:28 +00005672
Nate Begemanbd956c42009-06-28 02:36:38 +00005673 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5674 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005675 if (LHSType->isExtVectorType()) {
5676 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005677 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005678 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005679 // CK_VectorSplat does T -> vector T, so first cast to the
5680 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005681 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5682 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005683 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005684 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005685 }
5686 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005687 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005688 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005689 }
Mike Stump11289f42009-09-09 15:08:12 +00005690
John McCalle5255932011-01-31 22:28:28 +00005691 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005692 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5693 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005694 // Allow assignments of an AltiVec vector type to an equivalent GCC
5695 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005696 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005697 Kind = CK_BitCast;
5698 return Compatible;
5699 }
5700
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005701 // If we are allowing lax vector conversions, and LHS and RHS are both
5702 // vectors, the total size only needs to be the same. This is a bitcast;
5703 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005704 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005705 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005706 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005707 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005708 }
Chris Lattner881a2122008-01-04 23:32:24 +00005709 }
5710 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005711 }
Eli Friedman3360d892008-05-30 18:07:22 +00005712
John McCalle5255932011-01-31 22:28:28 +00005713 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005714 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005715 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005716 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005717 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005718 }
Eli Friedman3360d892008-05-30 18:07:22 +00005719
John McCalle5255932011-01-31 22:28:28 +00005720 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005721 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005722 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005723 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005724 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005725 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005726 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005727
John McCalle5255932011-01-31 22:28:28 +00005728 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005729 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005730 Kind = CK_IntegralToPointer; // FIXME: null?
5731 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005732 }
John McCalle5255932011-01-31 22:28:28 +00005733
5734 // C pointers are not compatible with ObjC object pointers,
5735 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005736 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005737 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005738 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005739 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005740 return Compatible;
5741 }
5742
5743 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005744 if (RHSType->isObjCClassType() &&
5745 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005746 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005747 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005748 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005749 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005750
John McCalle5255932011-01-31 22:28:28 +00005751 Kind = CK_BitCast;
5752 return IncompatiblePointer;
5753 }
5754
5755 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005756 if (RHSType->getAs<BlockPointerType>()) {
5757 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005758 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005759 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005760 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005761 }
John McCalle5255932011-01-31 22:28:28 +00005762
Steve Naroff081c7422008-09-04 15:10:53 +00005763 return Incompatible;
5764 }
5765
John McCalle5255932011-01-31 22:28:28 +00005766 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005767 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005768 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005769 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005770 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005771 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005772 }
5773
5774 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005775 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005776 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005777 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005778 }
5779
John McCalle5255932011-01-31 22:28:28 +00005780 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005781 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005782 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005783 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005784 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005785
John McCalle5255932011-01-31 22:28:28 +00005786 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005787 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005788 if (RHSPT->getPointeeType()->isVoidType()) {
5789 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005790 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005791 }
John McCall8cb679e2010-11-15 09:13:47 +00005792
Chris Lattnera52c2f22008-01-04 23:18:45 +00005793 return Incompatible;
5794 }
5795
John McCalle5255932011-01-31 22:28:28 +00005796 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005797 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005798 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005799 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005800 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005801 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005802 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005803 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005804 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005805 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005806 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005807 return result;
John McCalle5255932011-01-31 22:28:28 +00005808 }
5809
5810 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005811 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005812 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005813 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005814 }
5815
John McCalle5255932011-01-31 22:28:28 +00005816 // In general, C pointers are not compatible with ObjC object pointers,
5817 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005818 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005819 Kind = CK_CPointerToObjCPointerCast;
5820
John McCalle5255932011-01-31 22:28:28 +00005821 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005822 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005823 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005824 }
5825
5826 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005827 if (LHSType->isObjCClassType() &&
5828 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005829 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005830 return Compatible;
5831 }
5832
Steve Naroffaccc4882009-07-20 17:56:53 +00005833 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005834 }
John McCalle5255932011-01-31 22:28:28 +00005835
5836 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005837 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005838 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005839 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005840 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005841 }
5842
Steve Naroff7cae42b2009-07-10 23:34:53 +00005843 return Incompatible;
5844 }
John McCalle5255932011-01-31 22:28:28 +00005845
5846 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005847 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005848 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005849 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005850 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005851 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005852 }
Eli Friedman3360d892008-05-30 18:07:22 +00005853
John McCalle5255932011-01-31 22:28:28 +00005854 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005855 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005856 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005857 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005858 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005859
Chris Lattnera52c2f22008-01-04 23:18:45 +00005860 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005861 }
John McCalle5255932011-01-31 22:28:28 +00005862
5863 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005864 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005865 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005866 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005867 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005868 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005869 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005870
John McCalle5255932011-01-31 22:28:28 +00005871 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005872 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005873 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005874 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005875 }
5876
Steve Naroff7cae42b2009-07-10 23:34:53 +00005877 return Incompatible;
5878 }
Eli Friedman3360d892008-05-30 18:07:22 +00005879
John McCalle5255932011-01-31 22:28:28 +00005880 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005881 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5882 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005883 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005884 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005885 }
Bill Wendling216423b2007-05-30 06:30:29 +00005886 }
John McCalle5255932011-01-31 22:28:28 +00005887
Steve Naroff98cf3e92007-06-06 18:38:38 +00005888 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005889}
5890
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005891/// \brief Constructs a transparent union from an expression that is
5892/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005893static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5894 ExprResult &EResult, QualType UnionType,
5895 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005896 // Build an initializer list that designates the appropriate member
5897 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005898 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005899 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00005900 E, SourceLocation());
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005901 Initializer->setType(UnionType);
5902 Initializer->setInitializedFieldInUnion(Field);
5903
5904 // Build a compound literal constructing a value of the transparent
5905 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005906 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005907 EResult = S.Owned(
5908 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5909 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005910}
5911
5912Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005913Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005914 ExprResult &RHS) {
5915 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005916
Mike Stump11289f42009-09-09 15:08:12 +00005917 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005918 // transparent_union GCC extension.
5919 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005920 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005921 return Incompatible;
5922
5923 // The field to initialize within the transparent union.
5924 RecordDecl *UD = UT->getDecl();
5925 FieldDecl *InitField = 0;
5926 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005927 for (RecordDecl::field_iterator it = UD->field_begin(),
5928 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005929 it != itend; ++it) {
5930 if (it->getType()->isPointerType()) {
5931 // If the transparent union contains a pointer type, we allow:
5932 // 1) void pointer
5933 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005934 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005935 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005936 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005937 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005938 break;
5939 }
Mike Stump11289f42009-09-09 15:08:12 +00005940
Richard Trieueb299142011-09-06 20:40:12 +00005941 if (RHS.get()->isNullPointerConstant(Context,
5942 Expr::NPC_ValueDependentIsNull)) {
5943 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5944 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005945 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005946 break;
5947 }
5948 }
5949
John McCall8cb679e2010-11-15 09:13:47 +00005950 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005951 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005952 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005953 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005954 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005955 break;
5956 }
5957 }
5958
5959 if (!InitField)
5960 return Incompatible;
5961
Richard Trieueb299142011-09-06 20:40:12 +00005962 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005963 return Compatible;
5964}
5965
Chris Lattner9bad62c2008-01-04 18:04:52 +00005966Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005967Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5968 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005969 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005970 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005971 // C++ 5.17p3: If the left operand is not of class type, the
5972 // expression is implicitly converted (C++ 4) to the
5973 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005974 ExprResult Res;
5975 if (Diagnose) {
5976 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5977 AA_Assigning);
5978 } else {
5979 ImplicitConversionSequence ICS =
5980 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5981 /*SuppressUserConversions=*/false,
5982 /*AllowExplicit=*/false,
5983 /*InOverloadResolution=*/false,
5984 /*CStyle=*/false,
5985 /*AllowObjCWritebackConversion=*/false);
5986 if (ICS.isFailure())
5987 return Incompatible;
5988 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5989 ICS, AA_Assigning);
5990 }
John Wiegley01296292011-04-08 18:41:53 +00005991 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005992 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005993 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005994 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005995 !CheckObjCARCUnavailableWeakConversion(LHSType,
5996 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005997 result = IncompatibleObjCWeakRef;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005998 RHS = Res;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005999 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00006000 }
6001
6002 // FIXME: Currently, we fall through and treat C++ classes like C
6003 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00006004 // FIXME: We also fall through for atomics; not sure what should
6005 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006006 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006007
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006008 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6009 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00006010 if ((LHSType->isPointerType() ||
6011 LHSType->isObjCObjectPointerType() ||
6012 LHSType->isBlockPointerType())
6013 && RHS.get()->isNullPointerConstant(Context,
6014 Expr::NPC_ValueDependentIsNull)) {
6015 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006016 return Compatible;
6017 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006018
Chris Lattnere6dcd502007-10-16 02:55:40 +00006019 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006020 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006021 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006022 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006023 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006024 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00006025 if (!LHSType->isReferenceType()) {
6026 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6027 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006028 return Incompatible;
6029 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006030
John McCall8cb679e2010-11-15 09:13:47 +00006031 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006032 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00006033 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006034
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006035 // C99 6.5.16.1p2: The value of the right operand is converted to the
6036 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006037 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6038 // so that we can use references in built-in functions even in C.
6039 // The getNonReferenceType() call makes sure that the resulting expression
6040 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00006041 if (result != Incompatible && RHS.get()->getType() != LHSType)
6042 RHS = ImpCastExprToType(RHS.take(),
6043 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006044 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006045}
6046
Richard Trieueb299142011-09-06 20:40:12 +00006047QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6048 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006049 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00006050 << LHS.get()->getType() << RHS.get()->getType()
6051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006052 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006053}
6054
Richard Trieu859d23f2011-09-06 21:01:04 +00006055QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006056 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00006057 if (!IsCompAssign) {
6058 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6059 if (LHS.isInvalid())
6060 return QualType();
6061 }
6062 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6063 if (RHS.isInvalid())
6064 return QualType();
6065
Mike Stump4e1f26a2009-02-19 03:04:26 +00006066 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006067 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00006068 QualType LHSType =
6069 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6070 QualType RHSType =
6071 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006072
Nate Begeman191a6b12008-07-14 18:02:46 +00006073 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00006074 if (LHSType == RHSType)
6075 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006076
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006077 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00006078 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6079 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6080 if (LHSType->isExtVectorType()) {
6081 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6082 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006083 }
6084
Richard Trieuba63ce62011-09-09 01:45:06 +00006085 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00006086 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6087 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006088 }
6089
David Blaikiebbafb8a2012-03-11 07:00:24 +00006090 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006091 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00006092 // If we are allowing lax vector conversions, and LHS and RHS are both
6093 // vectors, the total size only needs to be the same. This is a
6094 // bitcast; no bits are changed but the result type is different.
6095 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00006096 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6097 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00006098 }
6099
Nate Begemanbd956c42009-06-28 02:36:38 +00006100 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6101 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6102 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00006103 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006104 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00006105 std::swap(RHS, LHS);
6106 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00006107 }
Mike Stump11289f42009-09-09 15:08:12 +00006108
Nate Begeman886448d2009-06-28 19:12:57 +00006109 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00006110 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006111 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00006112 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6113 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006114 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006115 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006116 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006117 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6118 if (swapped) std::swap(RHS, LHS);
6119 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006120 }
6121 }
Richard Trieu859d23f2011-09-06 21:01:04 +00006122 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6123 RHSType->isRealFloatingType()) {
6124 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00006125 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00006126 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006127 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00006128 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6129 if (swapped) std::swap(RHS, LHS);
6130 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00006131 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006132 }
6133 }
Mike Stump11289f42009-09-09 15:08:12 +00006134
Nate Begeman886448d2009-06-28 19:12:57 +00006135 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00006136 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00006137 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00006138 << LHS.get()->getType() << RHS.get()->getType()
6139 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006140 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006141}
6142
Richard Trieuf8916e12011-09-16 00:53:10 +00006143// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6144// expression. These are mainly cases where the null pointer is used as an
6145// integer instead of a pointer.
6146static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6147 SourceLocation Loc, bool IsCompare) {
6148 // The canonical way to check for a GNU null is with isNullPointerConstant,
6149 // but we use a bit of a hack here for speed; this is a relatively
6150 // hot path, and isNullPointerConstant is slow.
6151 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6152 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6153
6154 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6155
6156 // Avoid analyzing cases where the result will either be invalid (and
6157 // diagnosed as such) or entirely valid and not something to warn about.
6158 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6159 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6160 return;
6161
6162 // Comparison operations would not make sense with a null pointer no matter
6163 // what the other expression is.
6164 if (!IsCompare) {
6165 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6166 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6167 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6168 return;
6169 }
6170
6171 // The rest of the operations only make sense with a null pointer
6172 // if the other expression is a pointer.
6173 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6174 NonNullType->canDecayToPointerType())
6175 return;
6176
6177 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6178 << LHSNull /* LHS is NULL */ << NonNullType
6179 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6180}
6181
Richard Trieu859d23f2011-09-06 21:01:04 +00006182QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006183 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006184 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006185 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6186
Richard Trieu859d23f2011-09-06 21:01:04 +00006187 if (LHS.get()->getType()->isVectorType() ||
6188 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006189 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006190
Richard Trieuba63ce62011-09-09 01:45:06 +00006191 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006192 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006193 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006194
David Chisnallfa35df62012-01-16 17:27:18 +00006195
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006196 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006197 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006198
Chris Lattnerfaa54172010-01-12 21:23:57 +00006199 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006200 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006201 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006202 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006203 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6204 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006205
Chris Lattnerfaa54172010-01-12 21:23:57 +00006206 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006207}
6208
Chris Lattnerfaa54172010-01-12 21:23:57 +00006209QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006210 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006211 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6212
Richard Trieu859d23f2011-09-06 21:01:04 +00006213 if (LHS.get()->getType()->isVectorType() ||
6214 RHS.get()->getType()->isVectorType()) {
6215 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6216 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006217 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006218 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006219 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006220
Richard Trieuba63ce62011-09-09 01:45:06 +00006221 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006222 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006223 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006224
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006225 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006226 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006227
Chris Lattnerfaa54172010-01-12 21:23:57 +00006228 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006229 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006230 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006231 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6232 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006233
Chris Lattnerfaa54172010-01-12 21:23:57 +00006234 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006235}
6236
Chandler Carruthc9332212011-06-27 08:02:19 +00006237/// \brief Diagnose invalid arithmetic on two void pointers.
6238static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006239 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006240 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006241 ? diag::err_typecheck_pointer_arith_void_type
6242 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006243 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6244 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006245}
6246
6247/// \brief Diagnose invalid arithmetic on a void pointer.
6248static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6249 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006250 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006251 ? diag::err_typecheck_pointer_arith_void_type
6252 : diag::ext_gnu_void_ptr)
6253 << 0 /* one pointer */ << Pointer->getSourceRange();
6254}
6255
6256/// \brief Diagnose invalid arithmetic on two function pointers.
6257static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6258 Expr *LHS, Expr *RHS) {
6259 assert(LHS->getType()->isAnyPointerType());
6260 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006261 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006262 ? diag::err_typecheck_pointer_arith_function_type
6263 : diag::ext_gnu_ptr_func_arith)
6264 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6265 // We only show the second type if it differs from the first.
6266 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6267 RHS->getType())
6268 << RHS->getType()->getPointeeType()
6269 << LHS->getSourceRange() << RHS->getSourceRange();
6270}
6271
6272/// \brief Diagnose invalid arithmetic on a function pointer.
6273static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6274 Expr *Pointer) {
6275 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006276 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006277 ? diag::err_typecheck_pointer_arith_function_type
6278 : diag::ext_gnu_ptr_func_arith)
6279 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6280 << 0 /* one pointer, so only one type */
6281 << Pointer->getSourceRange();
6282}
6283
Richard Trieu993f3ab2011-09-12 18:08:02 +00006284/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006285///
6286/// \returns True if pointer has incomplete type
6287static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6288 Expr *Operand) {
John McCallf2538342012-07-31 05:14:30 +00006289 assert(Operand->getType()->isAnyPointerType() &&
6290 !Operand->getType()->isDependentType());
6291 QualType PointeeTy = Operand->getType()->getPointeeType();
6292 return S.RequireCompleteType(Loc, PointeeTy,
6293 diag::err_typecheck_arithmetic_incomplete_type,
6294 PointeeTy, Operand->getSourceRange());
Richard Trieuaba22802011-09-02 02:15:37 +00006295}
6296
Chandler Carruthc9332212011-06-27 08:02:19 +00006297/// \brief Check the validity of an arithmetic pointer operand.
6298///
6299/// If the operand has pointer type, this code will check for pointer types
6300/// which are invalid in arithmetic operations. These will be diagnosed
6301/// appropriately, including whether or not the use is supported as an
6302/// extension.
6303///
6304/// \returns True when the operand is valid to use (even if as an extension).
6305static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6306 Expr *Operand) {
6307 if (!Operand->getType()->isAnyPointerType()) return true;
6308
6309 QualType PointeeTy = Operand->getType()->getPointeeType();
6310 if (PointeeTy->isVoidType()) {
6311 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006312 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006313 }
6314 if (PointeeTy->isFunctionType()) {
6315 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006316 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006317 }
6318
Richard Trieuaba22802011-09-02 02:15:37 +00006319 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006320
6321 return true;
6322}
6323
6324/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6325/// operands.
6326///
6327/// This routine will diagnose any invalid arithmetic on pointer operands much
6328/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6329/// for emitting a single diagnostic even for operations where both LHS and RHS
6330/// are (potentially problematic) pointers.
6331///
6332/// \returns True when the operand is valid to use (even if as an extension).
6333static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006334 Expr *LHSExpr, Expr *RHSExpr) {
6335 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6336 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006337 if (!isLHSPointer && !isRHSPointer) return true;
6338
6339 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006340 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6341 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006342
6343 // Check for arithmetic on pointers to incomplete types.
6344 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6345 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6346 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006347 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6348 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6349 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006350
David Blaikiebbafb8a2012-03-11 07:00:24 +00006351 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006352 }
6353
6354 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6355 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6356 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006357 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6358 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6359 RHSExpr);
6360 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006361
David Blaikiebbafb8a2012-03-11 07:00:24 +00006362 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006363 }
6364
John McCallf2538342012-07-31 05:14:30 +00006365 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6366 return false;
6367 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6368 return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006369
Chandler Carruthc9332212011-06-27 08:02:19 +00006370 return true;
6371}
6372
Nico Weberccec40d2012-03-02 22:01:22 +00006373/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6374/// literal.
6375static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6376 Expr *LHSExpr, Expr *RHSExpr) {
6377 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6378 Expr* IndexExpr = RHSExpr;
6379 if (!StrExpr) {
6380 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6381 IndexExpr = LHSExpr;
6382 }
6383
6384 bool IsStringPlusInt = StrExpr &&
6385 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6386 if (!IsStringPlusInt)
6387 return;
6388
6389 llvm::APSInt index;
6390 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6391 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6392 if (index.isNonNegative() &&
6393 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6394 index.isUnsigned()))
6395 return;
6396 }
6397
6398 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6399 Self.Diag(OpLoc, diag::warn_string_plus_int)
6400 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6401
6402 // Only print a fixit for "str" + int, not for int + "str".
6403 if (IndexExpr == RHSExpr) {
6404 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6405 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6406 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6407 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6408 << FixItHint::CreateInsertion(EndLoc, "]");
6409 } else
6410 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6411}
6412
Richard Trieu993f3ab2011-09-12 18:08:02 +00006413/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006414static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006415 Expr *LHSExpr, Expr *RHSExpr) {
6416 assert(LHSExpr->getType()->isAnyPointerType());
6417 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006418 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006419 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6420 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006421}
6422
Chris Lattnerfaa54172010-01-12 21:23:57 +00006423QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006424 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6425 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006426 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6427
Richard Trieu4ae7e972011-09-06 21:13:51 +00006428 if (LHS.get()->getType()->isVectorType() ||
6429 RHS.get()->getType()->isVectorType()) {
6430 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006431 if (CompLHSTy) *CompLHSTy = compType;
6432 return compType;
6433 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006434
Richard Trieu4ae7e972011-09-06 21:13:51 +00006435 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6436 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006437 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006438
Nico Weberccec40d2012-03-02 22:01:22 +00006439 // Diagnose "string literal" '+' int.
6440 if (Opc == BO_Add)
6441 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6442
Steve Naroffe4718892007-04-27 18:30:00 +00006443 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006444 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006445 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006446 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006447 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006448
John McCallf2538342012-07-31 05:14:30 +00006449 // Type-checking. Ultimately the pointer's going to be in PExp;
6450 // note that we bias towards the LHS being the pointer.
6451 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedman8e122982008-05-18 18:08:51 +00006452
John McCallf2538342012-07-31 05:14:30 +00006453 bool isObjCPointer;
6454 if (PExp->getType()->isPointerType()) {
6455 isObjCPointer = false;
6456 } else if (PExp->getType()->isObjCObjectPointerType()) {
6457 isObjCPointer = true;
6458 } else {
6459 std::swap(PExp, IExp);
6460 if (PExp->getType()->isPointerType()) {
6461 isObjCPointer = false;
6462 } else if (PExp->getType()->isObjCObjectPointerType()) {
6463 isObjCPointer = true;
6464 } else {
6465 return InvalidOperands(Loc, LHS, RHS);
6466 }
6467 }
6468 assert(PExp->getType()->isAnyPointerType());
Chandler Carruthc9332212011-06-27 08:02:19 +00006469
Richard Trieub420bca2011-09-12 18:37:54 +00006470 if (!IExp->getType()->isIntegerType())
6471 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006472
Richard Trieub420bca2011-09-12 18:37:54 +00006473 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6474 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006475
John McCallf2538342012-07-31 05:14:30 +00006476 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieub420bca2011-09-12 18:37:54 +00006477 return QualType();
6478
6479 // Check array bounds for pointer arithemtic
6480 CheckArrayAccess(PExp, IExp);
6481
6482 if (CompLHSTy) {
6483 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6484 if (LHSTy.isNull()) {
6485 LHSTy = LHS.get()->getType();
6486 if (LHSTy->isPromotableIntegerType())
6487 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006488 }
Richard Trieub420bca2011-09-12 18:37:54 +00006489 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006490 }
6491
Richard Trieub420bca2011-09-12 18:37:54 +00006492 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006493}
6494
Chris Lattner2a3569b2008-04-07 05:30:13 +00006495// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006496QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006497 SourceLocation Loc,
6498 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006499 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6500
Richard Trieu4ae7e972011-09-06 21:13:51 +00006501 if (LHS.get()->getType()->isVectorType() ||
6502 RHS.get()->getType()->isVectorType()) {
6503 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006504 if (CompLHSTy) *CompLHSTy = compType;
6505 return compType;
6506 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006507
Richard Trieu4ae7e972011-09-06 21:13:51 +00006508 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6509 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006510 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006511
Chris Lattner4d62f422007-12-09 21:53:25 +00006512 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006513
Chris Lattner4d62f422007-12-09 21:53:25 +00006514 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006515 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006516 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006517 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006518 }
Mike Stump11289f42009-09-09 15:08:12 +00006519
Chris Lattner4d62f422007-12-09 21:53:25 +00006520 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006521 if (LHS.get()->getType()->isAnyPointerType()) {
6522 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Chris Lattner12bdebb2009-04-24 23:50:08 +00006524 // Diagnose bad cases where we step over interface counts.
John McCallf2538342012-07-31 05:14:30 +00006525 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6526 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006527 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006528
Chris Lattner4d62f422007-12-09 21:53:25 +00006529 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006530 if (RHS.get()->getType()->isIntegerType()) {
6531 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006532 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006533
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006534 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006535 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6536 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006537
Richard Trieu4ae7e972011-09-06 21:13:51 +00006538 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6539 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006540 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006541
Chris Lattner4d62f422007-12-09 21:53:25 +00006542 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006543 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006544 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006545 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006546
David Blaikiebbafb8a2012-03-11 07:00:24 +00006547 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006548 // Pointee types must be the same: C++ [expr.add]
6549 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006550 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006551 }
6552 } else {
6553 // Pointee types must be compatible C99 6.5.6p3
6554 if (!Context.typesAreCompatible(
6555 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6556 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006557 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006558 return QualType();
6559 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006560 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006561
Chandler Carruthc9332212011-06-27 08:02:19 +00006562 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006563 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006564 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006565
Richard Trieu4ae7e972011-09-06 21:13:51 +00006566 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006567 return Context.getPointerDiffType();
6568 }
6569 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006570
Richard Trieu4ae7e972011-09-06 21:13:51 +00006571 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006572}
6573
Douglas Gregor0bf31402010-10-08 23:50:27 +00006574static bool isScopedEnumerationType(QualType T) {
6575 if (const EnumType *ET = dyn_cast<EnumType>(T))
6576 return ET->getDecl()->isScoped();
6577 return false;
6578}
6579
Richard Trieue4a19fb2011-09-06 21:21:28 +00006580static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006581 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006582 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006583 llvm::APSInt Right;
6584 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006585 if (RHS.get()->isValueDependent() ||
6586 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006587 return;
6588
6589 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006590 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006591 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006592 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006593 return;
6594 }
6595 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006596 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006597 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006598 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006599 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006600 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006601 return;
6602 }
6603 if (Opc != BO_Shl)
6604 return;
6605
6606 // When left shifting an ICE which is signed, we can check for overflow which
6607 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6608 // integers have defined behavior modulo one more than the maximum value
6609 // representable in the result type, so never warn for those.
6610 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006611 if (LHS.get()->isValueDependent() ||
6612 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6613 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006614 return;
6615 llvm::APInt ResultBits =
6616 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6617 if (LeftBits.uge(ResultBits))
6618 return;
6619 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6620 Result = Result.shl(Right);
6621
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006622 // Print the bit representation of the signed integer as an unsigned
6623 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006624 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006625 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6626
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006627 // If we are only missing a sign bit, this is less likely to result in actual
6628 // bugs -- if the result is cast back to an unsigned type, it will have the
6629 // expected value. Thus we place this behind a different warning that can be
6630 // turned off separately if needed.
6631 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006632 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006633 << HexResult.str() << LHSType
6634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006635 return;
6636 }
6637
6638 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006639 << HexResult.str() << Result.getMinSignedBits() << LHSType
6640 << Left.getBitWidth() << LHS.get()->getSourceRange()
6641 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006642}
6643
Chris Lattner2a3569b2008-04-07 05:30:13 +00006644// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006645QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006646 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006647 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006648 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6649
Chris Lattner5c11c412007-12-12 05:47:28 +00006650 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006651 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6652 !RHS.get()->getType()->hasIntegerRepresentation())
6653 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006654
Douglas Gregor0bf31402010-10-08 23:50:27 +00006655 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6656 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006657 if (isScopedEnumerationType(LHS.get()->getType()) ||
6658 isScopedEnumerationType(RHS.get()->getType())) {
6659 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006660 }
6661
Nate Begemane46ee9a2009-10-25 02:26:48 +00006662 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006663 if (LHS.get()->getType()->isVectorType() ||
6664 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006665 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006666
Chris Lattner5c11c412007-12-12 05:47:28 +00006667 // Shifts don't perform usual arithmetic conversions, they just do integer
6668 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006669
John McCall57cdd882010-12-16 19:28:59 +00006670 // For the LHS, do usual unary conversions, but then reset them away
6671 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006672 ExprResult OldLHS = LHS;
6673 LHS = UsualUnaryConversions(LHS.take());
6674 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006675 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006676 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006677 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006678
6679 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006680 RHS = UsualUnaryConversions(RHS.take());
6681 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006682 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006683
Ryan Flynnf53fab82009-08-07 16:20:20 +00006684 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006685 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006686
Chris Lattner5c11c412007-12-12 05:47:28 +00006687 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006688 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006689}
6690
Chandler Carruth17773fc2010-07-10 12:30:03 +00006691static bool IsWithinTemplateSpecialization(Decl *D) {
6692 if (DeclContext *DC = D->getDeclContext()) {
6693 if (isa<ClassTemplateSpecializationDecl>(DC))
6694 return true;
6695 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6696 return FD->isFunctionTemplateSpecialization();
6697 }
6698 return false;
6699}
6700
Richard Trieueea56f72011-09-02 03:48:46 +00006701/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006702static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6703 ExprResult &RHS) {
6704 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6705 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006706
6707 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6708 if (!LHSEnumType)
6709 return;
6710 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6711 if (!RHSEnumType)
6712 return;
6713
6714 // Ignore anonymous enums.
6715 if (!LHSEnumType->getDecl()->getIdentifier())
6716 return;
6717 if (!RHSEnumType->getDecl()->getIdentifier())
6718 return;
6719
6720 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6721 return;
6722
6723 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6724 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006726}
6727
Richard Trieudd82a5c2011-09-02 02:55:45 +00006728/// \brief Diagnose bad pointer comparisons.
6729static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006730 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006731 bool IsError) {
6732 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006733 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006734 << LHS.get()->getType() << RHS.get()->getType()
6735 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006736}
6737
6738/// \brief Returns false if the pointers are converted to a composite type,
6739/// true otherwise.
6740static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006741 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006742 // C++ [expr.rel]p2:
6743 // [...] Pointer conversions (4.10) and qualification
6744 // conversions (4.4) are performed on pointer operands (or on
6745 // a pointer operand and a null pointer constant) to bring
6746 // them to their composite pointer type. [...]
6747 //
6748 // C++ [expr.eq]p1 uses the same notion for (in)equality
6749 // comparisons of pointers.
6750
6751 // C++ [expr.eq]p2:
6752 // In addition, pointers to members can be compared, or a pointer to
6753 // member and a null pointer constant. Pointer to member conversions
6754 // (4.11) and qualification conversions (4.4) are performed to bring
6755 // them to a common type. If one operand is a null pointer constant,
6756 // the common type is the type of the other operand. Otherwise, the
6757 // common type is a pointer to member type similar (4.4) to the type
6758 // of one of the operands, with a cv-qualification signature (4.4)
6759 // that is the union of the cv-qualification signatures of the operand
6760 // types.
6761
Richard Trieu1762d7c2011-09-06 21:27:33 +00006762 QualType LHSType = LHS.get()->getType();
6763 QualType RHSType = RHS.get()->getType();
6764 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6765 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006766
6767 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006768 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006769 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006770 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006771 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006772 return true;
6773 }
6774
6775 if (NonStandardCompositeType)
6776 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006777 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6778 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006779
Richard Trieu1762d7c2011-09-06 21:27:33 +00006780 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6781 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006782 return false;
6783}
6784
6785static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006786 ExprResult &LHS,
6787 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006788 bool IsError) {
6789 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6790 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006791 << LHS.get()->getType() << RHS.get()->getType()
6792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006793}
6794
Jordan Rosed49a33e2012-06-08 21:14:25 +00006795static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rosee2028132012-11-09 23:55:21 +00006796 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rosed49a33e2012-06-08 21:14:25 +00006797 case Stmt::ObjCArrayLiteralClass:
6798 case Stmt::ObjCDictionaryLiteralClass:
6799 case Stmt::ObjCStringLiteralClass:
6800 case Stmt::ObjCBoxedExprClass:
6801 return true;
6802 default:
6803 // Note that ObjCBoolLiteral is NOT an object literal!
6804 return false;
6805 }
6806}
6807
Jordan Rose7660f782012-07-17 17:46:40 +00006808static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6809 // Get the LHS object's interface type.
6810 QualType Type = LHS->getType();
6811 QualType InterfaceType;
6812 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6813 InterfaceType = PTy->getPointeeType();
6814 if (const ObjCObjectType *iQFaceTy =
6815 InterfaceType->getAsObjCQualifiedInterfaceType())
6816 InterfaceType = iQFaceTy->getBaseType();
6817 } else {
6818 // If this is not actually an Objective-C object, bail out.
6819 return false;
6820 }
6821
6822 // If the RHS isn't an Objective-C object, bail out.
6823 if (!RHS->getType()->isObjCObjectPointerType())
6824 return false;
6825
6826 // Try to find the -isEqual: method.
6827 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6828 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6829 InterfaceType,
6830 /*instance=*/true);
6831 if (!Method) {
6832 if (Type->isObjCIdType()) {
6833 // For 'id', just check the global pool.
6834 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6835 /*receiverId=*/true,
6836 /*warn=*/false);
6837 } else {
6838 // Check protocols.
6839 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6840 cast<ObjCObjectPointerType>(Type),
6841 /*instance=*/true);
6842 }
6843 }
6844
6845 if (!Method)
6846 return false;
6847
6848 QualType T = Method->param_begin()[0]->getType();
6849 if (!T->isObjCObjectPointerType())
6850 return false;
6851
6852 QualType R = Method->getResultType();
6853 if (!R->isScalarType())
6854 return false;
6855
6856 return true;
6857}
6858
6859static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6860 ExprResult &LHS, ExprResult &RHS,
6861 BinaryOperator::Opcode Opc){
Jordan Rose63ffaa82012-07-17 17:46:48 +00006862 Expr *Literal;
6863 Expr *Other;
6864 if (isObjCObjectLiteral(LHS)) {
6865 Literal = LHS.get();
6866 Other = RHS.get();
6867 } else {
6868 Literal = RHS.get();
6869 Other = LHS.get();
6870 }
6871
6872 // Don't warn on comparisons against nil.
6873 Other = Other->IgnoreParenCasts();
6874 if (Other->isNullPointerConstant(S.getASTContext(),
6875 Expr::NPC_ValueDependentIsNotNull))
6876 return;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006877
Jordan Roseea70bf72012-07-17 17:46:44 +00006878 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rose63ffaa82012-07-17 17:46:48 +00006879 // LK_String should always be last, since it has its own warning flag.
Jordan Roseea70bf72012-07-17 17:46:44 +00006880 enum {
6881 LK_Array,
6882 LK_Dictionary,
6883 LK_Numeric,
6884 LK_Boxed,
6885 LK_String
6886 } LiteralKind;
6887
Jordan Rosee2028132012-11-09 23:55:21 +00006888 Literal = Literal->IgnoreParenImpCasts();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006889 switch (Literal->getStmtClass()) {
6890 case Stmt::ObjCStringLiteralClass:
6891 // "string literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006892 LiteralKind = LK_String;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006893 break;
6894 case Stmt::ObjCArrayLiteralClass:
6895 // "array literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006896 LiteralKind = LK_Array;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006897 break;
6898 case Stmt::ObjCDictionaryLiteralClass:
6899 // "dictionary literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006900 LiteralKind = LK_Dictionary;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006901 break;
6902 case Stmt::ObjCBoxedExprClass: {
6903 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6904 switch (Inner->getStmtClass()) {
6905 case Stmt::IntegerLiteralClass:
6906 case Stmt::FloatingLiteralClass:
6907 case Stmt::CharacterLiteralClass:
6908 case Stmt::ObjCBoolLiteralExprClass:
6909 case Stmt::CXXBoolLiteralExprClass:
6910 // "numeric literal"
Jordan Roseea70bf72012-07-17 17:46:44 +00006911 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006912 break;
6913 case Stmt::ImplicitCastExprClass: {
6914 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6915 // Boolean literals can be represented by implicit casts.
6916 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseea70bf72012-07-17 17:46:44 +00006917 LiteralKind = LK_Numeric;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006918 break;
6919 }
6920 // FALLTHROUGH
6921 }
6922 default:
6923 // "boxed expression"
Jordan Roseea70bf72012-07-17 17:46:44 +00006924 LiteralKind = LK_Boxed;
Jordan Rosed49a33e2012-06-08 21:14:25 +00006925 break;
6926 }
6927 break;
6928 }
6929 default:
6930 llvm_unreachable("Unknown Objective-C object literal kind");
6931 }
6932
Jordan Roseea70bf72012-07-17 17:46:44 +00006933 if (LiteralKind == LK_String)
6934 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6935 << Literal->getSourceRange();
6936 else
6937 S.Diag(Loc, diag::warn_objc_literal_comparison)
6938 << LiteralKind << Literal->getSourceRange();
Jordan Rosed49a33e2012-06-08 21:14:25 +00006939
Jordan Rose7660f782012-07-17 17:46:40 +00006940 if (BinaryOperator::isEqualityOp(Opc) &&
6941 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6942 SourceLocation Start = LHS.get()->getLocStart();
6943 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6944 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rosef9198032012-07-09 16:54:44 +00006945
Jordan Rose7660f782012-07-17 17:46:40 +00006946 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6947 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6948 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6949 << FixItHint::CreateInsertion(End, "]");
Jordan Rosed49a33e2012-06-08 21:14:25 +00006950 }
Jordan Rosed49a33e2012-06-08 21:14:25 +00006951}
6952
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006953// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006954QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006955 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006956 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006957 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6958
John McCalle3027922010-08-25 11:45:40 +00006959 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006960
Chris Lattner9a152e22009-12-05 05:40:13 +00006961 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006962 if (LHS.get()->getType()->isVectorType() ||
6963 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006964 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006965
Richard Trieub80728f2011-09-06 21:43:51 +00006966 QualType LHSType = LHS.get()->getType();
6967 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006968
Richard Trieub80728f2011-09-06 21:43:51 +00006969 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6970 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006971
Richard Trieub80728f2011-09-06 21:43:51 +00006972 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006973
Richard Trieub80728f2011-09-06 21:43:51 +00006974 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006975 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006976 !LHS.get()->getLocStart().isMacroID() &&
6977 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006978 // For non-floating point types, check for self-comparisons of the form
6979 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6980 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006981 //
6982 // NOTE: Don't warn about comparison expressions resulting from macro
6983 // expansion. Also don't warn about comparisons which are only self
6984 // comparisons within a template specialization. The warnings should catch
6985 // obvious cases in the definition of the template anyways. The idea is to
6986 // warn when the typed comparison operator will always evaluate to the same
6987 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006988 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006989 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006990 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006991 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006992 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006993 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006994 << (Opc == BO_EQ
6995 || Opc == BO_LE
6996 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006997 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006998 !DRL->getDecl()->getType()->isReferenceType() &&
6999 !DRR->getDecl()->getType()->isReferenceType()) {
7000 // what is it always going to eval to?
7001 char always_evals_to;
7002 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007003 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007004 always_evals_to = 0; // false
7005 break;
John McCalle3027922010-08-25 11:45:40 +00007006 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007007 always_evals_to = 1; // true
7008 break;
7009 default:
7010 // best we can say is 'a constant'
7011 always_evals_to = 2; // e.g. array1 <= array2
7012 break;
7013 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007014 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007015 << 1 // array
7016 << always_evals_to);
7017 }
7018 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007019 }
Mike Stump11289f42009-09-09 15:08:12 +00007020
Chris Lattner222b8bd2009-03-08 19:39:53 +00007021 if (isa<CastExpr>(LHSStripped))
7022 LHSStripped = LHSStripped->IgnoreParenCasts();
7023 if (isa<CastExpr>(RHSStripped))
7024 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007025
Chris Lattner222b8bd2009-03-08 19:39:53 +00007026 // Warn about comparisons against a string constant (unless the other
7027 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007028 Expr *literalString = 0;
7029 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007030 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007031 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007032 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007033 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007034 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007035 } else if ((isa<StringLiteral>(RHSStripped) ||
7036 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007037 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007038 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00007039 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007040 literalStringStripped = RHSStripped;
7041 }
7042
7043 if (literalString) {
7044 std::string resultComparison;
7045 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007046 case BO_LT: resultComparison = ") < 0"; break;
7047 case BO_GT: resultComparison = ") > 0"; break;
7048 case BO_LE: resultComparison = ") <= 0"; break;
7049 case BO_GE: resultComparison = ") >= 0"; break;
7050 case BO_EQ: resultComparison = ") == 0"; break;
7051 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00007052 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007053 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007054
Ted Kremenek3427fac2011-02-23 01:52:04 +00007055 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007056 PDiag(diag::warn_stringcompare)
7057 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007058 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007059 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007060 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007061
Douglas Gregorec170db2010-06-08 19:50:34 +00007062 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00007063 if (LHS.get()->getType()->isArithmeticType() &&
7064 RHS.get()->getType()->isArithmeticType()) {
7065 UsualArithmeticConversions(LHS, RHS);
7066 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007067 return QualType();
7068 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007069 else {
Richard Trieub80728f2011-09-06 21:43:51 +00007070 LHS = UsualUnaryConversions(LHS.take());
7071 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007072 return QualType();
7073
Richard Trieub80728f2011-09-06 21:43:51 +00007074 RHS = UsualUnaryConversions(RHS.take());
7075 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007076 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007077 }
7078
Richard Trieub80728f2011-09-06 21:43:51 +00007079 LHSType = LHS.get()->getType();
7080 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007081
Douglas Gregorca63811b2008-11-19 03:25:36 +00007082 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007083 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007084
Richard Trieuba63ce62011-09-09 01:45:06 +00007085 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00007086 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007087 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007088 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007089 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00007090 if (LHSType->hasFloatingRepresentation())
7091 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007092
Richard Trieub80728f2011-09-06 21:43:51 +00007093 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007094 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007095 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007096
Richard Trieub80728f2011-09-06 21:43:51 +00007097 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007098 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00007099 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007100 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007101
Douglas Gregorf267edd2010-06-15 21:38:40 +00007102 // All of the following pointer-related warnings are GCC extensions, except
7103 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00007104 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007105 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007106 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00007107 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00007108 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007109
David Blaikiebbafb8a2012-03-11 07:00:24 +00007110 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007111 if (LCanPointeeTy == RCanPointeeTy)
7112 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00007113 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007114 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7115 // Valid unless comparison between non-null pointer and function pointer
7116 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007117 // In a SFINAE context, we treat this as a hard error to maintain
7118 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007119 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7120 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00007121 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00007122 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00007123
7124 if (isSFINAEContext())
7125 return QualType();
7126
Richard Trieub80728f2011-09-06 21:43:51 +00007127 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007128 return ResultTy;
7129 }
7130 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007131
Richard Trieub80728f2011-09-06 21:43:51 +00007132 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007133 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007134 else
7135 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007136 }
Eli Friedman16c209612009-08-23 00:27:47 +00007137 // C99 6.5.9p2 and C99 6.5.8p2
7138 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7139 RCanPointeeTy.getUnqualifiedType())) {
7140 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00007141 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00007142 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00007143 << LHSType << RHSType << LHS.get()->getSourceRange()
7144 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007145 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007146 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00007147 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7148 // Valid unless comparison between non-null pointer and function pointer
7149 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00007150 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007151 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007152 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00007153 } else {
7154 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00007155 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00007156 }
John McCall7684dde2011-03-11 04:25:25 +00007157 if (LCanPointeeTy != RCanPointeeTy) {
7158 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007159 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007160 else
Richard Trieub80728f2011-09-06 21:43:51 +00007161 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007162 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007163 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007164 }
Mike Stump11289f42009-09-09 15:08:12 +00007165
David Blaikiebbafb8a2012-03-11 07:00:24 +00007166 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007167 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00007168 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00007169 return ResultTy;
7170
Mike Stump11289f42009-09-09 15:08:12 +00007171 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007172 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007173 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007174 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007175 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007176 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7177 RHS = ImpCastExprToType(RHS.take(), LHSType,
7178 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007179 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007180 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007181 return ResultTy;
7182 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007183 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00007184 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00007185 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007186 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7187 LHS = ImpCastExprToType(LHS.take(), RHSType,
7188 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007189 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007190 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007191 return ResultTy;
7192 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007193
7194 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007195 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00007196 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7197 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007198 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00007199 else
7200 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007201 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007202
7203 // Handle scoped enumeration types specifically, since they don't promote
7204 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007205 if (LHS.get()->getType()->isEnumeralType() &&
7206 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7207 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007208 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007209 }
Mike Stump11289f42009-09-09 15:08:12 +00007210
Steve Naroff081c7422008-09-04 15:10:53 +00007211 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007212 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007213 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007214 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7215 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007216
Steve Naroff081c7422008-09-04 15:10:53 +00007217 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007218 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007219 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007220 << LHSType << RHSType << LHS.get()->getSourceRange()
7221 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007222 }
Richard Trieub80728f2011-09-06 21:43:51 +00007223 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007224 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007225 }
John Wiegley01296292011-04-08 18:41:53 +00007226
Steve Naroffe18f94c2008-09-28 01:11:11 +00007227 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007228 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007229 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7230 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007231 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007232 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007233 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007234 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007235 ->getPointeeType()->isVoidType())))
7236 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007237 << LHSType << RHSType << LHS.get()->getSourceRange()
7238 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007239 }
John McCall7684dde2011-03-11 04:25:25 +00007240 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007241 LHS = ImpCastExprToType(LHS.take(), RHSType,
7242 RHSType->isPointerType() ? CK_BitCast
7243 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007244 else
John McCall9320b872011-09-09 05:25:32 +00007245 RHS = ImpCastExprToType(RHS.take(), LHSType,
7246 LHSType->isPointerType() ? CK_BitCast
7247 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007248 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007249 }
Steve Naroff081c7422008-09-04 15:10:53 +00007250
Richard Trieub80728f2011-09-06 21:43:51 +00007251 if (LHSType->isObjCObjectPointerType() ||
7252 RHSType->isObjCObjectPointerType()) {
7253 const PointerType *LPT = LHSType->getAs<PointerType>();
7254 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007255 if (LPT || RPT) {
7256 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7257 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007258
Steve Naroff753567f2008-11-17 19:49:16 +00007259 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007260 !Context.typesAreCompatible(LHSType, RHSType)) {
7261 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007262 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007263 }
John McCall7684dde2011-03-11 04:25:25 +00007264 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007265 LHS = ImpCastExprToType(LHS.take(), RHSType,
7266 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007267 else
John McCall9320b872011-09-09 05:25:32 +00007268 RHS = ImpCastExprToType(RHS.take(), LHSType,
7269 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007270 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007271 }
Richard Trieub80728f2011-09-06 21:43:51 +00007272 if (LHSType->isObjCObjectPointerType() &&
7273 RHSType->isObjCObjectPointerType()) {
7274 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7275 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007276 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007277 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose7660f782012-07-17 17:46:40 +00007278 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007279
John McCall7684dde2011-03-11 04:25:25 +00007280 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007281 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007282 else
Richard Trieub80728f2011-09-06 21:43:51 +00007283 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007284 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007285 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007286 }
Richard Trieub80728f2011-09-06 21:43:51 +00007287 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7288 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007289 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007290 bool isError = false;
Douglas Gregor0064c592012-09-14 04:35:37 +00007291 if (LangOpts.DebuggerSupport) {
7292 // Under a debugger, allow the comparison of pointers to integers,
7293 // since users tend to want to compare addresses.
7294 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieub80728f2011-09-06 21:43:51 +00007295 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007296 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007297 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007298 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007299 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007300 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007301 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7302 isError = true;
7303 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007304 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007305
Chris Lattnerd99bd522009-08-23 00:03:44 +00007306 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007307 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007308 << LHSType << RHSType << LHS.get()->getSourceRange()
7309 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007310 if (isError)
7311 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007312 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007313
Richard Trieub80728f2011-09-06 21:43:51 +00007314 if (LHSType->isIntegerType())
7315 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007316 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007317 else
Richard Trieub80728f2011-09-06 21:43:51 +00007318 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007319 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007320 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007321 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007322
Steve Naroff4b191572008-09-04 16:56:14 +00007323 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007324 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007325 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7326 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007327 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007328 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007329 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007330 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7331 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007332 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007333 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007334
Richard Trieub80728f2011-09-06 21:43:51 +00007335 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007336}
7337
Tanya Lattner20248222012-01-16 21:02:28 +00007338
7339// Return a signed type that is of identical size and number of elements.
7340// For floating point vectors, return an integer type of identical size
7341// and number of elements.
7342QualType Sema::GetSignedVectorType(QualType V) {
7343 const VectorType *VTy = V->getAs<VectorType>();
7344 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7345 if (TypeSize == Context.getTypeSize(Context.CharTy))
7346 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7347 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7348 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7349 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7350 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7351 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7352 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7353 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7354 "Unhandled vector element size in vector compare");
7355 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7356}
7357
Nate Begeman191a6b12008-07-14 18:02:46 +00007358/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007359/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007360/// like a scalar comparison, a vector comparison produces a vector of integer
7361/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007362QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007363 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007364 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007365 // Check to make sure we're operating on vectors of the same type and width,
7366 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007367 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007368 if (vType.isNull())
7369 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007370
Richard Trieubcce2f72011-09-07 01:19:57 +00007371 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007372
Anton Yartsev530deb92011-03-27 15:36:07 +00007373 // If AltiVec, the comparison results in a numeric type, i.e.
7374 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007375 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007376 return Context.getLogicalOperationType();
7377
Nate Begeman191a6b12008-07-14 18:02:46 +00007378 // For non-floating point types, check for self-comparisons of the form
7379 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7380 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007381 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007382 if (DeclRefExpr* DRL
7383 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7384 if (DeclRefExpr* DRR
7385 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007386 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007387 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007388 PDiag(diag::warn_comparison_always)
7389 << 0 // self-
7390 << 2 // "a constant"
7391 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007392 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007393
Nate Begeman191a6b12008-07-14 18:02:46 +00007394 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007395 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007396 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007397 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007398 }
Tanya Lattner20248222012-01-16 21:02:28 +00007399
7400 // Return a signed type for the vector.
7401 return GetSignedVectorType(LHSType);
7402}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007403
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007404QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7405 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007406 // Ensure that either both operands are of the same vector type, or
7407 // one operand is of a vector type and the other is of its element type.
7408 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7409 if (vType.isNull() || vType->isFloatingType())
7410 return InvalidOperands(Loc, LHS, RHS);
7411
7412 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007413}
7414
Steve Naroff218bc2b2007-05-04 21:54:46 +00007415inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007416 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007417 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7418
Richard Trieubcce2f72011-09-07 01:19:57 +00007419 if (LHS.get()->getType()->isVectorType() ||
7420 RHS.get()->getType()->isVectorType()) {
7421 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7422 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007423 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007424
Richard Trieubcce2f72011-09-07 01:19:57 +00007425 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007426 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007427
Richard Trieubcce2f72011-09-07 01:19:57 +00007428 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7429 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007430 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007431 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007432 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007433 LHS = LHSResult.take();
7434 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007435
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007436 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007437 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007438 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007439}
7440
Steve Naroff218bc2b2007-05-04 21:54:46 +00007441inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007442 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007443
Tanya Lattner20248222012-01-16 21:02:28 +00007444 // Check vector operands differently.
7445 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7446 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7447
Chris Lattner8406c512010-07-13 19:41:32 +00007448 // Diagnose cases where the user write a logical and/or but probably meant a
7449 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7450 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007451 if (LHS.get()->getType()->isIntegerType() &&
7452 !LHS.get()->getType()->isBooleanType() &&
7453 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007454 // Don't warn in macros or template instantiations.
7455 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007456 // If the RHS can be constant folded, and if it constant folds to something
7457 // that isn't 0 or 1 (which indicate a potential logical operation that
7458 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007459 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007460 llvm::APSInt Result;
7461 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007462 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007463 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007464 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007465 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007466 << (Opc == BO_LAnd ? "&&" : "||");
7467 // Suggest replacing the logical operator with the bitwise version
7468 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7469 << (Opc == BO_LAnd ? "&" : "|")
7470 << FixItHint::CreateReplacement(SourceRange(
7471 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007472 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007473 Opc == BO_LAnd ? "&" : "|");
7474 if (Opc == BO_LAnd)
7475 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7476 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7477 << FixItHint::CreateRemoval(
7478 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007479 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007480 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007481 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007482 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007483 }
Chris Lattner938533d2010-07-24 01:10:11 +00007484 }
Chris Lattner8406c512010-07-13 19:41:32 +00007485
David Blaikiebbafb8a2012-03-11 07:00:24 +00007486 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007487 LHS = UsualUnaryConversions(LHS.take());
7488 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007489 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007490
Richard Trieubcce2f72011-09-07 01:19:57 +00007491 RHS = UsualUnaryConversions(RHS.take());
7492 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007493 return QualType();
7494
Richard Trieubcce2f72011-09-07 01:19:57 +00007495 if (!LHS.get()->getType()->isScalarType() ||
7496 !RHS.get()->getType()->isScalarType())
7497 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007498
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007499 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007500 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007501
John McCall4a2429a2010-06-04 00:29:51 +00007502 // The following is safe because we only use this method for
7503 // non-overloadable operands.
7504
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007505 // C++ [expr.log.and]p1
7506 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007507 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007508 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7509 if (LHSRes.isInvalid())
7510 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007511 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00007512
Richard Trieubcce2f72011-09-07 01:19:57 +00007513 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7514 if (RHSRes.isInvalid())
7515 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007516 RHS = RHSRes;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007517
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007518 // C++ [expr.log.and]p2
7519 // C++ [expr.log.or]p2
7520 // The result is a bool.
7521 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007522}
7523
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007524/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7525/// is a read-only property; return true if so. A readonly property expression
7526/// depends on various declarations and thus must be treated specially.
7527///
Mike Stump11289f42009-09-09 15:08:12 +00007528static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007529 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7530 if (!PropExpr) return false;
7531 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007532
John McCall526ab472011-10-25 17:37:35 +00007533 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7534 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007535 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007536 PropExpr->getBase()->getType();
7537
John McCall526ab472011-10-25 17:37:35 +00007538 if (const ObjCObjectPointerType *OPT =
7539 BaseType->getAsObjCInterfacePointerType())
7540 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7541 if (S.isPropertyReadonly(PDecl, IFace))
7542 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007543 return false;
7544}
7545
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007546static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007547 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7548 if (!ME) return false;
7549 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7550 ObjCMessageExpr *Base =
7551 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7552 if (!Base) return false;
7553 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007554}
7555
John McCall5fa2ef42012-03-13 00:37:01 +00007556/// Is the given expression (which must be 'const') a reference to a
7557/// variable which was originally non-const, but which has become
7558/// 'const' due to being captured within a block?
7559enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7560static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7561 assert(E->isLValue() && E->getType().isConstQualified());
7562 E = E->IgnoreParens();
7563
7564 // Must be a reference to a declaration from an enclosing scope.
7565 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7566 if (!DRE) return NCCK_None;
7567 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7568
7569 // The declaration must be a variable which is not declared 'const'.
7570 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7571 if (!var) return NCCK_None;
7572 if (var->getType().isConstQualified()) return NCCK_None;
7573 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7574
7575 // Decide whether the first capture was for a block or a lambda.
7576 DeclContext *DC = S.CurContext;
7577 while (DC->getParent() != var->getDeclContext())
7578 DC = DC->getParent();
7579 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7580}
7581
Chris Lattner30bd3272008-11-18 01:22:49 +00007582/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7583/// emit an error and return true. If so, return false.
7584static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007585 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007586 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007587 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007588 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007589 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7590 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007591 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7592 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007593 if (IsLV == Expr::MLV_Valid)
7594 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007595
Chris Lattner30bd3272008-11-18 01:22:49 +00007596 unsigned Diag = 0;
7597 bool NeedType = false;
7598 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007599 case Expr::MLV_ConstQualified:
7600 Diag = diag::err_typecheck_assign_const;
7601
John McCall5fa2ef42012-03-13 00:37:01 +00007602 // Use a specialized diagnostic when we're assigning to an object
7603 // from an enclosing function or block.
7604 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7605 if (NCCK == NCCK_Block)
7606 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7607 else
7608 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7609 break;
7610 }
7611
John McCalld4631322011-06-17 06:42:21 +00007612 // In ARC, use some specialized diagnostics for occasions where we
7613 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007614 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007615 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7616 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7617 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7618
John McCalld4631322011-06-17 06:42:21 +00007619 // Use the normal diagnostic if it's pseudo-__strong but the
7620 // user actually wrote 'const'.
7621 if (var->isARCPseudoStrong() &&
7622 (!var->getTypeSourceInfo() ||
7623 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7624 // There are two pseudo-strong cases:
7625 // - self
John McCall31168b02011-06-15 23:02:42 +00007626 ObjCMethodDecl *method = S.getCurMethodDecl();
7627 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007628 Diag = method->isClassMethod()
7629 ? diag::err_typecheck_arc_assign_self_class_method
7630 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007631
7632 // - fast enumeration variables
7633 else
John McCall31168b02011-06-15 23:02:42 +00007634 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007635
John McCall31168b02011-06-15 23:02:42 +00007636 SourceRange Assign;
7637 if (Loc != OrigLoc)
7638 Assign = SourceRange(OrigLoc, OrigLoc);
7639 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7640 // We need to preserve the AST regardless, so migration tool
7641 // can do its job.
7642 return false;
7643 }
7644 }
7645 }
7646
7647 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007648 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007649 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007650 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7651 NeedType = true;
7652 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007653 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007654 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7655 NeedType = true;
7656 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007657 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007658 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7659 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007660 case Expr::MLV_Valid:
7661 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007662 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007663 case Expr::MLV_MemberFunction:
7664 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007665 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7666 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007667 case Expr::MLV_IncompleteType:
7668 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007669 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007670 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007671 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007672 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7673 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007674 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007675 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007676 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007677 case Expr::MLV_InvalidMessageExpression:
7678 Diag = diag::error_readonly_message_assignment;
7679 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007680 case Expr::MLV_SubObjCPropertySetting:
7681 Diag = diag::error_no_subobject_property_setting;
7682 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007683 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007684
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007685 SourceRange Assign;
7686 if (Loc != OrigLoc)
7687 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007688 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007689 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007690 else
Mike Stump11289f42009-09-09 15:08:12 +00007691 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007692 return true;
7693}
7694
Nico Weberb8124d12012-07-03 02:03:06 +00007695static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7696 SourceLocation Loc,
7697 Sema &Sema) {
7698 // C / C++ fields
Nico Weber33fd5232012-06-28 23:53:12 +00007699 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7700 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7701 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7702 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weberb8124d12012-07-03 02:03:06 +00007703 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber33fd5232012-06-28 23:53:12 +00007704 }
Chris Lattner30bd3272008-11-18 01:22:49 +00007705
Nico Weberb8124d12012-07-03 02:03:06 +00007706 // Objective-C instance variables
Nico Weber33fd5232012-06-28 23:53:12 +00007707 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7708 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7709 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7710 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7711 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7712 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weberb8124d12012-07-03 02:03:06 +00007713 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber33fd5232012-06-28 23:53:12 +00007714 }
7715}
Chris Lattner30bd3272008-11-18 01:22:49 +00007716
7717// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007718QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007719 SourceLocation Loc,
7720 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007721 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7722
Chris Lattner326f7572008-11-18 01:30:42 +00007723 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007724 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007725 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007726
Richard Trieuda4f43a62011-09-07 01:33:52 +00007727 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007728 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7729 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007730 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007731 if (CompoundType.isNull()) {
Nico Weber33fd5232012-06-28 23:53:12 +00007732 Expr *RHSCheck = RHS.get();
7733
Nico Weberb8124d12012-07-03 02:03:06 +00007734 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber33fd5232012-06-28 23:53:12 +00007735
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007736 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007737 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007738 if (RHS.isInvalid())
7739 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007740 // Special case of NSObject attributes on c-style pointer types.
7741 if (ConvTy == IncompatiblePointer &&
7742 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007743 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007744 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007745 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007746 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007747
John McCall7decc9e2010-11-18 06:31:45 +00007748 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007749 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007750 Diag(Loc, diag::err_objc_object_assignment)
7751 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007752
Chris Lattnerea714382008-08-21 18:04:13 +00007753 // If the RHS is a unary plus or minus, check to see if they = and + are
7754 // right next to each other. If so, the user may have typo'd "x =+ 4"
7755 // instead of "x += 4".
Chris Lattnerea714382008-08-21 18:04:13 +00007756 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7757 RHSCheck = ICE->getSubExpr();
7758 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007759 if ((UO->getOpcode() == UO_Plus ||
7760 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007761 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007762 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007763 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007764 // And there is a space or other character before the subexpr of the
7765 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007766 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007767 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007768 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007769 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007770 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007771 }
Chris Lattnerea714382008-08-21 18:04:13 +00007772 }
John McCall31168b02011-06-15 23:02:42 +00007773
7774 if (ConvTy == Compatible) {
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007775 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7776 // Warn about retain cycles where a block captures the LHS, but
7777 // not if the LHS is a simple variable into which the block is
7778 // being stored...unless that variable can be captured by reference!
7779 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7780 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7781 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7782 checkRetainCycles(LHSExpr, RHS.get());
7783
Jordan Rosed3934582012-09-28 22:21:30 +00007784 // It is safe to assign a weak reference into a strong variable.
7785 // Although this code can still have problems:
7786 // id x = self.weakProp;
7787 // id y = self.weakProp;
7788 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7789 // paths through the function. This should be revisited if
7790 // -Wrepeated-use-of-weak is made flow-sensitive.
7791 DiagnosticsEngine::Level Level =
7792 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7793 RHS.get()->getLocStart());
7794 if (Level != DiagnosticsEngine::Ignored)
7795 getCurFunction()->markSafeWeakUse(RHS.get());
7796
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007797 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieuda4f43a62011-09-07 01:33:52 +00007798 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007799 }
John McCall31168b02011-06-15 23:02:42 +00007800 }
Chris Lattnerea714382008-08-21 18:04:13 +00007801 } else {
7802 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007803 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007804 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007805
Chris Lattner326f7572008-11-18 01:30:42 +00007806 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007807 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007808 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007809
Richard Trieuda4f43a62011-09-07 01:33:52 +00007810 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007811
Steve Naroff98cf3e92007-06-06 18:38:38 +00007812 // C99 6.5.16p3: The type of an assignment expression is the type of the
7813 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007814 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007815 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7816 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007817 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007818 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007819 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007820 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007821}
7822
Chris Lattner326f7572008-11-18 01:30:42 +00007823// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007824static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007825 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007826 LHS = S.CheckPlaceholderExpr(LHS.take());
7827 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007828 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007829 return QualType();
7830
John McCall73d36182010-10-12 07:14:40 +00007831 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7832 // operands, but not unary promotions.
7833 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007834
John McCall34376a62010-12-04 03:47:34 +00007835 // So we treat the LHS as a ignored value, and in C++ we allow the
7836 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007837 LHS = S.IgnoredValueConversions(LHS.take());
7838 if (LHS.isInvalid())
7839 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007840
Eli Friedmanc11535c2012-05-24 00:47:05 +00007841 S.DiagnoseUnusedExprResult(LHS.get());
7842
David Blaikiebbafb8a2012-03-11 07:00:24 +00007843 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007844 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7845 if (RHS.isInvalid())
7846 return QualType();
7847 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007848 S.RequireCompleteType(Loc, RHS.get()->getType(),
7849 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007850 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007851
John Wiegley01296292011-04-08 18:41:53 +00007852 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007853}
7854
Steve Naroff7a5af782007-07-13 16:58:59 +00007855/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7856/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007857static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7858 ExprValueKind &VK,
7859 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007860 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007861 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007862 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007863
Chris Lattner6b0cf142008-11-21 07:05:48 +00007864 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007865 // Atomic types can be used for increment / decrement where the non-atomic
7866 // versions can, so ignore the _Atomic() specifier for the purpose of
7867 // checking.
7868 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7869 ResType = ResAtomicType->getValueType();
7870
Chris Lattner6b0cf142008-11-21 07:05:48 +00007871 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007872
David Blaikiebbafb8a2012-03-11 07:00:24 +00007873 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007874 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007875 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007876 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007877 return QualType();
7878 }
7879 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007880 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007881 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007882 // OK!
John McCallf2538342012-07-31 05:14:30 +00007883 } else if (ResType->isPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007884 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007885 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007886 return QualType();
John McCallf2538342012-07-31 05:14:30 +00007887 } else if (ResType->isObjCObjectPointerType()) {
7888 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7889 // Otherwise, we just need a complete type.
7890 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7891 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7892 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007893 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007894 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007895 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007896 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007897 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007898 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007899 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007900 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007901 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007902 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007903 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007904 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007905 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007906 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007907 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007908 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007909 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007910 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007911 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007912 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007913 // In C++, a prefix increment is the same type as the operand. Otherwise
7914 // (in C or with postfix), the increment is the unqualified type of the
7915 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007916 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007917 VK = VK_LValue;
7918 return ResType;
7919 } else {
7920 VK = VK_RValue;
7921 return ResType.getUnqualifiedType();
7922 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007923}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007924
7925
Anders Carlsson806700f2008-02-01 07:15:58 +00007926/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007927/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007928/// where the declaration is needed for type checking. We only need to
7929/// handle cases when the expression references a function designator
7930/// or is an lvalue. Here are some examples:
7931/// - &(x) => x
7932/// - &*****f => f for f a function designator.
7933/// - &s.xx => s
7934/// - &s.zz[1].yy -> s, if zz is an array
7935/// - *(x + 1) -> x, if x is an array
7936/// - &"123"[2] -> 0
7937/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007938static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007939 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007940 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007941 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007942 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007943 // If this is an arrow operator, the address is an offset from
7944 // the base's value, so the object the base refers to is
7945 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007946 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007947 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007948 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007949 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007950 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007951 // FIXME: This code shouldn't be necessary! We should catch the implicit
7952 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007953 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7954 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7955 if (ICE->getSubExpr()->getType()->isArrayType())
7956 return getPrimaryDecl(ICE->getSubExpr());
7957 }
7958 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007959 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007960 case Stmt::UnaryOperatorClass: {
7961 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007962
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007963 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007964 case UO_Real:
7965 case UO_Imag:
7966 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007967 return getPrimaryDecl(UO->getSubExpr());
7968 default:
7969 return 0;
7970 }
7971 }
Steve Naroff47500512007-04-19 23:00:49 +00007972 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007973 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007974 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007975 // If the result of an implicit cast is an l-value, we care about
7976 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007977 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007978 default:
7979 return 0;
7980 }
7981}
7982
Richard Trieu5f376f62011-09-07 21:46:33 +00007983namespace {
7984 enum {
7985 AO_Bit_Field = 0,
7986 AO_Vector_Element = 1,
7987 AO_Property_Expansion = 2,
7988 AO_Register_Variable = 3,
7989 AO_No_Error = 4
7990 };
7991}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007992/// \brief Diagnose invalid operand for address of operations.
7993///
7994/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007995static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7996 Expr *E, unsigned Type) {
7997 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7998}
7999
Steve Naroff47500512007-04-19 23:00:49 +00008000/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008001/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008002/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008003/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008004/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008005/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008006/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00008007static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00008008 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00008009 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8010 if (PTy->getKind() == BuiltinType::Overload) {
8011 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8012 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8013 << OrigOp.get()->getSourceRange();
8014 return QualType();
8015 }
8016
8017 return S.Context.OverloadTy;
8018 }
8019
8020 if (PTy->getKind() == BuiltinType::UnknownAny)
8021 return S.Context.UnknownAnyTy;
8022
8023 if (PTy->getKind() == BuiltinType::BoundMember) {
8024 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8025 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00008026 return QualType();
8027 }
John McCall526ab472011-10-25 17:37:35 +00008028
8029 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8030 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00008031 }
John McCall8d08b9b2010-08-27 09:08:28 +00008032
John McCall526ab472011-10-25 17:37:35 +00008033 if (OrigOp.get()->isTypeDependent())
8034 return S.Context.DependentTy;
8035
8036 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008037
John McCall8d08b9b2010-08-27 09:08:28 +00008038 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00008039 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008040
David Blaikiebbafb8a2012-03-11 07:00:24 +00008041 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008042 // Implement C99-only parts of addressof rules.
8043 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008044 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008045 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8046 // (assuming the deref expression is valid).
8047 return uOp->getSubExpr()->getType();
8048 }
8049 // Technically, there should be a check for array subscript
8050 // expressions here, but the result of one is always an lvalue anyway.
8051 }
John McCallf3a88602011-02-03 08:15:49 +00008052 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008053 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00008054 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00008055
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008056 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008057 bool sfinae = S.isSFINAEContext();
8058 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8059 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008060 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008061 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008062 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008063 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008064 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008065 } else if (lval == Expr::LV_MemberFunction) {
8066 // If it's an instance method, make a member pointer.
8067 // The expression must have exactly the form &A::foo.
8068
8069 // If the underlying expression isn't a decl ref, give up.
8070 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008071 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008072 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008073 return QualType();
8074 }
8075 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8076 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8077
8078 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00008079 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008080 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00008081 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00008082
8083 // The method was named without a qualifier.
8084 } else if (!DRE->getQualifier()) {
David Blaikiec2ff8e12012-10-11 22:55:07 +00008085 if (MD->getParent()->getName().empty())
8086 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8087 << op->getSourceRange();
8088 else {
8089 SmallString<32> Str;
8090 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8091 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8092 << op->getSourceRange()
8093 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8094 }
John McCall8d08b9b2010-08-27 09:08:28 +00008095 }
8096
John McCall4bc41ae2010-11-18 19:01:18 +00008097 return S.Context.getMemberPointerType(op->getType(),
8098 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008099 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008100 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008101 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008102 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00008103 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00008104 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00008105 AddressOfError = AO_Property_Expansion;
8106 } else {
8107 // FIXME: emit more specific diag...
8108 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8109 << op->getSourceRange();
8110 return QualType();
8111 }
Steve Naroff35d85152007-05-07 00:24:15 +00008112 }
John McCall086a4642010-11-24 05:12:34 +00008113 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008114 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00008115 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00008116 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008117 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00008118 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008119 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008120 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008121 // with the register storage-class specifier.
8122 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008123 // in C++ it is not error to take address of a register
8124 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008125 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008126 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00008127 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00008128 }
John McCalld14a8642009-11-21 08:51:07 +00008129 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008130 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008131 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008132 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008133 // Could be a pointer to member, though, if there is an explicit
8134 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008135 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008136 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008137 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008138 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008139 S.Diag(OpLoc,
8140 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008141 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008142 return QualType();
8143 }
Mike Stump11289f42009-09-09 15:08:12 +00008144
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008145 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8146 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008147 return S.Context.getMemberPointerType(op->getType(),
8148 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008149 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008150 }
Eli Friedman755c0c92011-08-26 20:28:17 +00008151 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00008152 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008153 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008154
Richard Trieu5f376f62011-09-07 21:46:33 +00008155 if (AddressOfError != AO_No_Error) {
8156 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8157 return QualType();
8158 }
8159
Eli Friedmance7f9002009-05-16 23:27:50 +00008160 if (lval == Expr::LV_IncompleteVoidType) {
8161 // Taking the address of a void variable is technically illegal, but we
8162 // allow it in cases which are otherwise valid.
8163 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008164 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008165 }
8166
Steve Naroff47500512007-04-19 23:00:49 +00008167 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008168 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008169 return S.Context.getObjCObjectPointerType(op->getType());
8170 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008171}
8172
Chris Lattner9156f1b2010-07-05 19:17:26 +00008173/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008174static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8175 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008176 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008177 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008178
John Wiegley01296292011-04-08 18:41:53 +00008179 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8180 if (ConvResult.isInvalid())
8181 return QualType();
8182 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008183 QualType OpTy = Op->getType();
8184 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008185
8186 if (isa<CXXReinterpretCastExpr>(Op)) {
8187 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8188 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8189 Op->getSourceRange());
8190 }
8191
Chris Lattner9156f1b2010-07-05 19:17:26 +00008192 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8193 // is an incomplete type or void. It would be possible to warn about
8194 // dereferencing a void pointer, but it's completely well-defined, and such a
8195 // warning is unlikely to catch any mistakes.
8196 if (const PointerType *PT = OpTy->getAs<PointerType>())
8197 Result = PT->getPointeeType();
8198 else if (const ObjCObjectPointerType *OPT =
8199 OpTy->getAs<ObjCObjectPointerType>())
8200 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008201 else {
John McCall3aef3d82011-04-10 19:13:55 +00008202 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008203 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008204 if (PR.take() != Op)
8205 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008206 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008207
Chris Lattner9156f1b2010-07-05 19:17:26 +00008208 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008209 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008210 << OpTy << Op->getSourceRange();
8211 return QualType();
8212 }
John McCall4bc41ae2010-11-18 19:01:18 +00008213
8214 // Dereferences are usually l-values...
8215 VK = VK_LValue;
8216
8217 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008218 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00008219 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008220
8221 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008222}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008223
John McCalle3027922010-08-25 11:45:40 +00008224static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008225 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008226 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008227 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008228 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008229 case tok::periodstar: Opc = BO_PtrMemD; break;
8230 case tok::arrowstar: Opc = BO_PtrMemI; break;
8231 case tok::star: Opc = BO_Mul; break;
8232 case tok::slash: Opc = BO_Div; break;
8233 case tok::percent: Opc = BO_Rem; break;
8234 case tok::plus: Opc = BO_Add; break;
8235 case tok::minus: Opc = BO_Sub; break;
8236 case tok::lessless: Opc = BO_Shl; break;
8237 case tok::greatergreater: Opc = BO_Shr; break;
8238 case tok::lessequal: Opc = BO_LE; break;
8239 case tok::less: Opc = BO_LT; break;
8240 case tok::greaterequal: Opc = BO_GE; break;
8241 case tok::greater: Opc = BO_GT; break;
8242 case tok::exclaimequal: Opc = BO_NE; break;
8243 case tok::equalequal: Opc = BO_EQ; break;
8244 case tok::amp: Opc = BO_And; break;
8245 case tok::caret: Opc = BO_Xor; break;
8246 case tok::pipe: Opc = BO_Or; break;
8247 case tok::ampamp: Opc = BO_LAnd; break;
8248 case tok::pipepipe: Opc = BO_LOr; break;
8249 case tok::equal: Opc = BO_Assign; break;
8250 case tok::starequal: Opc = BO_MulAssign; break;
8251 case tok::slashequal: Opc = BO_DivAssign; break;
8252 case tok::percentequal: Opc = BO_RemAssign; break;
8253 case tok::plusequal: Opc = BO_AddAssign; break;
8254 case tok::minusequal: Opc = BO_SubAssign; break;
8255 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8256 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8257 case tok::ampequal: Opc = BO_AndAssign; break;
8258 case tok::caretequal: Opc = BO_XorAssign; break;
8259 case tok::pipeequal: Opc = BO_OrAssign; break;
8260 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008261 }
8262 return Opc;
8263}
8264
John McCalle3027922010-08-25 11:45:40 +00008265static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008266 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008267 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008268 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008269 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008270 case tok::plusplus: Opc = UO_PreInc; break;
8271 case tok::minusminus: Opc = UO_PreDec; break;
8272 case tok::amp: Opc = UO_AddrOf; break;
8273 case tok::star: Opc = UO_Deref; break;
8274 case tok::plus: Opc = UO_Plus; break;
8275 case tok::minus: Opc = UO_Minus; break;
8276 case tok::tilde: Opc = UO_Not; break;
8277 case tok::exclaim: Opc = UO_LNot; break;
8278 case tok::kw___real: Opc = UO_Real; break;
8279 case tok::kw___imag: Opc = UO_Imag; break;
8280 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008281 }
8282 return Opc;
8283}
8284
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008285/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8286/// This warning is only emitted for builtin assignment operations. It is also
8287/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008288static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008289 SourceLocation OpLoc) {
8290 if (!S.ActiveTemplateInstantiations.empty())
8291 return;
8292 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8293 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008294 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8295 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8296 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8297 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8298 if (!LHSDeclRef || !RHSDeclRef ||
8299 LHSDeclRef->getLocation().isMacroID() ||
8300 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008301 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008302 const ValueDecl *LHSDecl =
8303 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8304 const ValueDecl *RHSDecl =
8305 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8306 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008307 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008308 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008309 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008310 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008311 if (RefTy->getPointeeType().isVolatileQualified())
8312 return;
8313
8314 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008315 << LHSDeclRef->getType()
8316 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008317}
8318
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008319/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8320/// operator @p Opc at location @c TokLoc. This routine only supports
8321/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008322ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008323 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008324 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008325 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008326 // The syntax only allows initializer lists on the RHS of assignment,
8327 // so we don't need to worry about accepting invalid code for
8328 // non-assignment operators.
8329 // C++11 5.17p9:
8330 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8331 // of x = {} is x = T().
8332 InitializationKind Kind =
8333 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8334 InitializedEntity Entity =
8335 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8336 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00008337 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl67766732012-02-27 20:34:02 +00008338 if (Init.isInvalid())
8339 return Init;
8340 RHSExpr = Init.take();
8341 }
8342
Richard Trieu4a287fb2011-09-07 01:49:20 +00008343 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008344 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008345 // The following two variables are used for compound assignment operators
8346 QualType CompLHSTy; // Type of LHS after promotions for computation
8347 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008348 ExprValueKind VK = VK_RValue;
8349 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008350
8351 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008352 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008353 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008354 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008355 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8356 VK = LHS.get()->getValueKind();
8357 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008358 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008359 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008360 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008361 break;
John McCalle3027922010-08-25 11:45:40 +00008362 case BO_PtrMemD:
8363 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008364 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008365 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008366 break;
John McCalle3027922010-08-25 11:45:40 +00008367 case BO_Mul:
8368 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008369 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008370 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008371 break;
John McCalle3027922010-08-25 11:45:40 +00008372 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008373 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008374 break;
John McCalle3027922010-08-25 11:45:40 +00008375 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008376 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008377 break;
John McCalle3027922010-08-25 11:45:40 +00008378 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008379 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008380 break;
John McCalle3027922010-08-25 11:45:40 +00008381 case BO_Shl:
8382 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008383 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008384 break;
John McCalle3027922010-08-25 11:45:40 +00008385 case BO_LE:
8386 case BO_LT:
8387 case BO_GE:
8388 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008389 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008390 break;
John McCalle3027922010-08-25 11:45:40 +00008391 case BO_EQ:
8392 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008393 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008394 break;
John McCalle3027922010-08-25 11:45:40 +00008395 case BO_And:
8396 case BO_Xor:
8397 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008398 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008399 break;
John McCalle3027922010-08-25 11:45:40 +00008400 case BO_LAnd:
8401 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008402 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008403 break;
John McCalle3027922010-08-25 11:45:40 +00008404 case BO_MulAssign:
8405 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008406 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008407 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008408 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008409 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8410 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008411 break;
John McCalle3027922010-08-25 11:45:40 +00008412 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008413 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008414 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008415 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8416 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008417 break;
John McCalle3027922010-08-25 11:45:40 +00008418 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008419 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008420 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8421 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008422 break;
John McCalle3027922010-08-25 11:45:40 +00008423 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008424 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8425 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8426 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008427 break;
John McCalle3027922010-08-25 11:45:40 +00008428 case BO_ShlAssign:
8429 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008430 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008431 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008432 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8433 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008434 break;
John McCalle3027922010-08-25 11:45:40 +00008435 case BO_AndAssign:
8436 case BO_XorAssign:
8437 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008438 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008439 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008440 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8441 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008442 break;
John McCalle3027922010-08-25 11:45:40 +00008443 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008444 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008445 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008446 VK = RHS.get()->getValueKind();
8447 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008448 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008449 break;
8450 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008451 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008452 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008453
8454 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008455 CheckArrayAccess(LHS.get());
8456 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008457
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008458 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008459 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
Lang Hames5de91cc2012-10-02 04:45:10 +00008460 ResultTy, VK, OK, OpLoc,
8461 FPFeatures.fp_contract));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008462 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008463 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008464 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008465 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008466 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008467 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008468 ResultTy, VK, OK, CompLHSTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00008469 CompResultTy, OpLoc,
8470 FPFeatures.fp_contract));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008471}
8472
Sebastian Redl44615072009-10-27 12:10:02 +00008473/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8474/// operators are mixed in a way that suggests that the programmer forgot that
8475/// comparison operators have higher precedence. The most typical example of
8476/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008477static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008478 SourceLocation OpLoc, Expr *LHSExpr,
8479 Expr *RHSExpr) {
Eli Friedman37feb2d2012-11-15 00:29:07 +00008480 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8481 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008482
Eli Friedman37feb2d2012-11-15 00:29:07 +00008483 // Check that one of the sides is a comparison operator.
8484 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8485 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8486 if (!isLeftComp && !isRightComp)
Sebastian Redl43028242009-10-26 15:24:15 +00008487 return;
8488
8489 // Bitwise operations are sometimes used as eager logical ops.
8490 // Don't diagnose this.
Eli Friedman37feb2d2012-11-15 00:29:07 +00008491 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8492 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8493 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl43028242009-10-26 15:24:15 +00008494 return;
8495
Richard Trieu4a287fb2011-09-07 01:49:20 +00008496 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8497 OpLoc)
8498 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedman37feb2d2012-11-15 00:29:07 +00008499 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu73088052011-08-10 22:41:34 +00008500 SourceRange ParensRange = isLeftComp ?
Eli Friedman37feb2d2012-11-15 00:29:07 +00008501 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8502 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008503
8504 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedman37feb2d2012-11-15 00:29:07 +00008505 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu73088052011-08-10 22:41:34 +00008506 SuggestParentheses(Self, OpLoc,
David Blaikiedac86fd2012-10-08 01:19:49 +00008507 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008508 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008509 SuggestParentheses(Self, OpLoc,
Eli Friedman37feb2d2012-11-15 00:29:07 +00008510 Self.PDiag(diag::note_precedence_bitwise_first)
8511 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu73088052011-08-10 22:41:34 +00008512 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008513}
8514
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008515/// \brief It accepts a '&' expr that is inside a '|' one.
8516/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8517/// in parentheses.
8518static void
8519EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8520 BinaryOperator *Bop) {
8521 assert(Bop->getOpcode() == BO_And);
8522 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8523 << Bop->getSourceRange() << OpLoc;
8524 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00008525 Self.PDiag(diag::note_precedence_silence)
8526 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008527 Bop->getSourceRange());
8528}
8529
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008530/// \brief It accepts a '&&' expr that is inside a '||' one.
8531/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8532/// in parentheses.
8533static void
8534EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008535 BinaryOperator *Bop) {
8536 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008537 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8538 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008539 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00008540 Self.PDiag(diag::note_precedence_silence)
8541 << Bop->getOpcodeStr(),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008542 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008543}
8544
8545/// \brief Returns true if the given expression can be evaluated as a constant
8546/// 'true'.
8547static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8548 bool Res;
8549 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8550}
8551
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008552/// \brief Returns true if the given expression can be evaluated as a constant
8553/// 'false'.
8554static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8555 bool Res;
8556 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8557}
8558
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008559/// \brief Look for '&&' in the left hand of a '||' expr.
8560static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008561 Expr *LHSExpr, Expr *RHSExpr) {
8562 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008563 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008564 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008565 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008566 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008567 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8568 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8569 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8570 } else if (Bop->getOpcode() == BO_LOr) {
8571 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8572 // If it's "a || b && 1 || c" we didn't warn earlier for
8573 // "a || b && 1", but warn now.
8574 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8575 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8576 }
8577 }
8578 }
8579}
8580
8581/// \brief Look for '&&' in the right hand of a '||' expr.
8582static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008583 Expr *LHSExpr, Expr *RHSExpr) {
8584 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008585 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008586 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008587 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008588 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008589 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8590 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8591 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008592 }
8593 }
8594}
8595
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008596/// \brief Look for '&' in the left or right hand of a '|' expr.
8597static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8598 Expr *OrArg) {
8599 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8600 if (Bop->getOpcode() == BO_And)
8601 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8602 }
8603}
8604
David Blaikie15f17cb2012-10-05 00:41:03 +00008605static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie82d3ab92012-10-19 18:26:06 +00008606 Expr *SubExpr, StringRef Shift) {
David Blaikie15f17cb2012-10-05 00:41:03 +00008607 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8608 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikiedac86fd2012-10-08 01:19:49 +00008609 StringRef Op = Bop->getOpcodeStr();
David Blaikie15f17cb2012-10-05 00:41:03 +00008610 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie82d3ab92012-10-19 18:26:06 +00008611 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikie15f17cb2012-10-05 00:41:03 +00008612 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikiedac86fd2012-10-08 01:19:49 +00008613 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikie15f17cb2012-10-05 00:41:03 +00008614 Bop->getSourceRange());
8615 }
8616 }
8617}
8618
Sebastian Redl43028242009-10-26 15:24:15 +00008619/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008620/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008621static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008622 SourceLocation OpLoc, Expr *LHSExpr,
8623 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008624 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008625 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008626 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008627
8628 // Diagnose "arg1 & arg2 | arg3"
8629 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008630 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8631 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008632 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008633
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008634 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8635 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008636 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008637 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8638 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008639 }
David Blaikie15f17cb2012-10-05 00:41:03 +00008640
8641 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8642 || Opc == BO_Shr) {
David Blaikie82d3ab92012-10-19 18:26:06 +00008643 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8644 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8645 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikie15f17cb2012-10-05 00:41:03 +00008646 }
Sebastian Redl43028242009-10-26 15:24:15 +00008647}
8648
Steve Naroff218bc2b2007-05-04 21:54:46 +00008649// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008650ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008651 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008652 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008653 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008654 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8655 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008656
Sebastian Redl43028242009-10-26 15:24:15 +00008657 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008658 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008659
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008660 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008661}
8662
John McCall526ab472011-10-25 17:37:35 +00008663/// Build an overloaded binary operator expression in the given scope.
8664static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8665 BinaryOperatorKind Opc,
8666 Expr *LHS, Expr *RHS) {
8667 // Find all of the overloaded operators visible from this
8668 // point. We perform both an operator-name lookup from the local
8669 // scope and an argument-dependent lookup based on the types of
8670 // the arguments.
8671 UnresolvedSet<16> Functions;
8672 OverloadedOperatorKind OverOp
8673 = BinaryOperator::getOverloadedOperator(Opc);
8674 if (Sc && OverOp != OO_None)
8675 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8676 RHS->getType(), Functions);
8677
8678 // Build the (potentially-overloaded, potentially-dependent)
8679 // binary operation.
8680 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8681}
8682
John McCalldadc5752010-08-24 06:29:42 +00008683ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008684 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008685 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008686 // We want to end up calling one of checkPseudoObjectAssignment
8687 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8688 // both expressions are overloadable or either is type-dependent),
8689 // or CreateBuiltinBinOp (in any other case). We also want to get
8690 // any placeholder types out of the way.
8691
John McCall526ab472011-10-25 17:37:35 +00008692 // Handle pseudo-objects in the LHS.
8693 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8694 // Assignments with a pseudo-object l-value need special analysis.
8695 if (pty->getKind() == BuiltinType::PseudoObject &&
8696 BinaryOperator::isAssignmentOp(Opc))
8697 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8698
8699 // Don't resolve overloads if the other type is overloadable.
8700 if (pty->getKind() == BuiltinType::Overload) {
8701 // We can't actually test that if we still have a placeholder,
8702 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008703 // code below are valid when the LHS is an overload set. Note
8704 // that an overload set can be dependently-typed, but it never
8705 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008706 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8707 if (resolvedRHS.isInvalid()) return ExprError();
8708 RHSExpr = resolvedRHS.take();
8709
John McCall9a43e122011-10-28 01:04:34 +00008710 if (RHSExpr->isTypeDependent() ||
8711 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008712 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8713 }
8714
8715 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8716 if (LHS.isInvalid()) return ExprError();
8717 LHSExpr = LHS.take();
8718 }
8719
8720 // Handle pseudo-objects in the RHS.
8721 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8722 // An overload in the RHS can potentially be resolved by the type
8723 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008724 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8725 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8726 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8727
Eli Friedman419b1ff2012-01-17 21:27:43 +00008728 if (LHSExpr->getType()->isOverloadableType())
8729 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8730
John McCall526ab472011-10-25 17:37:35 +00008731 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008732 }
John McCall526ab472011-10-25 17:37:35 +00008733
8734 // Don't resolve overloads if the other type is overloadable.
8735 if (pty->getKind() == BuiltinType::Overload &&
8736 LHSExpr->getType()->isOverloadableType())
8737 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8738
8739 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8740 if (!resolvedRHS.isUsable()) return ExprError();
8741 RHSExpr = resolvedRHS.take();
8742 }
8743
David Blaikiebbafb8a2012-03-11 07:00:24 +00008744 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008745 // If either expression is type-dependent, always build an
8746 // overloaded op.
8747 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8748 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008749
John McCall9a43e122011-10-28 01:04:34 +00008750 // Otherwise, build an overloaded op if either expression has an
8751 // overloadable type.
8752 if (LHSExpr->getType()->isOverloadableType() ||
8753 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008754 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008755 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008756
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008757 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008758 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008759}
8760
John McCalldadc5752010-08-24 06:29:42 +00008761ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008762 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008763 Expr *InputExpr) {
8764 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008765 ExprValueKind VK = VK_RValue;
8766 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008767 QualType resultType;
8768 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008769 case UO_PreInc:
8770 case UO_PreDec:
8771 case UO_PostInc:
8772 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008773 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008774 Opc == UO_PreInc ||
8775 Opc == UO_PostInc,
8776 Opc == UO_PreInc ||
8777 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008778 break;
John McCalle3027922010-08-25 11:45:40 +00008779 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008780 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008781 break;
John McCall31996342011-04-07 08:22:57 +00008782 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008783 Input = DefaultFunctionArrayLvalueConversion(Input.take());
Eli Friedman34866c72012-08-31 00:14:07 +00008784 if (Input.isInvalid()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008785 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008786 break;
John McCall31996342011-04-07 08:22:57 +00008787 }
John McCalle3027922010-08-25 11:45:40 +00008788 case UO_Plus:
8789 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008790 Input = UsualUnaryConversions(Input.take());
8791 if (Input.isInvalid()) return ExprError();
8792 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008793 if (resultType->isDependentType())
8794 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008795 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8796 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008797 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008798 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008799 resultType->isEnumeralType())
8800 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008801 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008802 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008803 resultType->isPointerType())
8804 break;
8805
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008806 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008807 << resultType << Input.get()->getSourceRange());
8808
John McCalle3027922010-08-25 11:45:40 +00008809 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008810 Input = UsualUnaryConversions(Input.take());
8811 if (Input.isInvalid()) return ExprError();
8812 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008813 if (resultType->isDependentType())
8814 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008815 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8816 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8817 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008818 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008819 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008820 else if (resultType->hasIntegerRepresentation())
8821 break;
John McCall526ab472011-10-25 17:37:35 +00008822 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008823 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008824 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008825 }
Steve Naroff35d85152007-05-07 00:24:15 +00008826 break;
John Wiegley01296292011-04-08 18:41:53 +00008827
John McCalle3027922010-08-25 11:45:40 +00008828 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008829 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008830 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8831 if (Input.isInvalid()) return ExprError();
8832 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008833
8834 // Though we still have to promote half FP to float...
8835 if (resultType->isHalfType()) {
8836 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8837 resultType = Context.FloatTy;
8838 }
8839
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008840 if (resultType->isDependentType())
8841 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008842 if (resultType->isScalarType()) {
8843 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008844 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008845 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8846 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008847 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8848 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008849 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008850 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008851 // Vector logical not returns the signed variant of the operand type.
8852 resultType = GetSignedVectorType(resultType);
8853 break;
John McCall36226622010-10-12 02:09:17 +00008854 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008855 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008856 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008857 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008858
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008859 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008860 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008861 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008862 break;
John McCalle3027922010-08-25 11:45:40 +00008863 case UO_Real:
8864 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008865 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008866 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8867 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008868 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008869 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8870 if (Input.get()->getValueKind() != VK_RValue &&
8871 Input.get()->getObjectKind() == OK_Ordinary)
8872 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008873 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008874 // In C, a volatile scalar is read by __imag. In C++, it is not.
8875 Input = DefaultLvalueConversion(Input.take());
8876 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008877 break;
John McCalle3027922010-08-25 11:45:40 +00008878 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008879 resultType = Input.get()->getType();
8880 VK = Input.get()->getValueKind();
8881 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008882 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008883 }
John Wiegley01296292011-04-08 18:41:53 +00008884 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008885 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008886
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008887 // Check for array bounds violations in the operand of the UnaryOperator,
8888 // except for the '*' and '&' operators that have to be handled specially
8889 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8890 // that are explicitly defined as valid by the standard).
8891 if (Opc != UO_AddrOf && Opc != UO_Deref)
8892 CheckArrayAccess(Input.get());
8893
John Wiegley01296292011-04-08 18:41:53 +00008894 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008895 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008896}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008897
Douglas Gregor72341032011-12-14 21:23:13 +00008898/// \brief Determine whether the given expression is a qualified member
8899/// access expression, of a form that could be turned into a pointer to member
8900/// with the address-of operator.
8901static bool isQualifiedMemberAccess(Expr *E) {
8902 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8903 if (!DRE->getQualifier())
8904 return false;
8905
8906 ValueDecl *VD = DRE->getDecl();
8907 if (!VD->isCXXClassMember())
8908 return false;
8909
8910 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8911 return true;
8912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8913 return Method->isInstance();
8914
8915 return false;
8916 }
8917
8918 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8919 if (!ULE->getQualifier())
8920 return false;
8921
8922 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8923 DEnd = ULE->decls_end();
8924 D != DEnd; ++D) {
8925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8926 if (Method->isInstance())
8927 return true;
8928 } else {
8929 // Overload set does not contain methods.
8930 break;
8931 }
8932 }
8933
8934 return false;
8935 }
8936
8937 return false;
8938}
8939
John McCalldadc5752010-08-24 06:29:42 +00008940ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008941 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008942 // First things first: handle placeholders so that the
8943 // overloaded-operator check considers the right type.
8944 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8945 // Increment and decrement of pseudo-object references.
8946 if (pty->getKind() == BuiltinType::PseudoObject &&
8947 UnaryOperator::isIncrementDecrementOp(Opc))
8948 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8949
8950 // extension is always a builtin operator.
8951 if (Opc == UO_Extension)
8952 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8953
8954 // & gets special logic for several kinds of placeholder.
8955 // The builtin code knows what to do.
8956 if (Opc == UO_AddrOf &&
8957 (pty->getKind() == BuiltinType::Overload ||
8958 pty->getKind() == BuiltinType::UnknownAny ||
8959 pty->getKind() == BuiltinType::BoundMember))
8960 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8961
8962 // Anything else needs to be handled now.
8963 ExprResult Result = CheckPlaceholderExpr(Input);
8964 if (Result.isInvalid()) return ExprError();
8965 Input = Result.take();
8966 }
8967
David Blaikiebbafb8a2012-03-11 07:00:24 +00008968 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008969 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8970 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008971 // Find all of the overloaded operators visible from this
8972 // point. We perform both an operator-name lookup from the local
8973 // scope and an argument-dependent lookup based on the types of
8974 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008975 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008976 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008977 if (S && OverOp != OO_None)
8978 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8979 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008980
John McCallb268a282010-08-23 23:25:46 +00008981 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008982 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008983
John McCallb268a282010-08-23 23:25:46 +00008984 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008985}
8986
Douglas Gregor5287f092009-11-05 00:51:44 +00008987// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008988ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008989 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008990 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008991}
8992
Steve Naroff66356bd2007-09-16 14:56:35 +00008993/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008994ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008995 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008996 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008997 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008998 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008999 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009000}
9001
John McCall31168b02011-06-15 23:02:42 +00009002/// Given the last statement in a statement-expression, check whether
9003/// the result is a producing expression (like a call to an
9004/// ns_returns_retained function) and, if so, rebuild it to hoist the
9005/// release out of the full-expression. Otherwise, return null.
9006/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00009007static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00009008 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00009009 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00009010 if (!cleanups) return 0;
9011
9012 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00009013 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00009014 return 0;
9015
9016 // Splice out the cast. This shouldn't modify any interesting
9017 // features of the statement.
9018 Expr *producer = cast->getSubExpr();
9019 assert(producer->getType() == cast->getType());
9020 assert(producer->getValueKind() == cast->getValueKind());
9021 cleanups->setSubExpr(producer);
9022 return cleanups;
9023}
9024
John McCall3abee492012-04-04 01:27:53 +00009025void Sema::ActOnStartStmtExpr() {
9026 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9027}
9028
9029void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00009030 // Note that function is also called by TreeTransform when leaving a
9031 // StmtExpr scope without rebuilding anything.
9032
John McCall3abee492012-04-04 01:27:53 +00009033 DiscardCleanupsInEvaluationContext();
9034 PopExpressionEvaluationContext();
9035}
9036
John McCalldadc5752010-08-24 06:29:42 +00009037ExprResult
John McCallb268a282010-08-23 23:25:46 +00009038Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009039 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009040 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9041 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9042
John McCall3abee492012-04-04 01:27:53 +00009043 if (hasAnyUnrecoverableErrorsInThisFunction())
9044 DiscardCleanupsInEvaluationContext();
9045 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9046 PopExpressionEvaluationContext();
9047
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009048 bool isFileScope
9049 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009050 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009051 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009052
Chris Lattner366727f2007-07-24 16:58:17 +00009053 // FIXME: there are a variety of strange constraints to enforce here, for
9054 // example, it is not possible to goto into a stmt expression apparently.
9055 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009056
Chris Lattner366727f2007-07-24 16:58:17 +00009057 // If there are sub stmts in the compound stmt, take the type of the last one
9058 // as the type of the stmtexpr.
9059 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009060 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009061 if (!Compound->body_empty()) {
9062 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009063 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009064 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009065 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9066 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009067 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009068 }
John McCall31168b02011-06-15 23:02:42 +00009069
John Wiegley01296292011-04-08 18:41:53 +00009070 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009071 // Do function/array conversion on the last expression, but not
9072 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009073 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9074 if (LastExpr.isInvalid())
9075 return ExprError();
9076 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009077
John Wiegley01296292011-04-08 18:41:53 +00009078 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00009079 // In ARC, if the final expression ends in a consume, splice
9080 // the consume out and bind it later. In the alternate case
9081 // (when dealing with a retainable type), the result
9082 // initialization will create a produce. In both cases the
9083 // result will be +1, and we'll need to balance that out with
9084 // a bind.
9085 if (Expr *rebuiltLastStmt
9086 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9087 LastExpr = rebuiltLastStmt;
9088 } else {
9089 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009090 InitializedEntity::InitializeResult(LPLoc,
9091 Ty,
9092 false),
9093 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009094 LastExpr);
9095 }
9096
John Wiegley01296292011-04-08 18:41:53 +00009097 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009098 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009099 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009100 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009101 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009102 else
John Wiegley01296292011-04-08 18:41:53 +00009103 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009104 StmtExprMayBindToTemp = true;
9105 }
9106 }
9107 }
Chris Lattner944d3062008-07-26 19:51:01 +00009108 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009109
Eli Friedmanba961a92009-03-23 00:24:07 +00009110 // FIXME: Check that expression type is complete/non-abstract; statement
9111 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009112 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9113 if (StmtExprMayBindToTemp)
9114 return MaybeBindToTemporary(ResStmtExpr);
9115 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009116}
Steve Naroff78864672007-08-01 22:05:33 +00009117
John McCalldadc5752010-08-24 06:29:42 +00009118ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009119 TypeSourceInfo *TInfo,
9120 OffsetOfComponent *CompPtr,
9121 unsigned NumComponents,
9122 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009123 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009124 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009125 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009126
Chris Lattnerf17bd422007-08-30 17:45:32 +00009127 // We must have at least one component that refers to the type, and the first
9128 // one is known to be a field designator. Verify that the ArgTy represents
9129 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009130 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009131 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9132 << ArgTy << TypeRange);
9133
9134 // Type must be complete per C99 7.17p3 because a declaring a variable
9135 // with an incomplete type would be ill-formed.
9136 if (!Dependent
9137 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009138 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00009139 return ExprError();
9140
Chris Lattner78502cf2007-08-31 21:49:13 +00009141 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9142 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009143 // FIXME: This diagnostic isn't actually visible because the location is in
9144 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009145 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009146 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9147 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009148
9149 bool DidWarnAboutNonPOD = false;
9150 QualType CurrentType = ArgTy;
9151 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009152 SmallVector<OffsetOfNode, 4> Comps;
9153 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00009154 for (unsigned i = 0; i != NumComponents; ++i) {
9155 const OffsetOfComponent &OC = CompPtr[i];
9156 if (OC.isBrackets) {
9157 // Offset of an array sub-field. TODO: Should we allow vector elements?
9158 if (!CurrentType->isDependentType()) {
9159 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9160 if(!AT)
9161 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9162 << CurrentType);
9163 CurrentType = AT->getElementType();
9164 } else
9165 CurrentType = Context.DependentTy;
9166
Richard Smith9fcc5c32011-10-17 23:29:39 +00009167 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9168 if (IdxRval.isInvalid())
9169 return ExprError();
9170 Expr *Idx = IdxRval.take();
9171
Douglas Gregor882211c2010-04-28 22:16:22 +00009172 // The expression must be an integral expression.
9173 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00009174 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9175 !Idx->getType()->isIntegerType())
9176 return ExprError(Diag(Idx->getLocStart(),
9177 diag::err_typecheck_subscript_not_integer)
9178 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00009179
Douglas Gregor882211c2010-04-28 22:16:22 +00009180 // Record this array index.
9181 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00009182 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00009183 continue;
9184 }
9185
9186 // Offset of a field.
9187 if (CurrentType->isDependentType()) {
9188 // We have the offset of a field, but we can't look into the dependent
9189 // type. Just record the identifier of the field.
9190 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9191 CurrentType = Context.DependentTy;
9192 continue;
9193 }
9194
9195 // We need to have a complete type to look into.
9196 if (RequireCompleteType(OC.LocStart, CurrentType,
9197 diag::err_offsetof_incomplete_type))
9198 return ExprError();
9199
9200 // Look for the designated field.
9201 const RecordType *RC = CurrentType->getAs<RecordType>();
9202 if (!RC)
9203 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9204 << CurrentType);
9205 RecordDecl *RD = RC->getDecl();
9206
9207 // C++ [lib.support.types]p5:
9208 // The macro offsetof accepts a restricted set of type arguments in this
9209 // International Standard. type shall be a POD structure or a POD union
9210 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009211 // C++11 [support.types]p4:
9212 // If type is not a standard-layout class (Clause 9), the results are
9213 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00009214 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009215 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9216 unsigned DiagID =
9217 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9218 : diag::warn_offsetof_non_pod_type;
9219
9220 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009221 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00009222 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00009223 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9224 << CurrentType))
9225 DidWarnAboutNonPOD = true;
9226 }
9227
9228 // Look for the field.
9229 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9230 LookupQualifiedName(R, RD);
9231 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009232 IndirectFieldDecl *IndirectMemberDecl = 0;
9233 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009234 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009235 MemberDecl = IndirectMemberDecl->getAnonField();
9236 }
9237
Douglas Gregor882211c2010-04-28 22:16:22 +00009238 if (!MemberDecl)
9239 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9240 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9241 OC.LocEnd));
9242
Douglas Gregor10982ea2010-04-28 22:36:06 +00009243 // C99 7.17p3:
9244 // (If the specified member is a bit-field, the behavior is undefined.)
9245 //
9246 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00009247 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00009248 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9249 << MemberDecl->getDeclName()
9250 << SourceRange(BuiltinLoc, RParenLoc);
9251 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9252 return ExprError();
9253 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009254
9255 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009256 if (IndirectMemberDecl)
9257 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009258
Douglas Gregord1702062010-04-29 00:18:15 +00009259 // If the member was found in a base class, introduce OffsetOfNodes for
9260 // the base class indirections.
9261 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9262 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009263 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009264 CXXBasePath &Path = Paths.front();
9265 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9266 B != BEnd; ++B)
9267 Comps.push_back(OffsetOfNode(B->Base));
9268 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009269
Francois Pichet783dd6e2010-11-21 06:08:52 +00009270 if (IndirectMemberDecl) {
9271 for (IndirectFieldDecl::chain_iterator FI =
9272 IndirectMemberDecl->chain_begin(),
9273 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9274 assert(isa<FieldDecl>(*FI));
9275 Comps.push_back(OffsetOfNode(OC.LocStart,
9276 cast<FieldDecl>(*FI), OC.LocEnd));
9277 }
9278 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009279 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009280
Douglas Gregor882211c2010-04-28 22:16:22 +00009281 CurrentType = MemberDecl->getType().getNonReferenceType();
9282 }
9283
9284 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00009285 TInfo, Comps, Exprs, RParenLoc));
Douglas Gregor882211c2010-04-28 22:16:22 +00009286}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009287
John McCalldadc5752010-08-24 06:29:42 +00009288ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009289 SourceLocation BuiltinLoc,
9290 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009291 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009292 OffsetOfComponent *CompPtr,
9293 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009294 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009295
Douglas Gregor882211c2010-04-28 22:16:22 +00009296 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009297 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009298 if (ArgTy.isNull())
9299 return ExprError();
9300
Eli Friedman06dcfd92010-08-05 10:15:45 +00009301 if (!ArgTInfo)
9302 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9303
9304 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009305 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009306}
9307
9308
John McCalldadc5752010-08-24 06:29:42 +00009309ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009310 Expr *CondExpr,
9311 Expr *LHSExpr, Expr *RHSExpr,
9312 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009313 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9314
John McCall7decc9e2010-11-18 06:31:45 +00009315 ExprValueKind VK = VK_RValue;
9316 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009317 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009318 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009319 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009320 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009321 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009322 } else {
9323 // The conditional expression is required to be a constant expression.
9324 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009325 ExprResult CondICE
9326 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9327 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009328 if (CondICE.isInvalid())
9329 return ExprError();
9330 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009331
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009332 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009333 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9334
9335 resType = ActiveExpr->getType();
9336 ValueDependent = ActiveExpr->isValueDependent();
9337 VK = ActiveExpr->getValueKind();
9338 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009339 }
9340
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009341 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009342 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009343 resType->isDependentType(),
9344 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009345}
9346
Steve Naroffc540d662008-09-03 18:15:37 +00009347//===----------------------------------------------------------------------===//
9348// Clang Extensions.
9349//===----------------------------------------------------------------------===//
9350
9351/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009352void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009353 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009354 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009355 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009356 if (CurScope)
9357 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009358 else
9359 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009360
Eli Friedman34b49062012-01-26 03:00:14 +00009361 getCurBlock()->HasImplicitReturnType = true;
9362
John McCallf1a3c2a2011-11-11 03:19:12 +00009363 // Enter a new evaluation context to insulate the block from any
9364 // cleanups from the enclosing full-expression.
9365 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009366}
9367
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009368void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9369 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009370 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009371 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009372 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009373
John McCall8cb7bdf2010-06-04 23:28:52 +00009374 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009375 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009376
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009377 // FIXME: We should allow unexpanded parameter packs here, but that would,
9378 // in turn, make the block expression contain unexpanded parameter packs.
9379 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9380 // Drop the parameters.
9381 FunctionProtoType::ExtProtoInfo EPI;
9382 EPI.HasTrailingReturn = false;
9383 EPI.TypeQuals |= DeclSpec::TQ_const;
9384 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9385 EPI);
9386 Sig = Context.getTrivialTypeSourceInfo(T);
9387 }
9388
John McCall3882ace2011-01-05 12:14:39 +00009389 // GetTypeForDeclarator always produces a function type for a block
9390 // literal signature. Furthermore, it is always a FunctionProtoType
9391 // unless the function was written with a typedef.
9392 assert(T->isFunctionType() &&
9393 "GetTypeForDeclarator made a non-function block signature");
9394
9395 // Look for an explicit signature in that function type.
9396 FunctionProtoTypeLoc ExplicitSignature;
9397
9398 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9399 if (isa<FunctionProtoTypeLoc>(tmp)) {
9400 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9401
9402 // Check whether that explicit signature was synthesized by
9403 // GetTypeForDeclarator. If so, don't save that as part of the
9404 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009405 if (ExplicitSignature.getLocalRangeBegin() ==
9406 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009407 // This would be much cheaper if we stored TypeLocs instead of
9408 // TypeSourceInfos.
9409 TypeLoc Result = ExplicitSignature.getResultLoc();
9410 unsigned Size = Result.getFullDataSize();
9411 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9412 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9413
9414 ExplicitSignature = FunctionProtoTypeLoc();
9415 }
John McCalla3ccba02010-06-04 11:21:44 +00009416 }
Mike Stump11289f42009-09-09 15:08:12 +00009417
John McCall3882ace2011-01-05 12:14:39 +00009418 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9419 CurBlock->FunctionType = T;
9420
9421 const FunctionType *Fn = T->getAs<FunctionType>();
9422 QualType RetTy = Fn->getResultType();
9423 bool isVariadic =
9424 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9425
John McCall8e346702010-06-04 19:02:56 +00009426 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009427
John McCalla3ccba02010-06-04 11:21:44 +00009428 // Don't allow returning a objc interface by value.
9429 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009430 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009431 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9432 return;
9433 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009434
John McCalla3ccba02010-06-04 11:21:44 +00009435 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009436 // return type. TODO: what should we do with declarators like:
9437 // ^ * { ... }
9438 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009439 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009440 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009441 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009442 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009443 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009444
John McCalla3ccba02010-06-04 11:21:44 +00009445 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009446 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009447 if (ExplicitSignature) {
9448 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9449 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009450 if (Param->getIdentifier() == 0 &&
9451 !Param->isImplicit() &&
9452 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009453 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009454 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009455 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009456 }
John McCalla3ccba02010-06-04 11:21:44 +00009457
9458 // Fake up parameter variables if we have a typedef, like
9459 // ^ fntype { ... }
9460 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9461 for (FunctionProtoType::arg_type_iterator
9462 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9463 ParmVarDecl *Param =
9464 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009465 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009466 *I);
John McCall8e346702010-06-04 19:02:56 +00009467 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009468 }
Steve Naroffc540d662008-09-03 18:15:37 +00009469 }
John McCalla3ccba02010-06-04 11:21:44 +00009470
John McCall8e346702010-06-04 19:02:56 +00009471 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009472 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009473 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009474 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9475 CurBlock->TheDecl->param_end(),
9476 /*CheckParameterNames=*/false);
9477 }
9478
John McCalla3ccba02010-06-04 11:21:44 +00009479 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009480 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009481
John McCalla3ccba02010-06-04 11:21:44 +00009482 // Put the parameter variables in scope. We can bail out immediately
9483 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009484 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009485 return;
9486
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009487 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009488 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9489 (*AI)->setOwningFunction(CurBlock->TheDecl);
9490
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009491 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009492 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009493 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009494
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009495 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009496 }
John McCallf7b2fb52010-01-22 00:28:27 +00009497 }
Steve Naroffc540d662008-09-03 18:15:37 +00009498}
9499
9500/// ActOnBlockError - If there is an error parsing a block, this callback
9501/// is invoked to pop the information about the block from the action impl.
9502void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009503 // Leave the expression-evaluation context.
9504 DiscardCleanupsInEvaluationContext();
9505 PopExpressionEvaluationContext();
9506
Steve Naroffc540d662008-09-03 18:15:37 +00009507 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009508 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009509 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009510}
9511
9512/// ActOnBlockStmtExpr - This is called when the body of a block statement
9513/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009514ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009515 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009516 // If blocks are disabled, emit an error.
9517 if (!LangOpts.Blocks)
9518 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009519
John McCallf1a3c2a2011-11-11 03:19:12 +00009520 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009521 if (hasAnyUnrecoverableErrorsInThisFunction())
9522 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009523 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9524 PopExpressionEvaluationContext();
9525
Douglas Gregor9a28e842010-03-01 23:15:13 +00009526 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rosed39e5f12012-07-02 21:19:23 +00009527
9528 if (BSI->HasImplicitReturnType)
9529 deduceClosureReturnType(*BSI);
9530
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009531 PopDeclContext();
9532
Steve Naroffc540d662008-09-03 18:15:37 +00009533 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009534 if (!BSI->ReturnType.isNull())
9535 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009536
Mike Stump3bf1ab42009-07-28 22:04:01 +00009537 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009538 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009539
John McCallc63de662011-02-02 13:00:07 +00009540 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009541 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9542 SmallVector<BlockDecl::Capture, 4> Captures;
9543 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9544 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9545 if (Cap.isThisCapture())
9546 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009547 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009548 Cap.isNested(), Cap.getCopyExpr());
9549 Captures.push_back(NewCap);
9550 }
9551 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9552 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009553
John McCall8e346702010-06-04 19:02:56 +00009554 // If the user wrote a function type in some form, try to use that.
9555 if (!BSI->FunctionType.isNull()) {
9556 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9557
9558 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9559 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9560
9561 // Turn protoless block types into nullary block types.
9562 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009563 FunctionProtoType::ExtProtoInfo EPI;
9564 EPI.ExtInfo = Ext;
9565 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009566
9567 // Otherwise, if we don't need to change anything about the function type,
9568 // preserve its sugar structure.
9569 } else if (FTy->getResultType() == RetTy &&
9570 (!NoReturn || FTy->getNoReturnAttr())) {
9571 BlockTy = BSI->FunctionType;
9572
9573 // Otherwise, make the minimal modifications to the function type.
9574 } else {
9575 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009576 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9577 EPI.TypeQuals = 0; // FIXME: silently?
9578 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009579 BlockTy = Context.getFunctionType(RetTy,
9580 FPT->arg_type_begin(),
9581 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009582 EPI);
John McCall8e346702010-06-04 19:02:56 +00009583 }
9584
9585 // If we don't have a function type, just build one from nothing.
9586 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009587 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009588 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009589 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009590 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009591
John McCall8e346702010-06-04 19:02:56 +00009592 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9593 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009594 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009595
Chris Lattner45542ea2009-04-19 05:28:12 +00009596 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009597 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009598 !hasAnyUnrecoverableErrorsInThisFunction() &&
9599 !PP.isCodeCompletionEnabled())
John McCallb268a282010-08-23 23:25:46 +00009600 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009601
Chris Lattner60f84492011-02-17 23:58:47 +00009602 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009603
Jordan Rosed39e5f12012-07-02 21:19:23 +00009604 // Try to apply the named return value optimization. We have to check again
9605 // if we can do this, though, because blocks keep return statements around
9606 // to deduce an implicit return type.
9607 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9608 !BSI->TheDecl->isDependentContext())
9609 computeNRVO(Body, getCurBlock());
Douglas Gregor49695f02011-09-06 20:46:03 +00009610
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009611 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9612 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009613 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009614
John McCall28fc7092011-11-10 05:35:25 +00009615 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009616 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009617 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009618 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009619 ExprCleanupObjects.push_back(Result->getBlockDecl());
9620 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009621
9622 // It also gets a branch-protected scope if any of the captured
9623 // variables needs destruction.
9624 for (BlockDecl::capture_const_iterator
9625 ci = Result->getBlockDecl()->capture_begin(),
9626 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9627 const VarDecl *var = ci->getVariable();
9628 if (var->getType().isDestructedType() != QualType::DK_none) {
9629 getCurFunction()->setHasBranchProtectedScope();
9630 break;
9631 }
9632 }
John McCall28fc7092011-11-10 05:35:25 +00009633 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009634
Douglas Gregor9a28e842010-03-01 23:15:13 +00009635 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009636}
9637
John McCalldadc5752010-08-24 06:29:42 +00009638ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009639 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009640 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009641 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009642 GetTypeFromParser(Ty, &TInfo);
9643 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009644}
9645
John McCalldadc5752010-08-24 06:29:42 +00009646ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009647 Expr *E, TypeSourceInfo *TInfo,
9648 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009649 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009650
Eli Friedman121ba0c2008-08-09 23:32:40 +00009651 // Get the va_list type
9652 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009653 if (VaListType->isArrayType()) {
9654 // Deal with implicit array decay; for example, on x86-64,
9655 // va_list is an array, but it's supposed to decay to
9656 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009657 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009658 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009659 ExprResult Result = UsualUnaryConversions(E);
9660 if (Result.isInvalid())
9661 return ExprError();
9662 E = Result.take();
Logan Chien29574892012-10-20 06:11:33 +00009663 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9664 // If va_list is a record type and we are compiling in C++ mode,
9665 // check the argument using reference binding.
9666 InitializedEntity Entity
9667 = InitializedEntity::InitializeParameter(Context,
9668 Context.getLValueReferenceType(VaListType), false);
9669 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9670 if (Init.isInvalid())
9671 return ExprError();
9672 E = Init.takeAs<Expr>();
Eli Friedmane2cad652009-05-16 12:46:54 +00009673 } else {
9674 // Otherwise, the va_list argument must be an l-value because
9675 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009676 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009677 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009678 return ExprError();
9679 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009680
Douglas Gregorad3150c2009-05-19 23:10:31 +00009681 if (!E->isTypeDependent() &&
9682 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009683 return ExprError(Diag(E->getLocStart(),
9684 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009685 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009686 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009687
David Majnemerc75d1a12011-06-14 05:17:32 +00009688 if (!TInfo->getType()->isDependentType()) {
9689 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009690 diag::err_second_parameter_to_va_arg_incomplete,
9691 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009692 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009693
David Majnemerc75d1a12011-06-14 05:17:32 +00009694 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009695 TInfo->getType(),
9696 diag::err_second_parameter_to_va_arg_abstract,
9697 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009698 return ExprError();
9699
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009700 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009701 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009702 TInfo->getType()->isObjCLifetimeType()
9703 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9704 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009705 << TInfo->getType()
9706 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009707 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009708
9709 // Check for va_arg where arguments of the given type will be promoted
9710 // (i.e. this va_arg is guaranteed to have undefined behavior).
9711 QualType PromoteType;
9712 if (TInfo->getType()->isPromotableIntegerType()) {
9713 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9714 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9715 PromoteType = QualType();
9716 }
9717 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9718 PromoteType = Context.DoubleTy;
9719 if (!PromoteType.isNull())
9720 Diag(TInfo->getTypeLoc().getBeginLoc(),
9721 diag::warn_second_parameter_to_va_arg_never_compatible)
9722 << TInfo->getType()
9723 << PromoteType
9724 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009725 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009726
Abramo Bagnara27db2392010-08-10 10:06:15 +00009727 QualType T = TInfo->getType().getNonLValueExprType(Context);
9728 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009729}
9730
John McCalldadc5752010-08-24 06:29:42 +00009731ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009732 // The type of __null will be int or long, depending on the size of
9733 // pointers on the target.
9734 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009735 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9736 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009737 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009738 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009739 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009740 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009741 Ty = Context.LongLongTy;
9742 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009743 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009744 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009745
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009746 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009747}
9748
Alexis Huntc46382e2010-04-28 23:02:27 +00009749static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009750 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009751 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009752 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009753
Anders Carlssonace5d072009-11-10 04:46:30 +00009754 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9755 if (!PT)
9756 return;
9757
9758 // Check if the destination is of type 'id'.
9759 if (!PT->isObjCIdType()) {
9760 // Check if the destination is the 'NSString' interface.
9761 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9762 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9763 return;
9764 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009765
John McCallfe96e0b2011-11-06 09:01:30 +00009766 // Ignore any parens, implicit casts (should only be
9767 // array-to-pointer decays), and not-so-opaque values. The last is
9768 // important for making this trigger for property assignments.
9769 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9770 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9771 if (OV->getSourceExpr())
9772 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9773
9774 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009775 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009776 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009777
Douglas Gregora771f462010-03-31 17:46:05 +00009778 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009779}
9780
Chris Lattner9bad62c2008-01-04 18:04:52 +00009781bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9782 SourceLocation Loc,
9783 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009784 Expr *SrcExpr, AssignmentAction Action,
9785 bool *Complained) {
9786 if (Complained)
9787 *Complained = false;
9788
Chris Lattner9bad62c2008-01-04 18:04:52 +00009789 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009790 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009791 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009792 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009793 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009794 ConversionFixItGenerator ConvHints;
9795 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009796 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009797
Chris Lattner9bad62c2008-01-04 18:04:52 +00009798 switch (ConvTy) {
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009799 case Compatible:
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00009800 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9801 return false;
Fariborz Jahanian268fec12012-07-17 18:00:08 +00009802
Chris Lattner940cfeb2008-01-04 18:22:42 +00009803 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009804 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009805 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9806 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009807 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009808 case IntToPointer:
9809 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009810 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9811 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009812 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009813 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009814 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009815 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009816 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9817 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009818 if (Hint.isNull() && !CheckInferredResultType) {
9819 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9820 }
9821 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009822 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009823 case IncompatiblePointerSign:
9824 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9825 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009826 case FunctionVoidPointer:
9827 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9828 break;
John McCall4fff8f62011-02-01 00:10:29 +00009829 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009830 // Perform array-to-pointer decay if necessary.
9831 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9832
John McCall4fff8f62011-02-01 00:10:29 +00009833 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9834 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9835 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9836 DiagKind = diag::err_typecheck_incompatible_address_space;
9837 break;
John McCall31168b02011-06-15 23:02:42 +00009838
9839
9840 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009841 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009842 break;
John McCall4fff8f62011-02-01 00:10:29 +00009843 }
9844
9845 llvm_unreachable("unknown error case for discarding qualifiers!");
9846 // fallthrough
9847 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009848 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009849 // If the qualifiers lost were because we were applying the
9850 // (deprecated) C++ conversion from a string literal to a char*
9851 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9852 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009853 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009854 // bit of refactoring (so that the second argument is an
9855 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009856 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009857 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009858 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009859 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9860 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009861 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9862 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009863 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009864 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009865 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009866 case IntToBlockPointer:
9867 DiagKind = diag::err_int_to_block_pointer;
9868 break;
9869 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009870 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009871 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009872 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009873 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009874 // it can give a more specific diagnostic.
9875 DiagKind = diag::warn_incompatible_qualified_id;
9876 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009877 case IncompatibleVectors:
9878 DiagKind = diag::warn_incompatible_vectors;
9879 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009880 case IncompatibleObjCWeakRef:
9881 DiagKind = diag::err_arc_weak_unavailable_assign;
9882 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009883 case Incompatible:
9884 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009885 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9886 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009887 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009888 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009889 break;
9890 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009891
Douglas Gregorc68e1402010-04-09 00:35:39 +00009892 QualType FirstType, SecondType;
9893 switch (Action) {
9894 case AA_Assigning:
9895 case AA_Initializing:
9896 // The destination type comes first.
9897 FirstType = DstType;
9898 SecondType = SrcType;
9899 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009900
Douglas Gregorc68e1402010-04-09 00:35:39 +00009901 case AA_Returning:
9902 case AA_Passing:
9903 case AA_Converting:
9904 case AA_Sending:
9905 case AA_Casting:
9906 // The source type comes first.
9907 FirstType = SrcType;
9908 SecondType = DstType;
9909 break;
9910 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009911
Anna Zaks3b402712011-07-28 19:51:27 +00009912 PartialDiagnostic FDiag = PDiag(DiagKind);
9913 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9914
9915 // If we can fix the conversion, suggest the FixIts.
9916 assert(ConvHints.isNull() || Hint.isNull());
9917 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009918 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9919 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009920 FDiag << *HI;
9921 } else {
9922 FDiag << Hint;
9923 }
9924 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9925
Richard Trieucaff2472011-11-23 22:32:32 +00009926 if (MayHaveFunctionDiff)
9927 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9928
Anna Zaks3b402712011-07-28 19:51:27 +00009929 Diag(Loc, FDiag);
9930
Richard Trieucaff2472011-11-23 22:32:32 +00009931 if (SecondType == Context.OverloadTy)
9932 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9933 FirstType);
9934
Douglas Gregor33823722011-06-11 01:09:30 +00009935 if (CheckInferredResultType)
9936 EmitRelatedResultTypeNote(SrcExpr);
9937
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009938 if (Complained)
9939 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009940 return isInvalid;
9941}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009942
Richard Smithf4c51d92012-02-04 09:53:13 +00009943ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9944 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009945 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9946 public:
9947 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9948 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9949 }
9950 } Diagnoser;
9951
9952 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9953}
9954
9955ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9956 llvm::APSInt *Result,
9957 unsigned DiagID,
9958 bool AllowFold) {
9959 class IDDiagnoser : public VerifyICEDiagnoser {
9960 unsigned DiagID;
9961
9962 public:
9963 IDDiagnoser(unsigned DiagID)
9964 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9965
9966 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9967 S.Diag(Loc, DiagID) << SR;
9968 }
9969 } Diagnoser(DiagID);
9970
9971 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9972}
9973
9974void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9975 SourceRange SR) {
9976 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009977}
9978
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009979ExprResult
9980Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009981 VerifyICEDiagnoser &Diagnoser,
9982 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009983 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009984
David Blaikiebbafb8a2012-03-11 07:00:24 +00009985 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009986 // C++11 [expr.const]p5:
9987 // If an expression of literal class type is used in a context where an
9988 // integral constant expression is required, then that class type shall
9989 // have a single non-explicit conversion function to an integral or
9990 // unscoped enumeration type
9991 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009992 if (!Diagnoser.Suppress) {
9993 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9994 public:
9995 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9996
9997 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9998 QualType T) {
9999 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10000 }
10001
10002 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10003 SourceLocation Loc,
10004 QualType T) {
10005 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10006 }
10007
10008 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10009 SourceLocation Loc,
10010 QualType T,
10011 QualType ConvTy) {
10012 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10013 }
10014
10015 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10016 CXXConversionDecl *Conv,
10017 QualType ConvTy) {
10018 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10019 << ConvTy->isEnumeralType() << ConvTy;
10020 }
10021
10022 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10023 QualType T) {
10024 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10025 }
10026
10027 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10028 CXXConversionDecl *Conv,
10029 QualType ConvTy) {
10030 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10031 << ConvTy->isEnumeralType() << ConvTy;
10032 }
10033
10034 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10035 SourceLocation Loc,
10036 QualType T,
10037 QualType ConvTy) {
10038 return DiagnosticBuilder::getEmpty();
10039 }
10040 } ConvertDiagnoser;
10041
10042 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10043 ConvertDiagnoser,
10044 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +000010045 } else {
10046 // The caller wants to silently enquire whether this is an ICE. Don't
10047 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +000010048 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10049 public:
10050 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10051
10052 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10053 QualType T) {
10054 return DiagnosticBuilder::getEmpty();
10055 }
10056
10057 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10058 SourceLocation Loc,
10059 QualType T) {
10060 return DiagnosticBuilder::getEmpty();
10061 }
10062
10063 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10064 SourceLocation Loc,
10065 QualType T,
10066 QualType ConvTy) {
10067 return DiagnosticBuilder::getEmpty();
10068 }
10069
10070 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10071 CXXConversionDecl *Conv,
10072 QualType ConvTy) {
10073 return DiagnosticBuilder::getEmpty();
10074 }
10075
10076 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10077 QualType T) {
10078 return DiagnosticBuilder::getEmpty();
10079 }
10080
10081 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10082 CXXConversionDecl *Conv,
10083 QualType ConvTy) {
10084 return DiagnosticBuilder::getEmpty();
10085 }
10086
10087 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10088 SourceLocation Loc,
10089 QualType T,
10090 QualType ConvTy) {
10091 return DiagnosticBuilder::getEmpty();
10092 }
10093 } ConvertDiagnoser;
10094
10095 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10096 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +000010097 }
10098 if (Converted.isInvalid())
10099 return Converted;
10100 E = Converted.take();
10101 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10102 return ExprError();
10103 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10104 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +000010105 if (!Diagnoser.Suppress)
10106 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +000010107 return ExprError();
10108 }
10109
Richard Smith902ca212011-12-14 23:32:26 +000010110 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10111 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010112 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +000010113 if (Result)
10114 *Result = E->EvaluateKnownConstInt(Context);
10115 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010116 }
10117
Anders Carlssone54e8a12008-11-30 19:50:32 +000010118 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +000010119 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10120 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +000010121
Richard Smith902ca212011-12-14 23:32:26 +000010122 // Try to evaluate the expression, and produce diagnostics explaining why it's
10123 // not a constant expression as a side-effect.
10124 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10125 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10126
10127 // In C++11, we can rely on diagnostics being produced for any expression
10128 // which is not a constant expression. If no diagnostics were produced, then
10129 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010130 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +000010131 if (Result)
10132 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010133 return Owned(E);
10134 }
10135
10136 // If our only note is the usual "invalid subexpression" note, just point
10137 // the caret at its location rather than producing an essentially
10138 // redundant note.
10139 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10140 diag::note_invalid_subexpr_in_const_expr) {
10141 DiagLoc = Notes[0].first;
10142 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +000010143 }
10144
10145 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +000010146 if (!Diagnoser.Suppress) {
10147 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +000010148 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10149 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010150 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010151
Richard Smithf4c51d92012-02-04 09:53:13 +000010152 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010153 }
10154
Douglas Gregore2b37442012-05-04 22:38:52 +000010155 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +000010156 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10157 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010158
Anders Carlssone54e8a12008-11-30 19:50:32 +000010159 if (Result)
10160 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +000010161 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +000010162}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010163
Eli Friedman456f0182012-01-20 01:26:23 +000010164namespace {
10165 // Handle the case where we conclude a expression which we speculatively
10166 // considered to be unevaluated is actually evaluated.
10167 class TransformToPE : public TreeTransform<TransformToPE> {
10168 typedef TreeTransform<TransformToPE> BaseTransform;
10169
10170 public:
10171 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10172
10173 // Make sure we redo semantic analysis
10174 bool AlwaysRebuild() { return true; }
10175
Eli Friedman5f0ca242012-02-06 23:29:57 +000010176 // Make sure we handle LabelStmts correctly.
10177 // FIXME: This does the right thing, but maybe we need a more general
10178 // fix to TreeTransform?
10179 StmtResult TransformLabelStmt(LabelStmt *S) {
10180 S->getDecl()->setStmt(0);
10181 return BaseTransform::TransformLabelStmt(S);
10182 }
10183
Eli Friedman456f0182012-01-20 01:26:23 +000010184 // We need to special-case DeclRefExprs referring to FieldDecls which
10185 // are not part of a member pointer formation; normal TreeTransforming
10186 // doesn't catch this case because of the way we represent them in the AST.
10187 // FIXME: This is a bit ugly; is it really the best way to handle this
10188 // case?
10189 //
10190 // Error on DeclRefExprs referring to FieldDecls.
10191 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10192 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie131fcb42012-08-06 22:47:24 +000010193 !SemaRef.isUnevaluatedContext())
Eli Friedman456f0182012-01-20 01:26:23 +000010194 return SemaRef.Diag(E->getLocation(),
10195 diag::err_invalid_non_static_member_use)
10196 << E->getDecl() << E->getSourceRange();
10197
10198 return BaseTransform::TransformDeclRefExpr(E);
10199 }
10200
10201 // Exception: filter out member pointer formation
10202 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10203 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10204 return E;
10205
10206 return BaseTransform::TransformUnaryOperator(E);
10207 }
10208
Douglas Gregor89625492012-02-09 08:14:43 +000010209 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10210 // Lambdas never need to be transformed.
10211 return E;
10212 }
Eli Friedman456f0182012-01-20 01:26:23 +000010213 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010214}
10215
Benjamin Kramerd81108f2012-11-14 15:08:31 +000010216ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +000010217 assert(ExprEvalContexts.back().Context == Unevaluated &&
10218 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +000010219 ExprEvalContexts.back().Context =
10220 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10221 if (ExprEvalContexts.back().Context == Unevaluated)
10222 return E;
10223 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000010224}
10225
Douglas Gregorff790f12009-11-26 00:44:06 +000010226void
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010227Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +000010228 Decl *LambdaContextDecl,
10229 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010230 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010231 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +000010232 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +000010233 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +000010234 LambdaContextDecl,
10235 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +000010236 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010237 if (!MaybeODRUseExprs.empty())
10238 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010239}
10240
Eli Friedman15681d62012-09-26 04:34:21 +000010241void
10242Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10243 ReuseLambdaContextDecl_t,
10244 bool IsDecltype) {
10245 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10246 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10247}
10248
Richard Trieucfc491d2011-08-02 04:35:43 +000010249void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010250 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010251
Douglas Gregor89625492012-02-09 08:14:43 +000010252 if (!Rec.Lambdas.empty()) {
10253 if (Rec.Context == Unevaluated) {
10254 // C++11 [expr.prim.lambda]p2:
10255 // A lambda-expression shall not appear in an unevaluated operand
10256 // (Clause 5).
10257 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10258 Diag(Rec.Lambdas[I]->getLocStart(),
10259 diag::err_lambda_unevaluated_operand);
10260 } else {
10261 // Mark the capture expressions odr-used. This was deferred
10262 // during lambda expression creation.
10263 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10264 LambdaExpr *Lambda = Rec.Lambdas[I];
10265 for (LambdaExpr::capture_init_iterator
10266 C = Lambda->capture_init_begin(),
10267 CEnd = Lambda->capture_init_end();
10268 C != CEnd; ++C) {
10269 MarkDeclarationsReferencedInExpr(*C);
10270 }
10271 }
10272 }
10273 }
10274
Douglas Gregorff790f12009-11-26 00:44:06 +000010275 // When are coming out of an unevaluated context, clear out any
10276 // temporaries that we may have created as part of the evaluation of
10277 // the expression in that context: they aren't relevant because they
10278 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +000010279 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +000010280 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10281 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010282 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010283 CleanupVarDeclMarking();
10284 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +000010285 // Otherwise, merge the contexts together.
10286 } else {
10287 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010288 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10289 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +000010290 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010291
10292 // Pop the current expression evaluation context off the stack.
10293 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010294}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010295
John McCall31168b02011-06-15 23:02:42 +000010296void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010297 ExprCleanupObjects.erase(
10298 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10299 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010300 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010301 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010302}
10303
Eli Friedmane0afc982012-01-21 01:01:51 +000010304ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10305 if (!E->getType()->isVariablyModifiedType())
10306 return E;
Benjamin Kramerd81108f2012-11-14 15:08:31 +000010307 return TransformToPotentiallyEvaluated(E);
Eli Friedmane0afc982012-01-21 01:01:51 +000010308}
10309
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010310static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010311 // Do not mark anything as "used" within a dependent context; wait for
10312 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010313 if (SemaRef.CurContext->isDependentContext())
10314 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010315
Eli Friedmanfa0df832012-02-02 03:46:19 +000010316 switch (SemaRef.ExprEvalContexts.back().Context) {
10317 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010318 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010319 // (Depending on how you read the standard, we actually do need to do
10320 // something here for null pointer constants, but the standard's
10321 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010322 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010323
Eli Friedmanfa0df832012-02-02 03:46:19 +000010324 case Sema::ConstantEvaluated:
10325 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010326 // We are in a potentially evaluated expression (or a constant-expression
10327 // in C++03); we need to do implicit template instantiation, implicitly
10328 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010329 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010330
Eli Friedmanfa0df832012-02-02 03:46:19 +000010331 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010332 // Referenced declarations will only be used if the construct in the
10333 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010334 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010335 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010336 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010337}
10338
10339/// \brief Mark a function referenced, and check whether it is odr-used
10340/// (C++ [basic.def.odr]p2, C99 6.9p3)
10341void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10342 assert(Func && "No function?");
10343
10344 Func->setReferenced();
10345
Richard Smithe10d3042012-11-07 01:14:25 +000010346 // C++11 [basic.def.odr]p3:
10347 // A function whose name appears as a potentially-evaluated expression is
10348 // odr-used if it is the unique lookup result or the selected member of a
10349 // set of overloaded functions [...].
10350 //
10351 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10352 // can just check that here. Skip the rest of this function if we've already
10353 // marked the function as used.
10354 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10355 // C++11 [temp.inst]p3:
10356 // Unless a function template specialization has been explicitly
10357 // instantiated or explicitly specialized, the function template
10358 // specialization is implicitly instantiated when the specialization is
10359 // referenced in a context that requires a function definition to exist.
10360 //
10361 // We consider constexpr function templates to be referenced in a context
10362 // that requires a definition to exist whenever they are referenced.
10363 //
10364 // FIXME: This instantiates constexpr functions too frequently. If this is
10365 // really an unevaluated context (and we're not just in the definition of a
10366 // function template or overload resolution or other cases which we
10367 // incorrectly consider to be unevaluated contexts), and we're not in a
10368 // subexpression which we actually need to evaluate (for instance, a
10369 // template argument, array bound or an expression in a braced-init-list),
10370 // we are not permitted to instantiate this constexpr function definition.
10371 //
10372 // FIXME: This also implicitly defines special members too frequently. They
10373 // are only supposed to be implicitly defined if they are odr-used, but they
10374 // are not odr-used from constant expressions in unevaluated contexts.
10375 // However, they cannot be referenced if they are deleted, and they are
10376 // deleted whenever the implicit definition of the special member would
10377 // fail.
10378 if (!Func->isConstexpr() || Func->getBody())
10379 return;
10380 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10381 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10382 return;
10383 }
Mike Stump11289f42009-09-09 15:08:12 +000010384
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010385 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010386 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010387 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010388 if (Constructor->isDefaultConstructor()) {
10389 if (Constructor->isTrivial())
10390 return;
10391 if (!Constructor->isUsed(false))
10392 DefineImplicitDefaultConstructor(Loc, Constructor);
10393 } else if (Constructor->isCopyConstructor()) {
10394 if (!Constructor->isUsed(false))
10395 DefineImplicitCopyConstructor(Loc, Constructor);
10396 } else if (Constructor->isMoveConstructor()) {
10397 if (!Constructor->isUsed(false))
10398 DefineImplicitMoveConstructor(Loc, Constructor);
10399 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010400 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010401
Douglas Gregor88d292c2010-05-13 16:44:06 +000010402 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010403 } else if (CXXDestructorDecl *Destructor =
10404 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010405 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10406 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010407 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010408 if (Destructor->isVirtual())
10409 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010410 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010411 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10412 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010413 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010414 if (!MethodDecl->isUsed(false)) {
10415 if (MethodDecl->isCopyAssignmentOperator())
10416 DefineImplicitCopyAssignment(Loc, MethodDecl);
10417 else
10418 DefineImplicitMoveAssignment(Loc, MethodDecl);
10419 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010420 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10421 MethodDecl->getParent()->isLambda()) {
10422 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10423 if (Conversion->isLambdaToBlockPointerConversion())
10424 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10425 else
10426 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010427 } else if (MethodDecl->isVirtual())
10428 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010429 }
John McCall83779672011-02-19 02:53:41 +000010430
Eli Friedmanfa0df832012-02-02 03:46:19 +000010431 // Recursive functions should be marked when used from another function.
10432 // FIXME: Is this really right?
10433 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010434
Richard Smithd3b5c9082012-07-27 04:22:15 +000010435 // Resolve the exception specification for any function which is
Richard Smithf623c962012-04-17 00:58:00 +000010436 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010437 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010438 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10439 ResolveExceptionSpec(Loc, FPT);
Richard Smithf623c962012-04-17 00:58:00 +000010440
Eli Friedmanfa0df832012-02-02 03:46:19 +000010441 // Implicit instantiation of function templates and member functions of
10442 // class templates.
10443 if (Func->isImplicitlyInstantiable()) {
10444 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010445 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010446 if (FunctionTemplateSpecializationInfo *SpecInfo
10447 = Func->getTemplateSpecializationInfo()) {
10448 if (SpecInfo->getPointOfInstantiation().isInvalid())
10449 SpecInfo->setPointOfInstantiation(Loc);
10450 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010451 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010452 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010453 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10454 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010455 } else if (MemberSpecializationInfo *MSInfo
10456 = Func->getMemberSpecializationInfo()) {
10457 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010458 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010459 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010460 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010461 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010462 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10463 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010464 }
Mike Stump11289f42009-09-09 15:08:12 +000010465
Richard Smith4a941e22012-02-14 22:25:15 +000010466 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010467 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10468 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010469 PendingLocalImplicitInstantiations.push_back(
10470 std::make_pair(Func, PointOfInstantiation));
10471 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010472 // Do not defer instantiations of constexpr functions, to avoid the
10473 // expression evaluator needing to call back into Sema if it sees a
10474 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010475 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010476 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010477 PendingInstantiations.push_back(std::make_pair(Func,
10478 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010479 // Notify the consumer that a function was implicitly instantiated.
10480 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10481 }
John McCall83779672011-02-19 02:53:41 +000010482 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010483 } else {
10484 // Walk redefinitions, as some of them may be instantiable.
10485 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10486 e(Func->redecls_end()); i != e; ++i) {
10487 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10488 MarkFunctionReferenced(Loc, *i);
10489 }
Sam Weinigbae69142009-09-11 03:29:30 +000010490 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010491
10492 // Keep track of used but undefined functions.
10493 if (!Func->isPure() && !Func->hasBody() &&
10494 Func->getLinkage() != ExternalLinkage) {
10495 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10496 if (old.isInvalid()) old = Loc;
10497 }
10498
10499 Func->setUsed(true);
10500}
10501
Eli Friedman9bb33f52012-02-03 02:04:35 +000010502static void
10503diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10504 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010505 DeclContext *VarDC = var->getDeclContext();
10506
Eli Friedman9bb33f52012-02-03 02:04:35 +000010507 // If the parameter still belongs to the translation unit, then
10508 // we're actually just using one parameter in the declaration of
10509 // the next.
10510 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010511 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010512 return;
10513
Eli Friedmandd053f62012-02-07 00:15:00 +000010514 // For C code, don't diagnose about capture if we're not actually in code
10515 // right now; it's impossible to write a non-constant expression outside of
10516 // function context, so we'll get other (more useful) diagnostics later.
10517 //
10518 // For C++, things get a bit more nasty... it would be nice to suppress this
10519 // diagnostic for certain cases like using a local variable in an array bound
10520 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010521 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010522 return;
10523
Eli Friedmandd053f62012-02-07 00:15:00 +000010524 if (isa<CXXMethodDecl>(VarDC) &&
10525 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10526 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10527 << var->getIdentifier();
10528 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10529 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10530 << var->getIdentifier() << fn->getDeclName();
10531 } else if (isa<BlockDecl>(VarDC)) {
10532 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10533 << var->getIdentifier();
10534 } else {
10535 // FIXME: Is there any other context where a local variable can be
10536 // declared?
10537 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10538 << var->getIdentifier();
10539 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010540
Eli Friedman9bb33f52012-02-03 02:04:35 +000010541 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10542 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010543
10544 // FIXME: Add additional diagnostic info about class etc. which prevents
10545 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010546}
10547
Douglas Gregor81495f32012-02-12 18:42:33 +000010548/// \brief Capture the given variable in the given lambda expression.
10549static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010550 VarDecl *Var, QualType FieldType,
10551 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010552 SourceLocation Loc,
10553 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010554 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010555
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010556 // Build the non-static data member.
10557 FieldDecl *Field
10558 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10559 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010560 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010561 Field->setImplicit(true);
10562 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010563 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010564
10565 // C++11 [expr.prim.lambda]p21:
10566 // When the lambda-expression is evaluated, the entities that
10567 // are captured by copy are used to direct-initialize each
10568 // corresponding non-static data member of the resulting closure
10569 // object. (For array members, the array elements are
10570 // direct-initialized in increasing subscript order.) These
10571 // initializations are performed in the (unspecified) order in
10572 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010573
Douglas Gregor89625492012-02-09 08:14:43 +000010574 // Introduce a new evaluation context for the initialization, so
10575 // that temporaries introduced as part of the capture are retained
10576 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010577 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10578
Douglas Gregorf02455e2012-02-10 09:26:04 +000010579 // C++ [expr.prim.labda]p12:
10580 // An entity captured by a lambda-expression is odr-used (3.2) in
10581 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010582 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10583 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010584 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010585 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010586
10587 // When the field has array type, create index variables for each
10588 // dimension of the array. We use these index variables to subscript
10589 // the source array, and other clients (e.g., CodeGen) will perform
10590 // the necessary iteration with these index variables.
10591 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010592 QualType BaseType = FieldType;
10593 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010594 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010595 while (const ConstantArrayType *Array
10596 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010597 // Create the iteration variable for this array index.
10598 IdentifierInfo *IterationVarName = 0;
10599 {
10600 SmallString<8> Str;
10601 llvm::raw_svector_ostream OS(Str);
10602 OS << "__i" << IndexVariables.size();
10603 IterationVarName = &S.Context.Idents.get(OS.str());
10604 }
10605 VarDecl *IterationVar
10606 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10607 IterationVarName, SizeType,
10608 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10609 SC_None, SC_None);
10610 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010611 LSI->ArrayIndexVars.push_back(IterationVar);
10612
Douglas Gregor199cec72012-02-09 02:45:47 +000010613 // Create a reference to the iteration variable.
10614 ExprResult IterationVarRef
10615 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10616 assert(!IterationVarRef.isInvalid() &&
10617 "Reference to invented variable cannot fail!");
10618 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10619 assert(!IterationVarRef.isInvalid() &&
10620 "Conversion of invented variable cannot fail!");
10621
10622 // Subscript the array with this iteration variable.
10623 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10624 Ref, Loc, IterationVarRef.take(), Loc);
10625 if (Subscript.isInvalid()) {
10626 S.CleanupVarDeclMarking();
10627 S.DiscardCleanupsInEvaluationContext();
10628 S.PopExpressionEvaluationContext();
10629 return ExprError();
10630 }
10631
10632 Ref = Subscript.take();
10633 BaseType = Array->getElementType();
10634 }
10635
10636 // Construct the entity that we will be initializing. For an array, this
10637 // will be first element in the array, which may require several levels
10638 // of array-subscript entities.
10639 SmallVector<InitializedEntity, 4> Entities;
10640 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010641 Entities.push_back(
10642 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010643 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10644 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10645 0,
10646 Entities.back()));
10647
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010648 InitializationKind InitKind
10649 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010650 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010651 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010652 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010653 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010654
10655 // If this initialization requires any cleanups (e.g., due to a
10656 // default argument to a copy constructor), note that for the
10657 // lambda.
10658 if (S.ExprNeedsCleanups)
10659 LSI->ExprNeedsCleanups = true;
10660
10661 // Exit the expression evaluation context used for the capture.
10662 S.CleanupVarDeclMarking();
10663 S.DiscardCleanupsInEvaluationContext();
10664 S.PopExpressionEvaluationContext();
10665 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010666}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010667
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010668bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10669 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10670 bool BuildAndDiagnose,
10671 QualType &CaptureType,
10672 QualType &DeclRefType) {
10673 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010674
Eli Friedman24af8502012-02-03 22:47:37 +000010675 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010676 if (Var->getDeclContext() == DC) return true;
10677 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010678
Douglas Gregor81495f32012-02-12 18:42:33 +000010679 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010680
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010681 // Walk up the stack to determine whether we can capture the variable,
10682 // performing the "simple" checks that don't depend on type. We stop when
10683 // we've either hit the declared scope of the variable or find an existing
10684 // capture of that variable.
10685 CaptureType = Var->getType();
10686 DeclRefType = CaptureType.getNonReferenceType();
10687 bool Explicit = (Kind != TryCapture_Implicit);
10688 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010689 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010690 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010691 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010692 DeclContext *ParentDC;
10693 if (isa<BlockDecl>(DC))
10694 ParentDC = DC->getParent();
10695 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010696 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010697 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10698 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010699 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010700 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010701 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010702 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010703 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010704
Eli Friedman24af8502012-02-03 22:47:37 +000010705 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010706 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010707
Eli Friedman24af8502012-02-03 22:47:37 +000010708 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010709 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010710 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010711 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010712
10713 // Retrieve the capture type for this variable.
10714 CaptureType = CSI->getCapture(Var).getCaptureType();
10715
10716 // Compute the type of an expression that refers to this variable.
10717 DeclRefType = CaptureType.getNonReferenceType();
10718
10719 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10720 if (Cap.isCopyCapture() &&
10721 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10722 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010723 break;
10724 }
10725
Douglas Gregor81495f32012-02-12 18:42:33 +000010726 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010727 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010728
10729 // Lambdas are not allowed to capture unnamed variables
10730 // (e.g. anonymous unions).
10731 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10732 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010733 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010734 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010735 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10736 Diag(Var->getLocation(), diag::note_declared_at);
10737 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010738 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010739 }
10740
10741 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010742 if (Var->getType()->isVariablyModifiedType()) {
10743 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010744 if (IsBlock)
10745 Diag(Loc, diag::err_ref_vm_type);
10746 else
10747 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10748 Diag(Var->getLocation(), diag::note_previous_decl)
10749 << Var->getDeclName();
10750 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010751 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010752 }
10753
Eli Friedman24af8502012-02-03 22:47:37 +000010754 // Lambdas are not allowed to capture __block variables; they don't
10755 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010756 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010757 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010758 Diag(Loc, diag::err_lambda_capture_block)
10759 << Var->getDeclName();
10760 Diag(Var->getLocation(), diag::note_previous_decl)
10761 << Var->getDeclName();
10762 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010763 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010764 }
10765
Douglas Gregor81495f32012-02-12 18:42:33 +000010766 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10767 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010768 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010769 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10770 Diag(Var->getLocation(), diag::note_previous_decl)
10771 << Var->getDeclName();
10772 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10773 diag::note_lambda_decl);
10774 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010775 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010776 }
10777
10778 FunctionScopesIndex--;
10779 DC = ParentDC;
10780 Explicit = false;
10781 } while (!Var->getDeclContext()->Equals(DC));
10782
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010783 // Walk back down the scope stack, computing the type of the capture at
10784 // each step, checking type-specific requirements, and adding captures if
10785 // requested.
10786 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10787 ++I) {
10788 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010789
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010790 // Compute the type of the capture and of a reference to the capture within
10791 // this scope.
10792 if (isa<BlockScopeInfo>(CSI)) {
10793 Expr *CopyExpr = 0;
10794 bool ByRef = false;
10795
10796 // Blocks are not allowed to capture arrays.
10797 if (CaptureType->isArrayType()) {
10798 if (BuildAndDiagnose) {
10799 Diag(Loc, diag::err_ref_array_type);
10800 Diag(Var->getLocation(), diag::note_previous_decl)
10801 << Var->getDeclName();
10802 }
10803 return true;
10804 }
10805
John McCall67cd5e02012-03-30 05:23:48 +000010806 // Forbid the block-capture of autoreleasing variables.
10807 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10808 if (BuildAndDiagnose) {
10809 Diag(Loc, diag::err_arc_autoreleasing_capture)
10810 << /*block*/ 0;
10811 Diag(Var->getLocation(), diag::note_previous_decl)
10812 << Var->getDeclName();
10813 }
10814 return true;
10815 }
10816
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010817 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10818 // Block capture by reference does not change the capture or
10819 // declaration reference types.
10820 ByRef = true;
10821 } else {
10822 // Block capture by copy introduces 'const'.
10823 CaptureType = CaptureType.getNonReferenceType().withConst();
10824 DeclRefType = CaptureType;
10825
David Blaikiebbafb8a2012-03-11 07:00:24 +000010826 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010827 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10828 // The capture logic needs the destructor, so make sure we mark it.
10829 // Usually this is unnecessary because most local variables have
10830 // their destructors marked at declaration time, but parameters are
10831 // an exception because it's technically only the call site that
10832 // actually requires the destructor.
10833 if (isa<ParmVarDecl>(Var))
10834 FinalizeVarWithDestructor(Var, Record);
Douglas Gregorc4017552012-12-01 01:01:09 +000010835
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010836 // According to the blocks spec, the capture of a variable from
10837 // the stack requires a const copy constructor. This is not true
10838 // of the copy/move done to move a __block variable to the heap.
Douglas Gregorc4017552012-12-01 01:01:09 +000010839 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010840 DeclRefType.withConst(),
10841 VK_LValue, Loc);
Douglas Gregorc4017552012-12-01 01:01:09 +000010842
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010843 ExprResult Result
10844 = PerformCopyInitialization(
10845 InitializedEntity::InitializeBlock(Var->getLocation(),
10846 CaptureType, false),
10847 Loc, Owned(DeclRef));
10848
10849 // Build a full-expression copy expression if initialization
10850 // succeeded and used a non-trivial constructor. Recover from
10851 // errors by pretending that the copy isn't necessary.
10852 if (!Result.isInvalid() &&
10853 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10854 ->isTrivial()) {
10855 Result = MaybeCreateExprWithCleanups(Result);
10856 CopyExpr = Result.take();
10857 }
10858 }
10859 }
10860 }
10861
10862 // Actually capture the variable.
10863 if (BuildAndDiagnose)
10864 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10865 SourceLocation(), CaptureType, CopyExpr);
10866 Nested = true;
10867 continue;
10868 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010869
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010870 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10871
10872 // Determine whether we are capturing by reference or by value.
10873 bool ByRef = false;
10874 if (I == N - 1 && Kind != TryCapture_Implicit) {
10875 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010876 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010877 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010878 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010879
10880 // Compute the type of the field that will capture this variable.
10881 if (ByRef) {
10882 // C++11 [expr.prim.lambda]p15:
10883 // An entity is captured by reference if it is implicitly or
10884 // explicitly captured but not captured by copy. It is
10885 // unspecified whether additional unnamed non-static data
10886 // members are declared in the closure type for entities
10887 // captured by reference.
10888 //
10889 // FIXME: It is not clear whether we want to build an lvalue reference
10890 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10891 // to do the former, while EDG does the latter. Core issue 1249 will
10892 // clarify, but for now we follow GCC because it's a more permissive and
10893 // easily defensible position.
10894 CaptureType = Context.getLValueReferenceType(DeclRefType);
10895 } else {
10896 // C++11 [expr.prim.lambda]p14:
10897 // For each entity captured by copy, an unnamed non-static
10898 // data member is declared in the closure type. The
10899 // declaration order of these members is unspecified. The type
10900 // of such a data member is the type of the corresponding
10901 // captured entity if the entity is not a reference to an
10902 // object, or the referenced type otherwise. [Note: If the
10903 // captured entity is a reference to a function, the
10904 // corresponding data member is also a reference to a
10905 // function. - end note ]
10906 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10907 if (!RefType->getPointeeType()->isFunctionType())
10908 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010909 }
John McCall67cd5e02012-03-30 05:23:48 +000010910
10911 // Forbid the lambda copy-capture of autoreleasing variables.
10912 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10913 if (BuildAndDiagnose) {
10914 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10915 Diag(Var->getLocation(), diag::note_previous_decl)
10916 << Var->getDeclName();
10917 }
10918 return true;
10919 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010920 }
10921
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010922 // Capture this variable in the lambda.
10923 Expr *CopyExpr = 0;
10924 if (BuildAndDiagnose) {
10925 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010926 DeclRefType, Loc,
Douglas Gregorc4017552012-12-01 01:01:09 +000010927 Nested);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010928 if (!Result.isInvalid())
10929 CopyExpr = Result.take();
10930 }
10931
10932 // Compute the type of a reference to this captured variable.
10933 if (ByRef)
10934 DeclRefType = CaptureType.getNonReferenceType();
10935 else {
10936 // C++ [expr.prim.lambda]p5:
10937 // The closure type for a lambda-expression has a public inline
10938 // function call operator [...]. This function call operator is
10939 // declared const (9.3.1) if and only if the lambda-expression’s
10940 // parameter-declaration-clause is not followed by mutable.
10941 DeclRefType = CaptureType.getNonReferenceType();
10942 if (!LSI->Mutable && !CaptureType->isReferenceType())
10943 DeclRefType.addConst();
10944 }
10945
10946 // Add the capture.
10947 if (BuildAndDiagnose)
10948 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10949 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010950 Nested = true;
10951 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010952
10953 return false;
10954}
10955
10956bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10957 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10958 QualType CaptureType;
10959 QualType DeclRefType;
10960 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10961 /*BuildAndDiagnose=*/true, CaptureType,
10962 DeclRefType);
10963}
10964
10965QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10966 QualType CaptureType;
10967 QualType DeclRefType;
10968
10969 // Determine whether we can capture this variable.
10970 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10971 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10972 return QualType();
10973
10974 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010975}
10976
Eli Friedman3bda6b12012-02-02 23:15:15 +000010977static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10978 SourceLocation Loc) {
10979 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010980 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010981 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010982 Var->getLinkage() != ExternalLinkage &&
10983 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010984 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10985 if (old.isInvalid()) old = Loc;
10986 }
10987
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010988 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010989
Eli Friedman3bda6b12012-02-02 23:15:15 +000010990 Var->setUsed(true);
10991}
10992
10993void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10994 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10995 // an object that satisfies the requirements for appearing in a
10996 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10997 // is immediately applied." This function handles the lvalue-to-rvalue
10998 // conversion part.
10999 MaybeODRUseExprs.erase(E->IgnoreParens());
11000}
11001
Eli Friedmanc6237c62012-02-29 03:16:56 +000011002ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11003 if (!Res.isUsable())
11004 return Res;
11005
11006 // If a constant-expression is a reference to a variable where we delay
11007 // deciding whether it is an odr-use, just assume we will apply the
11008 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11009 // (a non-type template argument), we have special handling anyway.
11010 UpdateMarkingForLValueToRValue(Res.get());
11011 return Res;
11012}
11013
Eli Friedman3bda6b12012-02-02 23:15:15 +000011014void Sema::CleanupVarDeclMarking() {
11015 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11016 e = MaybeODRUseExprs.end();
11017 i != e; ++i) {
11018 VarDecl *Var;
11019 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000011020 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000011021 Var = cast<VarDecl>(DRE->getDecl());
11022 Loc = DRE->getLocation();
11023 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11024 Var = cast<VarDecl>(ME->getMemberDecl());
11025 Loc = ME->getMemberLoc();
11026 } else {
11027 llvm_unreachable("Unexpcted expression");
11028 }
11029
11030 MarkVarDeclODRUsed(*this, Var, Loc);
11031 }
11032
11033 MaybeODRUseExprs.clear();
11034}
11035
11036// Mark a VarDecl referenced, and perform the necessary handling to compute
11037// odr-uses.
11038static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11039 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011040 Var->setReferenced();
11041
Eli Friedman3bda6b12012-02-02 23:15:15 +000011042 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000011043 return;
11044
11045 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000011046 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011047 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11048 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000011049 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11050 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000011051 (!AlreadyInstantiated ||
11052 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000011053 if (!AlreadyInstantiated) {
11054 // This is a modification of an existing AST node. Notify listeners.
11055 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11056 L->StaticDataMemberInstantiated(Var);
11057 MSInfo->setPointOfInstantiation(Loc);
11058 }
11059 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000011060 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000011061 // Do not defer instantiations of variables which could be used in a
11062 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000011063 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011064 else
Richard Smithd3cf2382012-02-15 02:42:50 +000011065 SemaRef.PendingInstantiations.push_back(
11066 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000011067 }
11068 }
11069
Richard Smith5a1104b2012-10-20 01:38:33 +000011070 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11071 // the requirements for appearing in a constant expression (5.19) and, if
11072 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedman3bda6b12012-02-02 23:15:15 +000011073 // is immediately applied." We check the first part here, and
11074 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11075 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5a1104b2012-10-20 01:38:33 +000011076 // C++03 depends on whether we get the C++03 version correct. The second
11077 // part does not apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000011078 const VarDecl *DefVD;
Richard Smith5a1104b2012-10-20 01:38:33 +000011079 if (E && !isa<ParmVarDecl>(Var) &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000011080 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Richard Smith5a1104b2012-10-20 01:38:33 +000011081 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11082 if (!Var->getType()->isReferenceType())
11083 SemaRef.MaybeODRUseExprs.insert(E);
11084 } else
Eli Friedman3bda6b12012-02-02 23:15:15 +000011085 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11086}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011087
Eli Friedman3bda6b12012-02-02 23:15:15 +000011088/// \brief Mark a variable referenced, and check whether it is odr-used
11089/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11090/// used directly for normal expressions referring to VarDecl.
11091void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11092 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011093}
11094
11095static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11096 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000011097 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11098 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11099 return;
11100 }
11101
Eli Friedmanfa0df832012-02-02 03:46:19 +000011102 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola49e860b2012-06-26 17:45:31 +000011103
11104 // If this is a call to a method via a cast, also mark the method in the
11105 // derived class used in case codegen can devirtualize the call.
11106 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11107 if (!ME)
11108 return;
11109 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11110 if (!MD)
11111 return;
11112 const Expr *Base = ME->getBase();
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000011113 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000011114 if (!MostDerivedClassDecl)
11115 return;
11116 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindolaa245edc2012-06-27 17:44:39 +000011117 if (!DM)
11118 return;
Rafael Espindola49e860b2012-06-26 17:45:31 +000011119 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011120}
Eli Friedmanfa0df832012-02-02 03:46:19 +000011121
Eli Friedmanfa0df832012-02-02 03:46:19 +000011122/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11123void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11124 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11125}
11126
11127/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11128void Sema::MarkMemberReferenced(MemberExpr *E) {
11129 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11130}
11131
Douglas Gregorf02455e2012-02-10 09:26:04 +000011132/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000011133/// marks the declaration referenced, and performs odr-use checking for functions
11134/// and variables. This method should not be used when building an normal
11135/// expression which refers to a variable.
11136void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11137 if (VarDecl *VD = dyn_cast<VarDecl>(D))
11138 MarkVariableReferenced(Loc, VD);
11139 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11140 MarkFunctionReferenced(Loc, FD);
11141 else
11142 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000011143}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011144
Douglas Gregor5597ab42010-05-07 23:12:07 +000011145namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000011146 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000011147 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000011148 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000011149 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11150 Sema &S;
11151 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011152
Douglas Gregor5597ab42010-05-07 23:12:07 +000011153 public:
11154 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000011155
Douglas Gregor5597ab42010-05-07 23:12:07 +000011156 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011157
11158 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11159 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011160 };
11161}
11162
Chandler Carruthaf80f662010-06-09 08:17:30 +000011163bool MarkReferencedDecls::TraverseTemplateArgument(
11164 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011165 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000011166 if (Decl *D = Arg.getAsDecl())
11167 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011168 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000011169
11170 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000011171}
11172
Chandler Carruthaf80f662010-06-09 08:17:30 +000011173bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000011174 if (ClassTemplateSpecializationDecl *Spec
11175 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11176 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000011177 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000011178 }
11179
Chandler Carruthc65667c2010-06-10 10:31:57 +000011180 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000011181}
11182
11183void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11184 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000011185 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000011186}
11187
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011188namespace {
11189 /// \brief Helper class that marks all of the declarations referenced by
11190 /// potentially-evaluated subexpressions as "referenced".
11191 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11192 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000011193 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011194
11195 public:
11196 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11197
Douglas Gregor680e9e02012-02-21 19:11:17 +000011198 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11199 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011200
11201 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000011202 // If we were asked not to visit local variables, don't.
11203 if (SkipLocalVariables) {
11204 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11205 if (VD->hasLocalStorage())
11206 return;
11207 }
11208
Eli Friedmanfa0df832012-02-02 03:46:19 +000011209 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011210 }
11211
11212 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011213 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000011214 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011215 }
11216
John McCall28fc7092011-11-10 05:35:25 +000011217 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011218 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000011219 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11220 Visit(E->getSubExpr());
11221 }
11222
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011223 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011224 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011225 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011226 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011227 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011228 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011229 }
Sebastian Redl6047f072012-02-16 12:22:20 +000011230
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011231 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11232 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000011233 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011234 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11235 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11236 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000011237 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000011238 S.LookupDestructor(Record));
11239 }
11240
Douglas Gregor32b3de52010-09-11 23:32:50 +000011241 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011242 }
11243
11244 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011245 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000011246 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011247 }
11248
Douglas Gregorf0873f42010-10-19 17:17:35 +000011249 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11250 Visit(E->getExpr());
11251 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000011252
11253 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11254 Inherited::VisitImplicitCastExpr(E);
11255
11256 if (E->getCastKind() == CK_LValueToRValue)
11257 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11258 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011259 };
11260}
11261
11262/// \brief Mark any declarations that appear within this expression or any
11263/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000011264///
11265/// \param SkipLocalVariables If true, don't mark local variables as
11266/// 'referenced'.
11267void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11268 bool SkipLocalVariables) {
11269 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011270}
11271
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011272/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11273/// of the program being compiled.
11274///
11275/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011276/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011277/// possibility that the code will actually be executable. Code in sizeof()
11278/// expressions, code used only during overload resolution, etc., are not
11279/// potentially evaluated. This routine will suppress such diagnostics or,
11280/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011281/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011282/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011283///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011284/// This routine should be used for all diagnostics that describe the run-time
11285/// behavior of a program, such as passing a non-POD value through an ellipsis.
11286/// Failure to do so will likely result in spurious diagnostics or failures
11287/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000011288bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011289 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000011290 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011291 case Unevaluated:
11292 // The argument will never be evaluated, so don't complain.
11293 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000011294
Richard Smith764d2fe2011-12-20 02:08:33 +000011295 case ConstantEvaluated:
11296 // Relevant diagnostics should be produced by constant evaluation.
11297 break;
11298
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011299 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000011300 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000011301 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000011302 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000011303 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000011304 }
11305 else
11306 Diag(Loc, PD);
11307
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011308 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000011309 }
11310
11311 return false;
11312}
11313
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011314bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11315 CallExpr *CE, FunctionDecl *FD) {
11316 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11317 return false;
11318
Richard Smithfd555f62012-02-22 02:04:18 +000011319 // If we're inside a decltype's expression, don't check for a valid return
11320 // type or construct temporaries until we know whether this is the last call.
11321 if (ExprEvalContexts.back().IsDecltype) {
11322 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11323 return false;
11324 }
11325
Douglas Gregora6c5abb2012-05-04 16:48:41 +000011326 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011327 FunctionDecl *FD;
11328 CallExpr *CE;
11329
11330 public:
11331 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11332 : FD(FD), CE(CE) { }
11333
11334 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11335 if (!FD) {
11336 S.Diag(Loc, diag::err_call_incomplete_return)
11337 << T << CE->getSourceRange();
11338 return;
11339 }
11340
11341 S.Diag(Loc, diag::err_call_function_incomplete_return)
11342 << CE->getSourceRange() << FD->getDeclName() << T;
11343 S.Diag(FD->getLocation(),
11344 diag::note_function_with_incomplete_return_type_declared_here)
11345 << FD->getDeclName();
11346 }
11347 } Diagnoser(FD, CE);
11348
11349 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011350 return true;
11351
11352 return false;
11353}
11354
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011355// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011356// will prevent this condition from triggering, which is what we want.
11357void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11358 SourceLocation Loc;
11359
John McCall0506e4a2009-11-11 02:41:58 +000011360 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011361 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011362
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011363 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011364 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011365 return;
11366
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011367 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11368
John McCallb0e419e2009-11-12 00:06:05 +000011369 // Greylist some idioms by putting them into a warning subcategory.
11370 if (ObjCMessageExpr *ME
11371 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11372 Selector Sel = ME->getSelector();
11373
John McCallb0e419e2009-11-12 00:06:05 +000011374 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011375 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011376 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11377
11378 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011379 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011380 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11381 }
John McCall0506e4a2009-11-11 02:41:58 +000011382
John McCalld5707ab2009-10-12 21:59:07 +000011383 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011384 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011385 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011386 return;
11387
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011388 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011389 Loc = Op->getOperatorLoc();
Fariborz Jahanianf07bcc52012-08-29 17:17:11 +000011390 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11391 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11392 else {
John McCalld5707ab2009-10-12 21:59:07 +000011393 // Not an assignment.
11394 return;
11395 }
11396
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011397 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011398
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011399 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011400 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11401 Diag(Loc, diag::note_condition_assign_silence)
11402 << FixItHint::CreateInsertion(Open, "(")
11403 << FixItHint::CreateInsertion(Close, ")");
11404
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011405 if (IsOrAssign)
11406 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11407 << FixItHint::CreateReplacement(Loc, "!=");
11408 else
11409 Diag(Loc, diag::note_condition_assign_to_comparison)
11410 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011411}
11412
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011413/// \brief Redundant parentheses over an equality comparison can indicate
11414/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011415void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011416 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011417 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011418 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11419 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011420 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011421 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011422 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011423
Richard Trieuba63ce62011-09-09 01:45:06 +000011424 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011425
11426 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011427 if (opE->getOpcode() == BO_EQ &&
11428 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11429 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011430 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011431
Ted Kremenekae022092011-02-02 02:20:30 +000011432 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011433 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011434 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011435 << FixItHint::CreateRemoval(ParenERange.getBegin())
11436 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011437 Diag(Loc, diag::note_equality_comparison_to_assign)
11438 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011439 }
11440}
11441
John Wiegley01296292011-04-08 18:41:53 +000011442ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011443 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011444 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11445 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011446
John McCall0009fcc2011-04-26 20:42:42 +000011447 ExprResult result = CheckPlaceholderExpr(E);
11448 if (result.isInvalid()) return ExprError();
11449 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011450
John McCall0009fcc2011-04-26 20:42:42 +000011451 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011452 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011453 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11454
John Wiegley01296292011-04-08 18:41:53 +000011455 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11456 if (ERes.isInvalid())
11457 return ExprError();
11458 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011459
11460 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011461 if (!T->isScalarType()) { // C99 6.8.4.1p1
11462 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11463 << T << E->getSourceRange();
11464 return ExprError();
11465 }
John McCalld5707ab2009-10-12 21:59:07 +000011466 }
11467
John Wiegley01296292011-04-08 18:41:53 +000011468 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011469}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011470
John McCalldadc5752010-08-24 06:29:42 +000011471ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011472 Expr *SubExpr) {
11473 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011474 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011475
Richard Trieuba63ce62011-09-09 01:45:06 +000011476 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011477}
John McCall36e7fe32010-10-12 00:20:44 +000011478
John McCall31996342011-04-07 08:22:57 +000011479namespace {
John McCall2979fe02011-04-12 00:42:48 +000011480 /// A visitor for rebuilding a call to an __unknown_any expression
11481 /// to have an appropriate type.
11482 struct RebuildUnknownAnyFunction
11483 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11484
11485 Sema &S;
11486
11487 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11488
11489 ExprResult VisitStmt(Stmt *S) {
11490 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011491 }
11492
Richard Trieu10162ab2011-09-09 03:59:41 +000011493 ExprResult VisitExpr(Expr *E) {
11494 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11495 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011496 return ExprError();
11497 }
11498
11499 /// Rebuild an expression which simply semantically wraps another
11500 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011501 template <class T> ExprResult rebuildSugarExpr(T *E) {
11502 ExprResult SubResult = Visit(E->getSubExpr());
11503 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011504
Richard Trieu10162ab2011-09-09 03:59:41 +000011505 Expr *SubExpr = SubResult.take();
11506 E->setSubExpr(SubExpr);
11507 E->setType(SubExpr->getType());
11508 E->setValueKind(SubExpr->getValueKind());
11509 assert(E->getObjectKind() == OK_Ordinary);
11510 return E;
John McCall2979fe02011-04-12 00:42:48 +000011511 }
11512
Richard Trieu10162ab2011-09-09 03:59:41 +000011513 ExprResult VisitParenExpr(ParenExpr *E) {
11514 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011515 }
11516
Richard Trieu10162ab2011-09-09 03:59:41 +000011517 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11518 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011519 }
11520
Richard Trieu10162ab2011-09-09 03:59:41 +000011521 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11522 ExprResult SubResult = Visit(E->getSubExpr());
11523 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011524
Richard Trieu10162ab2011-09-09 03:59:41 +000011525 Expr *SubExpr = SubResult.take();
11526 E->setSubExpr(SubExpr);
11527 E->setType(S.Context.getPointerType(SubExpr->getType()));
11528 assert(E->getValueKind() == VK_RValue);
11529 assert(E->getObjectKind() == OK_Ordinary);
11530 return E;
John McCall2979fe02011-04-12 00:42:48 +000011531 }
11532
Richard Trieu10162ab2011-09-09 03:59:41 +000011533 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11534 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011535
Richard Trieu10162ab2011-09-09 03:59:41 +000011536 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011537
Richard Trieu10162ab2011-09-09 03:59:41 +000011538 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011539 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011540 !(isa<CXXMethodDecl>(VD) &&
11541 cast<CXXMethodDecl>(VD)->isInstance()))
11542 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011543
Richard Trieu10162ab2011-09-09 03:59:41 +000011544 return E;
John McCall2979fe02011-04-12 00:42:48 +000011545 }
11546
Richard Trieu10162ab2011-09-09 03:59:41 +000011547 ExprResult VisitMemberExpr(MemberExpr *E) {
11548 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011549 }
11550
Richard Trieu10162ab2011-09-09 03:59:41 +000011551 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11552 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011553 }
11554 };
11555}
11556
11557/// Given a function expression of unknown-any type, try to rebuild it
11558/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011559static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11560 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11561 if (Result.isInvalid()) return ExprError();
11562 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011563}
11564
11565namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011566 /// A visitor for rebuilding an expression of type __unknown_anytype
11567 /// into one which resolves the type directly on the referring
11568 /// expression. Strict preservation of the original source
11569 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011570 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011571 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011572
11573 Sema &S;
11574
11575 /// The current destination type.
11576 QualType DestType;
11577
Richard Trieu10162ab2011-09-09 03:59:41 +000011578 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11579 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011580
John McCall39439732011-04-09 22:50:59 +000011581 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011582 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011583 }
11584
Richard Trieu10162ab2011-09-09 03:59:41 +000011585 ExprResult VisitExpr(Expr *E) {
11586 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11587 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011588 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011589 }
11590
Richard Trieu10162ab2011-09-09 03:59:41 +000011591 ExprResult VisitCallExpr(CallExpr *E);
11592 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011593
John McCall39439732011-04-09 22:50:59 +000011594 /// Rebuild an expression which simply semantically wraps another
11595 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011596 template <class T> ExprResult rebuildSugarExpr(T *E) {
11597 ExprResult SubResult = Visit(E->getSubExpr());
11598 if (SubResult.isInvalid()) return ExprError();
11599 Expr *SubExpr = SubResult.take();
11600 E->setSubExpr(SubExpr);
11601 E->setType(SubExpr->getType());
11602 E->setValueKind(SubExpr->getValueKind());
11603 assert(E->getObjectKind() == OK_Ordinary);
11604 return E;
John McCall39439732011-04-09 22:50:59 +000011605 }
John McCall31996342011-04-07 08:22:57 +000011606
Richard Trieu10162ab2011-09-09 03:59:41 +000011607 ExprResult VisitParenExpr(ParenExpr *E) {
11608 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011609 }
11610
Richard Trieu10162ab2011-09-09 03:59:41 +000011611 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11612 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011613 }
11614
Richard Trieu10162ab2011-09-09 03:59:41 +000011615 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11616 const PointerType *Ptr = DestType->getAs<PointerType>();
11617 if (!Ptr) {
11618 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11619 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011620 return ExprError();
11621 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011622 assert(E->getValueKind() == VK_RValue);
11623 assert(E->getObjectKind() == OK_Ordinary);
11624 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011625
11626 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011627 DestType = Ptr->getPointeeType();
11628 ExprResult SubResult = Visit(E->getSubExpr());
11629 if (SubResult.isInvalid()) return ExprError();
11630 E->setSubExpr(SubResult.take());
11631 return E;
John McCall2979fe02011-04-12 00:42:48 +000011632 }
11633
Richard Trieu10162ab2011-09-09 03:59:41 +000011634 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011635
Richard Trieu10162ab2011-09-09 03:59:41 +000011636 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011637
Richard Trieu10162ab2011-09-09 03:59:41 +000011638 ExprResult VisitMemberExpr(MemberExpr *E) {
11639 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011640 }
John McCall39439732011-04-09 22:50:59 +000011641
Richard Trieu10162ab2011-09-09 03:59:41 +000011642 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11643 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011644 }
11645 };
11646}
11647
John McCall2d2e8702011-04-11 07:02:50 +000011648/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011649ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11650 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011651
11652 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011653 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011654 FK_FunctionPointer,
11655 FK_BlockPointer
11656 };
11657
Richard Trieu10162ab2011-09-09 03:59:41 +000011658 FnKind Kind;
11659 QualType CalleeType = CalleeExpr->getType();
11660 if (CalleeType == S.Context.BoundMemberTy) {
11661 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11662 Kind = FK_MemberFunction;
11663 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11664 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11665 CalleeType = Ptr->getPointeeType();
11666 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011667 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011668 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11669 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011670 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011671 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011672
11673 // Verify that this is a legal result type of a function.
11674 if (DestType->isArrayType() || DestType->isFunctionType()) {
11675 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011676 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011677 diagID = diag::err_block_returning_array_function;
11678
Richard Trieu10162ab2011-09-09 03:59:41 +000011679 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011680 << DestType->isFunctionType() << DestType;
11681 return ExprError();
11682 }
11683
11684 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011685 E->setType(DestType.getNonLValueExprType(S.Context));
11686 E->setValueKind(Expr::getValueKindForType(DestType));
11687 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011688
11689 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011690 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011691 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011692 Proto->arg_type_begin(),
11693 Proto->getNumArgs(),
11694 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011695 else
11696 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011697 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011698
11699 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011700 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011701 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011702 // Nothing to do.
11703 break;
11704
11705 case FK_FunctionPointer:
11706 DestType = S.Context.getPointerType(DestType);
11707 break;
11708
11709 case FK_BlockPointer:
11710 DestType = S.Context.getBlockPointerType(DestType);
11711 break;
11712 }
11713
11714 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011715 ExprResult CalleeResult = Visit(CalleeExpr);
11716 if (!CalleeResult.isUsable()) return ExprError();
11717 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011718
11719 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011720 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011721}
11722
Richard Trieu10162ab2011-09-09 03:59:41 +000011723ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011724 // Verify that this is a legal result type of a call.
11725 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011726 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011727 << DestType->isFunctionType() << DestType;
11728 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011729 }
11730
John McCall3f4138c2011-07-13 17:56:40 +000011731 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011732 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11733 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11734 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011735 }
John McCall2979fe02011-04-12 00:42:48 +000011736
John McCall2d2e8702011-04-11 07:02:50 +000011737 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011738 E->setType(DestType.getNonReferenceType());
11739 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011740
Richard Trieu10162ab2011-09-09 03:59:41 +000011741 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011742}
11743
Richard Trieu10162ab2011-09-09 03:59:41 +000011744ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011745 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011746 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011747 assert(E->getValueKind() == VK_RValue);
11748 assert(E->getObjectKind() == OK_Ordinary);
11749
11750 E->setType(DestType);
11751
11752 // Rebuild the sub-expression as the pointee (function) type.
11753 DestType = DestType->castAs<PointerType>()->getPointeeType();
11754
11755 ExprResult Result = Visit(E->getSubExpr());
11756 if (!Result.isUsable()) return ExprError();
11757
11758 E->setSubExpr(Result.take());
11759 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011760 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011761 assert(E->getValueKind() == VK_RValue);
11762 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011763
Sean Callanan12495112012-03-06 21:34:12 +000011764 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011765
Sean Callanan12495112012-03-06 21:34:12 +000011766 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011767
Sean Callanan12495112012-03-06 21:34:12 +000011768 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11769 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011770
Sean Callanan12495112012-03-06 21:34:12 +000011771 ExprResult Result = Visit(E->getSubExpr());
11772 if (!Result.isUsable()) return ExprError();
11773
11774 E->setSubExpr(Result.take());
11775 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011776 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011777 llvm_unreachable("Unhandled cast type!");
11778 }
John McCall2d2e8702011-04-11 07:02:50 +000011779}
11780
Richard Trieu10162ab2011-09-09 03:59:41 +000011781ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11782 ExprValueKind ValueKind = VK_LValue;
11783 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011784
11785 // We know how to make this work for certain kinds of decls:
11786
11787 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011788 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11789 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11790 DestType = Ptr->getPointeeType();
11791 ExprResult Result = resolveDecl(E, VD);
11792 if (Result.isInvalid()) return ExprError();
11793 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011794 CK_FunctionToPointerDecay, VK_RValue);
11795 }
11796
Richard Trieu10162ab2011-09-09 03:59:41 +000011797 if (!Type->isFunctionType()) {
11798 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11799 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011800 return ExprError();
11801 }
John McCall2d2e8702011-04-11 07:02:50 +000011802
Richard Trieu10162ab2011-09-09 03:59:41 +000011803 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11804 if (MD->isInstance()) {
11805 ValueKind = VK_RValue;
11806 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011807 }
11808
John McCall2d2e8702011-04-11 07:02:50 +000011809 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011810 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011811 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011812
11813 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011814 } else if (isa<VarDecl>(VD)) {
11815 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11816 Type = RefTy->getPointeeType();
11817 } else if (Type->isFunctionType()) {
11818 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11819 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011820 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011821 }
11822
11823 // - nothing else
11824 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011825 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11826 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011827 return ExprError();
11828 }
11829
Richard Trieu10162ab2011-09-09 03:59:41 +000011830 VD->setType(DestType);
11831 E->setType(Type);
11832 E->setValueKind(ValueKind);
11833 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011834}
11835
John McCall31996342011-04-07 08:22:57 +000011836/// Check a cast of an unknown-any type. We intentionally only
11837/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011838ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11839 Expr *CastExpr, CastKind &CastKind,
11840 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011841 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011842 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011843 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011844
Richard Trieuba63ce62011-09-09 01:45:06 +000011845 CastExpr = result.take();
11846 VK = CastExpr->getValueKind();
11847 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011848
Richard Trieuba63ce62011-09-09 01:45:06 +000011849 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011850}
11851
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011852ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11853 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11854}
11855
John McCallea0a39e2012-11-14 00:49:39 +000011856QualType Sema::checkUnknownAnyArg(Expr *&arg) {
11857 // Filter out placeholders.
11858 ExprResult argR = CheckPlaceholderExpr(arg);
11859 if (argR.isInvalid()) return QualType();
11860 arg = argR.take();
11861
11862 // If the argument is an explicit cast, use that exact type as the
11863 // effective parameter type.
11864 if (ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg)) {
11865 return castArg->getTypeAsWritten();
11866 }
11867
11868 // Otherwise, try to pass by value.
11869 return arg->getType().getUnqualifiedType();
11870}
11871
Richard Trieuba63ce62011-09-09 01:45:06 +000011872static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11873 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011874 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011875 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011876 E = E->IgnoreParenImpCasts();
11877 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11878 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011879 diagID = diag::err_uncasted_call_of_unknown_any;
11880 } else {
John McCall31996342011-04-07 08:22:57 +000011881 break;
John McCall2d2e8702011-04-11 07:02:50 +000011882 }
John McCall31996342011-04-07 08:22:57 +000011883 }
11884
John McCall2d2e8702011-04-11 07:02:50 +000011885 SourceLocation loc;
11886 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011887 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011888 loc = ref->getLocation();
11889 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011890 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011891 loc = mem->getMemberLoc();
11892 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011893 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011894 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011895 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011896 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011897 if (!d) {
11898 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11899 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11900 << orig->getSourceRange();
11901 return ExprError();
11902 }
John McCall2d2e8702011-04-11 07:02:50 +000011903 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011904 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11905 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011906 return ExprError();
11907 }
11908
11909 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011910
11911 // Never recoverable.
11912 return ExprError();
11913}
11914
John McCall36e7fe32010-10-12 00:20:44 +000011915/// Check for operands with placeholder types and complain if found.
11916/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011917ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011918 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11919 if (!placeholderType) return Owned(E);
11920
11921 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011922
John McCall31996342011-04-07 08:22:57 +000011923 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011924 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011925 // Try to resolve a single function template specialization.
11926 // This is obligatory.
11927 ExprResult result = Owned(E);
11928 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11929 return result;
11930
11931 // If that failed, try to recover with a call.
11932 } else {
11933 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11934 /*complain*/ true);
11935 return result;
11936 }
11937 }
John McCall31996342011-04-07 08:22:57 +000011938
John McCall0009fcc2011-04-26 20:42:42 +000011939 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011940 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011941 ExprResult result = Owned(E);
11942 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11943 /*complain*/ true);
11944 return result;
John McCall4124c492011-10-17 18:40:02 +000011945 }
11946
11947 // ARC unbridged casts.
11948 case BuiltinType::ARCUnbridgedCast: {
11949 Expr *realCast = stripARCUnbridgedCast(E);
11950 diagnoseARCUnbridgedCast(realCast);
11951 return Owned(realCast);
11952 }
John McCall0009fcc2011-04-26 20:42:42 +000011953
John McCall31996342011-04-07 08:22:57 +000011954 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011955 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011956 return diagnoseUnknownAnyExpr(*this, E);
11957
John McCall526ab472011-10-25 17:37:35 +000011958 // Pseudo-objects.
11959 case BuiltinType::PseudoObject:
11960 return checkPseudoObjectRValue(E);
11961
Eli Friedman34866c72012-08-31 00:14:07 +000011962 case BuiltinType::BuiltinFn:
11963 Diag(E->getLocStart(), diag::err_builtin_fn_use);
11964 return ExprError();
11965
John McCalle314e272011-10-18 21:02:43 +000011966 // Everything else should be impossible.
11967#define BUILTIN_TYPE(Id, SingletonId) \
11968 case BuiltinType::Id:
11969#define PLACEHOLDER_TYPE(Id, SingletonId)
11970#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011971 break;
11972 }
11973
11974 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011975}
Richard Trieu2c850c02011-04-21 21:44:26 +000011976
Richard Trieuba63ce62011-09-09 01:45:06 +000011977bool Sema::CheckCaseExpression(Expr *E) {
11978 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011979 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011980 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11981 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011982 return false;
11983}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011984
11985/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11986ExprResult
11987Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11988 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11989 "Unknown Objective-C Boolean value!");
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011990 QualType BoolT = Context.ObjCBuiltinBoolTy;
11991 if (!Context.getBOOLDecl()) {
Fariborz Jahanianeab17302012-10-16 17:08:11 +000011992 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011993 Sema::LookupOrdinaryName);
Fariborz Jahanian379e5362012-10-16 16:21:20 +000011994 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanianf2578572012-08-30 18:49:41 +000011995 NamedDecl *ND = Result.getFoundDecl();
11996 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11997 Context.setBOOLDecl(TD);
11998 }
11999 }
12000 if (Context.getBOOLDecl())
12001 BoolT = Context.getBOOLType();
Ted Kremeneke65b0862012-03-06 20:05:56 +000012002 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanianf2578572012-08-30 18:49:41 +000012003 BoolT, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000012004}