blob: 74296f1335e5222c3d35960401caedcf6e79ea22 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedman93c878e2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks67221552011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedmanef331b72012-01-20 01:26:23 +000044#include "TreeTransform.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000046using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000047
Sebastian Redl14b0c192011-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 Redl28bdb142011-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 Redl14b0c192011-09-24 17:48:00 +000066 return true;
67}
David Chisnall0f436562009-08-17 16:35:33 +000068
Ted Kremenekd6cf9122012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenekd6cf9122012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenekd6cf9122012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000096 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith6c4c36c2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith5bdaac52012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Jordan Rose0eb3f452012-06-18 22:09:19 +0000133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137 E = D->redecls_end();
138 I != E; ++I) {
139 if (I->getStorageClassAsWritten() != SC_None)
140 return true;
141 }
142 return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000146/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000147///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000148/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000149/// in many cases it will not behave correctly. This is not enabled in C++ mode
150/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151/// and so while there may still be user mistakes, most of the time we can't
152/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000153static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154 const NamedDecl *D,
155 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000156 // This is disabled under C++; there are too many ways for this to fire in
157 // contexts where the warning is a false positive, or where it is technically
158 // correct but benign.
159 if (S.getLangOpts().CPlusPlus)
160 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000161
162 // Check if this is an inlined function or method.
163 FunctionDecl *Current = S.getCurFunctionDecl();
164 if (!Current)
165 return;
166 if (!Current->isInlined())
167 return;
168 if (Current->getLinkage() != ExternalLinkage)
169 return;
170
171 // Check if the decl has internal linkage.
Jordan Rose33c0f372012-06-20 18:50:06 +0000172 if (D->getLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000173 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000174
Jordan Rose05233272012-06-21 05:54:50 +0000175 // Downgrade from ExtWarn to Extension if
176 // (1) the supposedly external inline function is in the main file,
177 // and probably won't be included anywhere else.
178 // (2) the thing we're referencing is a pure function.
179 // (3) the thing we're referencing is another inline function.
180 // This last can give us false negatives, but it's better than warning on
181 // wrappers for simple C library functions.
182 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184 if (!DowngradeWarning && UsedFn)
185 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186
187 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188 : diag::warn_internal_in_extern_inline)
189 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000190
191 // Suggest "static" on the inline function, if possible.
Jordan Rose33c0f372012-06-20 18:50:06 +0000192 if (!hasAnyExplicitStorageClass(Current)) {
Jordan Rose0eb3f452012-06-18 22:09:19 +0000193 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195 S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197 }
198
199 S.Diag(D->getCanonicalDecl()->getLocation(),
200 diag::note_internal_decl_declared_here)
201 << D;
202}
203
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000204/// \brief Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000215///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000217 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000219 // If there were any diagnostics suppressed by template argument deduction,
220 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000222 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000224 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000225 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226 Diag(Suppressed[I].first, Suppressed[I].second);
227
228 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000229 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000230 // entry from the table, because we want to avoid ever emitting these
231 // diagnostics again.
232 Suppressed.clear();
233 }
234 }
235
Richard Smith34b41d92011-02-20 03:19:35 +0000236 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000237 if (ParsingInitForAutoVars.count(D)) {
238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239 << D->getDeclName();
240 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000241 }
242
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000243 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000245 if (FD->isDeleted()) {
246 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000247 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000248 return true;
249 }
Douglas Gregor25d944a2009-02-24 04:26:15 +0000250 }
Ted Kremenekd6cf9122012-02-10 02:45:47 +0000251 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000252
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000253 // Warn if this is used but marked unused.
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000254 if (D->hasAttr<UnusedAttr>())
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000255 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose106af9e2012-06-15 18:19:48 +0000256
Jordan Rose0eb3f452012-06-18 22:09:19 +0000257 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000258
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000259 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000260}
261
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000262/// \brief Retrieve the message suffix that should be added to a
263/// diagnostic complaining about the given function being deleted or
264/// unavailable.
265std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266 // FIXME: C++0x implicitly-deleted special member functions could be
267 // detected here so that we could improve diagnostics to say, e.g.,
268 // "base class 'A' had a deleted copy constructor".
269 if (FD->isDeleted())
270 return std::string();
271
272 std::string Message;
273 if (FD->getAvailability(&Message))
274 return ": " + Message;
275
276 return std::string();
277}
278
John McCall3323fad2011-09-09 07:56:05 +0000279/// DiagnoseSentinelCalls - This routine checks whether a call or
280/// message-send is to a declaration with the sentinel attribute, and
281/// if so, it checks that the requirements of the sentinel are
282/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000283void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCall3323fad2011-09-09 07:56:05 +0000284 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000285 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000286 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000287 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000288
John McCall3323fad2011-09-09 07:56:05 +0000289 // The number of formal parameters of the declaration.
290 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000291
John McCall3323fad2011-09-09 07:56:05 +0000292 // The kind of declaration. This is also an index into a %select in
293 // the diagnostic.
294 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000297 numFormalParams = MD->param_size();
298 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000299 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000300 numFormalParams = FD->param_size();
301 calleeType = CT_Function;
302 } else if (isa<VarDecl>(D)) {
303 QualType type = cast<ValueDecl>(D)->getType();
304 const FunctionType *fn = 0;
305 if (const PointerType *ptr = type->getAs<PointerType>()) {
306 fn = ptr->getPointeeType()->getAs<FunctionType>();
307 if (!fn) return;
308 calleeType = CT_Function;
309 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310 fn = ptr->getPointeeType()->castAs<FunctionType>();
311 calleeType = CT_Block;
312 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000313 return;
John McCall3323fad2011-09-09 07:56:05 +0000314 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000315
John McCall3323fad2011-09-09 07:56:05 +0000316 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317 numFormalParams = proto->getNumArgs();
318 } else {
319 numFormalParams = 0;
320 }
321 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000322 return;
323 }
John McCall3323fad2011-09-09 07:56:05 +0000324
325 // "nullPos" is the number of formal parameters at the end which
326 // effectively count as part of the variadic arguments. This is
327 // useful if you would prefer to not have *any* formal parameters,
328 // but the language forces you to have at least one.
329 unsigned nullPos = attr->getNullPos();
330 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332
333 // The number of arguments which should follow the sentinel.
334 unsigned numArgsAfterSentinel = attr->getSentinel();
335
336 // If there aren't enough arguments for all the formal parameters,
337 // the sentinel, and the args after the sentinel, complain.
338 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000339 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCall3323fad2011-09-09 07:56:05 +0000340 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000341 return;
342 }
John McCall3323fad2011-09-09 07:56:05 +0000343
344 // Otherwise, find the sentinel expression.
345 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000346 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000347 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000348 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000349
John McCall3323fad2011-09-09 07:56:05 +0000350 // Pick a reasonable string to insert. Optimistically use 'nil' or
351 // 'NULL' if those are actually defined in the context. Only use
352 // 'nil' for ObjC methods, where it's much more likely that the
353 // variadic arguments form a list of object pointers.
354 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000355 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000357 if (calleeType == CT_Method &&
358 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000359 NullValue = "nil";
360 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000362 else
John McCall3323fad2011-09-09 07:56:05 +0000363 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000364
365 if (MissingNilLoc.isInvalid())
366 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367 else
368 Diag(MissingNilLoc, diag::warn_missing_sentinel)
369 << calleeType
370 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall3323fad2011-09-09 07:56:05 +0000371 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000372}
373
Richard Trieuccd891a2011-09-09 01:45:06 +0000374SourceRange Sema::getExprRange(Expr *E) const {
375 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000376}
377
Chris Lattnere7a2e912008-07-25 21:10:04 +0000378//===----------------------------------------------------------------------===//
379// Standard Promotions and Conversions
380//===----------------------------------------------------------------------===//
381
Chris Lattnere7a2e912008-07-25 21:10:04 +0000382/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000383ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000384 // Handle any placeholder expressions which made it here.
385 if (E->getType()->isPlaceholderType()) {
386 ExprResult result = CheckPlaceholderExpr(E);
387 if (result.isInvalid()) return ExprError();
388 E = result.take();
389 }
390
Chris Lattnere7a2e912008-07-25 21:10:04 +0000391 QualType Ty = E->getType();
392 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393
Chris Lattnere7a2e912008-07-25 21:10:04 +0000394 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000395 E = ImpCastExprToType(E, Context.getPointerType(Ty),
396 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000397 else if (Ty->isArrayType()) {
398 // In C90 mode, arrays only promote to pointers if the array expression is
399 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400 // type 'array of type' is converted to an expression that has type 'pointer
401 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
402 // that has type 'array of type' ...". The relevant change is "an lvalue"
403 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000404 //
405 // C++ 4.2p1:
406 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407 // T" can be converted to an rvalue of type "pointer to T".
408 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000412 }
John Wiegley429bb272011-04-08 18:41:53 +0000413 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000414}
415
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000416static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417 // Check to see if we are dereferencing a null pointer. If so,
418 // and if not volatile-qualified, this is undefined behavior that the
419 // optimizer will delete, so warn about it. People sometimes try to use this
420 // to get a deterministic trap and are surprised by clang's behavior. This
421 // only handles the pattern "*null", which is a very syntactic check.
422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423 if (UO->getOpcode() == UO_Deref &&
424 UO->getSubExpr()->IgnoreParenCasts()->
425 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426 !UO->getType().isVolatileQualified()) {
427 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428 S.PDiag(diag::warn_indirection_through_null)
429 << UO->getSubExpr()->getSourceRange());
430 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431 S.PDiag(diag::note_indirection_through_null));
432 }
433}
434
John Wiegley429bb272011-04-08 18:41:53 +0000435ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000436 // Handle any placeholder expressions which made it here.
437 if (E->getType()->isPlaceholderType()) {
438 ExprResult result = CheckPlaceholderExpr(E);
439 if (result.isInvalid()) return ExprError();
440 E = result.take();
441 }
442
John McCall0ae287a2010-12-01 04:43:34 +0000443 // C++ [conv.lval]p1:
444 // A glvalue of a non-function, non-array type T can be
445 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000446 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000447
John McCall409fa9a2010-12-06 20:48:59 +0000448 QualType T = E->getType();
449 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000450
John McCall409fa9a2010-12-06 20:48:59 +0000451 // We don't want to throw lvalue-to-rvalue casts on top of
452 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000453 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000454 (E->getType() == Context.OverloadTy ||
455 T->isDependentType() ||
456 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000457 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000458
459 // The C standard is actually really unclear on this point, and
460 // DR106 tells us what the result should be but not why. It's
461 // generally best to say that void types just doesn't undergo
462 // lvalue-to-rvalue at all. Note that expressions of unqualified
463 // 'void' type are never l-values, but qualified void can be.
464 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000465 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000466
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000467 CheckForNullPointerDereference(*this, E);
468
John McCall409fa9a2010-12-06 20:48:59 +0000469 // C++ [conv.lval]p1:
470 // [...] If T is a non-class type, the type of the prvalue is the
471 // cv-unqualified version of T. Otherwise, the type of the
472 // rvalue is T.
473 //
474 // C99 6.3.2.1p2:
475 // If the lvalue has qualified type, the value has the unqualified
476 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000477 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000478 if (T.hasQualifiers())
479 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000480
Eli Friedmand2cce132012-02-02 23:15:15 +0000481 UpdateMarkingForLValueToRValue(E);
482
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000483 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484 E, 0, VK_RValue));
485
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000486 // C11 6.3.2.1p2:
487 // ... if the lvalue has atomic type, the value has the non-atomic version
488 // of the type of the lvalue ...
489 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490 T = Atomic->getValueType().getUnqualifiedType();
491 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492 Res.get(), 0, VK_RValue));
493 }
494
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000495 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000496}
497
John Wiegley429bb272011-04-08 18:41:53 +0000498ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499 ExprResult Res = DefaultFunctionArrayConversion(E);
500 if (Res.isInvalid())
501 return ExprError();
502 Res = DefaultLvalueConversion(Res.take());
503 if (Res.isInvalid())
504 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000505 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000506}
507
508
Chris Lattnere7a2e912008-07-25 21:10:04 +0000509/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000510/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000511/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000512/// apply if the array is an argument to the sizeof or address (&) operators.
513/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000514ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000515 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000516 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517 if (Res.isInvalid())
518 return Owned(E);
519 E = Res.take();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000520
John McCall0ae287a2010-12-01 04:43:34 +0000521 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000522 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000523
524 // Half FP is a bit different: it's a storage-only type, meaning that any
525 // "use" of it should be promoted to float.
526 if (Ty->isHalfType())
527 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528
John McCall0ae287a2010-12-01 04:43:34 +0000529 // Try to perform integral promotions if the object has a theoretically
530 // promotable type.
531 if (Ty->isIntegralOrUnscopedEnumerationType()) {
532 // C99 6.3.1.1p2:
533 //
534 // The following may be used in an expression wherever an int or
535 // unsigned int may be used:
536 // - an object or expression with an integer type whose integer
537 // conversion rank is less than or equal to the rank of int
538 // and unsigned int.
539 // - A bit-field of type _Bool, int, signed int, or unsigned int.
540 //
541 // If an int can represent all values of the original type, the
542 // value is converted to an int; otherwise, it is converted to an
543 // unsigned int. These are called the integer promotions. All
544 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000545
John McCall0ae287a2010-12-01 04:43:34 +0000546 QualType PTy = Context.isPromotableBitField(E);
547 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000548 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000550 }
551 if (Ty->isPromotableIntegerType()) {
552 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000553 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000555 }
Eli Friedman04e83572009-08-20 04:21:42 +0000556 }
John Wiegley429bb272011-04-08 18:41:53 +0000557 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000558}
559
Chris Lattner05faf172008-07-25 22:25:12 +0000560/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000561/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000562/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000563ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000565 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000566
John Wiegley429bb272011-04-08 18:41:53 +0000567 ExprResult Res = UsualUnaryConversions(E);
568 if (Res.isInvalid())
569 return Owned(E);
570 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000571
Chris Lattner05faf172008-07-25 22:25:12 +0000572 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000573 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000574 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575
John McCall96a914a2011-08-27 22:06:17 +0000576 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000577 // promotion, even on class types, but note:
578 // C++11 [conv.lval]p2:
579 // When an lvalue-to-rvalue conversion occurs in an unevaluated
580 // operand or a subexpression thereof the value contained in the
581 // referenced object is not accessed. Otherwise, if the glvalue
582 // has a class type, the conversion copy-initializes a temporary
583 // of type T from the glvalue and the result of the conversion
584 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000585 // FIXME: add some way to gate this entire thing for correctness in
586 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000587 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000588 ExprResult Temp = PerformCopyInitialization(
589 InitializedEntity::InitializeTemporary(E->getType()),
590 E->getExprLoc(),
591 Owned(E));
592 if (Temp.isInvalid())
593 return ExprError();
594 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000595 }
596
John Wiegley429bb272011-04-08 18:41:53 +0000597 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000598}
599
Richard Smith831421f2012-06-25 20:30:08 +0000600/// Determine the degree of POD-ness for an expression.
601/// Incomplete types are considered POD, since this check can be performed
602/// when we're in an unevaluated context.
603Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000604 if (Ty->isIncompleteType()) {
605 if (Ty->isObjCObjectType())
606 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000607 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000608 }
609
610 if (Ty.isCXX98PODType(Context))
611 return VAK_Valid;
612
Richard Smith831421f2012-06-25 20:30:08 +0000613 // C++0x [expr.call]p7:
614 // Passing a potentially-evaluated argument of class type (Clause 9)
615 // having a non-trivial copy constructor, a non-trivial move constructor,
616 // or a non-trivial destructor, with no corresponding parameter,
617 // is conditionally-supported with implementation-defined semantics.
Richard Smith831421f2012-06-25 20:30:08 +0000618 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
619 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
620 if (Record->hasTrivialCopyConstructor() &&
621 Record->hasTrivialMoveConstructor() &&
622 Record->hasTrivialDestructor())
623 return VAK_ValidInCXX11;
624
625 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
626 return VAK_Valid;
627 return VAK_Invalid;
628}
629
630bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
631 // Don't allow one to pass an Objective-C interface to a vararg.
632 const QualType & Ty = E->getType();
633
634 // Complain about passing non-POD types through varargs.
635 switch (isValidVarArgType(Ty)) {
636 case VAK_Valid:
637 break;
638 case VAK_ValidInCXX11:
639 DiagRuntimeBehavior(E->getLocStart(), 0,
640 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
641 << E->getType() << CT);
642 break;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000643 case VAK_Invalid: {
644 if (Ty->isObjCObjectType())
645 return DiagRuntimeBehavior(E->getLocStart(), 0,
646 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
647 << Ty << CT);
648
Richard Smith831421f2012-06-25 20:30:08 +0000649 return DiagRuntimeBehavior(E->getLocStart(), 0,
650 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
651 << getLangOpts().CPlusPlus0x << Ty << CT);
652 }
Jordan Roseddcfbc92012-07-19 18:10:23 +0000653 }
Richard Smith831421f2012-06-25 20:30:08 +0000654 // c++ rules are enforced elsewhere.
655 return false;
656}
657
Chris Lattner312531a2009-04-12 08:11:20 +0000658/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000659/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000660ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000661 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000662 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000663 // Strip the unbridged-cast placeholder expression off, if applicable.
664 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
665 (CT == VariadicMethod ||
666 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
667 E = stripARCUnbridgedCast(E);
668
669 // Otherwise, do normal placeholder checking.
670 } else {
671 ExprResult ExprRes = CheckPlaceholderExpr(E);
672 if (ExprRes.isInvalid())
673 return ExprError();
674 E = ExprRes.take();
675 }
676 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000677
John McCall5acb0c92011-10-17 18:40:02 +0000678 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000679 if (ExprRes.isInvalid())
680 return ExprError();
681 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Richard Smith831421f2012-06-25 20:30:08 +0000683 // Diagnostics regarding non-POD argument types are
684 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith83ea5302012-06-27 20:23:58 +0000685 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
Richard Smith831421f2012-06-25 20:30:08 +0000686 // Turn this into a trap.
687 CXXScopeSpec SS;
688 SourceLocation TemplateKWLoc;
689 UnqualifiedId Name;
690 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
691 E->getLocStart());
692 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
693 Name, true, false);
694 if (TrapFn.isInvalid())
695 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000696
Richard Smith831421f2012-06-25 20:30:08 +0000697 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
698 E->getLocStart(), MultiExprArg(),
699 E->getLocEnd());
700 if (Call.isInvalid())
701 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000702
Richard Smith831421f2012-06-25 20:30:08 +0000703 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
704 Call.get(), E);
705 if (Comma.isInvalid())
706 return ExprError();
707 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000708 }
Richard Smith831421f2012-06-25 20:30:08 +0000709
David Blaikie4e4d0842012-03-11 07:00:24 +0000710 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000711 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000712 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000713 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000714
John Wiegley429bb272011-04-08 18:41:53 +0000715 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000716}
717
Richard Trieu8289f492011-09-02 20:58:51 +0000718/// \brief Converts an integer to complex float type. Helper function of
719/// UsualArithmeticConversions()
720///
721/// \return false if the integer expression is an integer type and is
722/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000723static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
724 ExprResult &ComplexExpr,
725 QualType IntTy,
726 QualType ComplexTy,
727 bool SkipCast) {
728 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
729 if (SkipCast) return false;
730 if (IntTy->isIntegerType()) {
731 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
732 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
733 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000734 CK_FloatingRealToComplex);
735 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000736 assert(IntTy->isComplexIntegerType());
737 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000738 CK_IntegralComplexToFloatingComplex);
739 }
740 return false;
741}
742
743/// \brief Takes two complex float types and converts them to the same type.
744/// Helper function of UsualArithmeticConversions()
745static QualType
Richard Trieucafd30b2011-09-06 18:25:09 +0000746handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
747 ExprResult &RHS, QualType LHSType,
748 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000749 bool IsCompAssign) {
Richard Trieucafd30b2011-09-06 18:25:09 +0000750 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000751
752 if (order < 0) {
753 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000754 if (!IsCompAssign)
Richard Trieucafd30b2011-09-06 18:25:09 +0000755 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
756 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000757 }
758 if (order > 0)
759 // _Complex float -> _Complex double
Richard Trieucafd30b2011-09-06 18:25:09 +0000760 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
761 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000762}
763
764/// \brief Converts otherExpr to complex float and promotes complexExpr if
765/// necessary. Helper function of UsualArithmeticConversions()
766static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuccd891a2011-09-09 01:45:06 +0000767 ExprResult &ComplexExpr,
768 ExprResult &OtherExpr,
769 QualType ComplexTy,
770 QualType OtherTy,
771 bool ConvertComplexExpr,
772 bool ConvertOtherExpr) {
773 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000774
775 // If just the complexExpr is complex, the otherExpr needs to be converted,
776 // and the complexExpr might need to be promoted.
777 if (order > 0) { // complexExpr is wider
778 // float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000779 if (ConvertOtherExpr) {
780 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
781 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
782 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000783 CK_FloatingRealToComplex);
784 }
Richard Trieuccd891a2011-09-09 01:45:06 +0000785 return ComplexTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000786 }
787
788 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000789 QualType result = (order == 0 ? ComplexTy :
790 S.Context.getComplexType(OtherTy));
Richard Trieu8289f492011-09-02 20:58:51 +0000791
792 // double -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000793 if (ConvertOtherExpr)
794 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000795 CK_FloatingRealToComplex);
796
797 // _Complex float -> _Complex double
Richard Trieuccd891a2011-09-09 01:45:06 +0000798 if (ConvertComplexExpr && order < 0)
799 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000800 CK_FloatingComplexCast);
801
802 return result;
803}
804
805/// \brief Handle arithmetic conversion with complex types. Helper function of
806/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000807static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
808 ExprResult &RHS, QualType LHSType,
809 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000810 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000811 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000812 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000813 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000814 return LHSType;
815 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000816 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +0000817 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000818
819 // This handles complex/complex, complex/float, or float/complex.
820 // When both operands are complex, the shorter operand is converted to the
821 // type of the longer, and that is the type of the result. This corresponds
822 // to what is done when combining two real floating-point operands.
823 // The fun begins when size promotion occur across type domains.
824 // From H&S 6.3.4: When one operand is complex and the other is a real
825 // floating-point type, the less precise type is converted, within it's
826 // real or complex domain, to the precision of the other type. For example,
827 // when combining a "long double" with a "double _Complex", the
828 // "double _Complex" is promoted to "long double _Complex".
829
Richard Trieucafd30b2011-09-06 18:25:09 +0000830 bool LHSComplexFloat = LHSType->isComplexType();
831 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu8289f492011-09-02 20:58:51 +0000832
833 // If both are complex, just cast to the more precise type.
834 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieucafd30b2011-09-06 18:25:09 +0000835 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
836 LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000837 IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000838
839 // If only one operand is complex, promote it if necessary and convert the
840 // other operand to complex.
841 if (LHSComplexFloat)
842 return handleOtherComplexFloatConversion(
Richard Trieuccd891a2011-09-09 01:45:06 +0000843 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000844 /*convertOtherExpr*/ true);
845
846 assert(RHSComplexFloat);
847 return handleOtherComplexFloatConversion(
Richard Trieucafd30b2011-09-06 18:25:09 +0000848 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000849 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000850}
851
852/// \brief Hande arithmetic conversion from integer to float. Helper function
853/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +0000854static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
855 ExprResult &IntExpr,
856 QualType FloatTy, QualType IntTy,
857 bool ConvertFloat, bool ConvertInt) {
858 if (IntTy->isIntegerType()) {
859 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +0000860 // Convert intExpr to the lhs floating point type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000861 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000862 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +0000863 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +0000864 }
865
866 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +0000867 assert(IntTy->isComplexIntegerType());
868 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +0000869
870 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000871 if (ConvertInt)
872 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000873 CK_IntegralComplexToFloatingComplex);
874
875 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +0000876 if (ConvertFloat)
877 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu8289f492011-09-02 20:58:51 +0000878 CK_FloatingRealToComplex);
879
880 return result;
881}
882
883/// \brief Handle arithmethic conversion with floating point types. Helper
884/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000885static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
886 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000887 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000888 bool LHSFloat = LHSType->isRealFloatingType();
889 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +0000890
891 // If we have two real floating types, convert the smaller operand
892 // to the bigger result.
893 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000894 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +0000895 if (order > 0) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000896 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
897 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000898 }
899
900 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +0000901 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000902 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
903 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000904 }
905
906 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000907 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000908 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +0000909 /*convertInt=*/ true);
910 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000911 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000912 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +0000913 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +0000914}
915
916/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000917/// of UsualArithmeticConversions()
Richard Trieu8289f492011-09-02 20:58:51 +0000918// FIXME: if the operands are (int, _Complex long), we currently
919// don't promote the complex. Also, signedness?
Benjamin Kramer5cc86802011-09-06 19:57:14 +0000920static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
921 ExprResult &RHS, QualType LHSType,
922 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000923 bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000924 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
925 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu8289f492011-09-02 20:58:51 +0000926
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000927 if (LHSComplexInt && RHSComplexInt) {
928 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
929 RHSComplexInt->getElementType());
Richard Trieu8289f492011-09-02 20:58:51 +0000930 assert(order && "inequal types with equal element ordering");
931 if (order > 0) {
932 // _Complex int -> _Complex long
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000933 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
934 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000935 }
936
Richard Trieuccd891a2011-09-09 01:45:06 +0000937 if (!IsCompAssign)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000938 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
939 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000940 }
941
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000942 if (LHSComplexInt) {
Richard Trieu8289f492011-09-02 20:58:51 +0000943 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000944 // FIXME: This needs to take integer ranks into account
945 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
946 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000947 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
948 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000949 }
950
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000951 assert(RHSComplexInt);
Richard Trieu8289f492011-09-02 20:58:51 +0000952 // int -> _Complex int
Eli Friedmanddadaa42011-11-12 03:56:23 +0000953 // FIXME: This needs to take integer ranks into account
954 if (!IsCompAssign) {
955 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
956 CK_IntegralCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000957 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedmanddadaa42011-11-12 03:56:23 +0000958 }
Richard Trieu8ef5c8e2011-09-06 18:38:41 +0000959 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000960}
961
962/// \brief Handle integer arithmetic conversions. Helper function of
963/// UsualArithmeticConversions()
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000964static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
965 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000966 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000967 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000968 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
969 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
970 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
971 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +0000972 // Same signedness; use the higher-ranked type
973 if (order >= 0) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000974 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
975 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000976 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000977 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
978 return RHSType;
979 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000980 // The unsigned type has greater than or equal rank to the
981 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000982 if (RHSSigned) {
983 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
984 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000985 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000986 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
987 return RHSType;
988 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +0000989 // The two types are different widths; if we are here, that
990 // means the signed type is larger than the unsigned type, so
991 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000992 if (LHSSigned) {
993 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
994 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +0000995 } else if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +0000996 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
997 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +0000998 } else {
999 // The signed type is higher-ranked than the unsigned type,
1000 // but isn't actually any bigger (like unsigned int and long
1001 // on most 32-bit systems). Use the unsigned type corresponding
1002 // to the signed type.
1003 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001004 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1005 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuccd891a2011-09-09 01:45:06 +00001006 if (!IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001007 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu8289f492011-09-02 20:58:51 +00001008 return result;
1009 }
1010}
1011
Chris Lattnere7a2e912008-07-25 21:10:04 +00001012/// UsualArithmeticConversions - Performs various conversions that are common to
1013/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001014/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001015/// responsible for emitting appropriate error diagnostics.
1016/// FIXME: verify the conversion rules for "complex int" are consistent with
1017/// GCC.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001018QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001019 bool IsCompAssign) {
1020 if (!IsCompAssign) {
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001021 LHS = UsualUnaryConversions(LHS.take());
1022 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001023 return QualType();
1024 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001025
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001026 RHS = UsualUnaryConversions(RHS.take());
1027 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001028 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001029
Mike Stump1eb44332009-09-09 15:08:12 +00001030 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001031 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001032 QualType LHSType =
1033 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1034 QualType RHSType =
1035 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001036
Eli Friedman860a3192012-06-16 02:19:17 +00001037 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1038 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1039 LHSType = AtomicLHS->getValueType();
1040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001041 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001042 if (LHSType == RHSType)
1043 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001044
1045 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1046 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001047 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001048 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001049
John McCallcf33b242010-11-13 08:17:45 +00001050 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001051 QualType LHSUnpromotedType = LHSType;
1052 if (LHSType->isPromotableIntegerType())
1053 LHSType = Context.getPromotedIntegerType(LHSType);
1054 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001055 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001056 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001057 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001058 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001059
John McCallcf33b242010-11-13 08:17:45 +00001060 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001061 if (LHSType == RHSType)
1062 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001063
1064 // At this point, we have two different arithmetic types.
1065
1066 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001067 if (LHSType->isComplexType() || RHSType->isComplexType())
1068 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001069 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001070
1071 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001072 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1073 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001074 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001075
1076 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001077 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001078 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001079 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001080
1081 // Finally, we have two differing integer types.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001082 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001083 IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001084}
1085
Chris Lattnere7a2e912008-07-25 21:10:04 +00001086//===----------------------------------------------------------------------===//
1087// Semantic Analysis for various Expression Types
1088//===----------------------------------------------------------------------===//
1089
1090
Peter Collingbournef111d932011-04-15 00:35:48 +00001091ExprResult
1092Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1093 SourceLocation DefaultLoc,
1094 SourceLocation RParenLoc,
1095 Expr *ControllingExpr,
Richard Trieuccd891a2011-09-09 01:45:06 +00001096 MultiTypeArg ArgTypes,
1097 MultiExprArg ArgExprs) {
1098 unsigned NumAssocs = ArgTypes.size();
1099 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001100
Benjamin Kramer5354e772012-08-23 23:38:35 +00001101 ParsedType *ParsedTypes = ArgTypes.data();
1102 Expr **Exprs = ArgExprs.data();
Peter Collingbournef111d932011-04-15 00:35:48 +00001103
1104 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1105 for (unsigned i = 0; i < NumAssocs; ++i) {
1106 if (ParsedTypes[i])
1107 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1108 else
1109 Types[i] = 0;
1110 }
1111
1112 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1113 ControllingExpr, Types, Exprs,
1114 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001115 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001116 return ER;
1117}
1118
1119ExprResult
1120Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1121 SourceLocation DefaultLoc,
1122 SourceLocation RParenLoc,
1123 Expr *ControllingExpr,
1124 TypeSourceInfo **Types,
1125 Expr **Exprs,
1126 unsigned NumAssocs) {
1127 bool TypeErrorFound = false,
1128 IsResultDependent = ControllingExpr->isTypeDependent(),
1129 ContainsUnexpandedParameterPack
1130 = ControllingExpr->containsUnexpandedParameterPack();
1131
1132 for (unsigned i = 0; i < NumAssocs; ++i) {
1133 if (Exprs[i]->containsUnexpandedParameterPack())
1134 ContainsUnexpandedParameterPack = true;
1135
1136 if (Types[i]) {
1137 if (Types[i]->getType()->containsUnexpandedParameterPack())
1138 ContainsUnexpandedParameterPack = true;
1139
1140 if (Types[i]->getType()->isDependentType()) {
1141 IsResultDependent = true;
1142 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001143 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001144 // complete object type other than a variably modified type."
1145 unsigned D = 0;
1146 if (Types[i]->getType()->isIncompleteType())
1147 D = diag::err_assoc_type_incomplete;
1148 else if (!Types[i]->getType()->isObjectType())
1149 D = diag::err_assoc_type_nonobject;
1150 else if (Types[i]->getType()->isVariablyModifiedType())
1151 D = diag::err_assoc_type_variably_modified;
1152
1153 if (D != 0) {
1154 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1155 << Types[i]->getTypeLoc().getSourceRange()
1156 << Types[i]->getType();
1157 TypeErrorFound = true;
1158 }
1159
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001160 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001161 // selection shall specify compatible types."
1162 for (unsigned j = i+1; j < NumAssocs; ++j)
1163 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1164 Context.typesAreCompatible(Types[i]->getType(),
1165 Types[j]->getType())) {
1166 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1167 diag::err_assoc_compatible_types)
1168 << Types[j]->getTypeLoc().getSourceRange()
1169 << Types[j]->getType()
1170 << Types[i]->getType();
1171 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1172 diag::note_compat_assoc)
1173 << Types[i]->getTypeLoc().getSourceRange()
1174 << Types[i]->getType();
1175 TypeErrorFound = true;
1176 }
1177 }
1178 }
1179 }
1180 if (TypeErrorFound)
1181 return ExprError();
1182
1183 // If we determined that the generic selection is result-dependent, don't
1184 // try to compute the result expression.
1185 if (IsResultDependent)
1186 return Owned(new (Context) GenericSelectionExpr(
1187 Context, KeyLoc, ControllingExpr,
1188 Types, Exprs, NumAssocs, DefaultLoc,
1189 RParenLoc, ContainsUnexpandedParameterPack));
1190
Chris Lattner5f9e2722011-07-23 10:55:15 +00001191 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001192 unsigned DefaultIndex = -1U;
1193 for (unsigned i = 0; i < NumAssocs; ++i) {
1194 if (!Types[i])
1195 DefaultIndex = i;
1196 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1197 Types[i]->getType()))
1198 CompatIndices.push_back(i);
1199 }
1200
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001201 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001202 // type compatible with at most one of the types named in its generic
1203 // association list."
1204 if (CompatIndices.size() > 1) {
1205 // We strip parens here because the controlling expression is typically
1206 // parenthesized in macro definitions.
1207 ControllingExpr = ControllingExpr->IgnoreParens();
1208 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1209 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1210 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001211 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001212 E = CompatIndices.end(); I != E; ++I) {
1213 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1214 diag::note_compat_assoc)
1215 << Types[*I]->getTypeLoc().getSourceRange()
1216 << Types[*I]->getType();
1217 }
1218 return ExprError();
1219 }
1220
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001221 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001222 // its controlling expression shall have type compatible with exactly one of
1223 // the types named in its generic association list."
1224 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1225 // We strip parens here because the controlling expression is typically
1226 // parenthesized in macro definitions.
1227 ControllingExpr = ControllingExpr->IgnoreParens();
1228 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1229 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1230 return ExprError();
1231 }
1232
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001233 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001234 // type name that is compatible with the type of the controlling expression,
1235 // then the result expression of the generic selection is the expression
1236 // in that generic association. Otherwise, the result expression of the
1237 // generic selection is the expression in the default generic association."
1238 unsigned ResultIndex =
1239 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1240
1241 return Owned(new (Context) GenericSelectionExpr(
1242 Context, KeyLoc, ControllingExpr,
1243 Types, Exprs, NumAssocs, DefaultLoc,
1244 RParenLoc, ContainsUnexpandedParameterPack,
1245 ResultIndex));
1246}
1247
Richard Smithdd66be72012-03-08 01:34:56 +00001248/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1249/// location of the token and the offset of the ud-suffix within it.
1250static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1251 unsigned Offset) {
1252 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001253 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001254}
1255
Richard Smith36f5cfe2012-03-09 08:00:36 +00001256/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1257/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1258static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1259 IdentifierInfo *UDSuffix,
1260 SourceLocation UDSuffixLoc,
1261 ArrayRef<Expr*> Args,
1262 SourceLocation LitEndLoc) {
1263 assert(Args.size() <= 2 && "too many arguments for literal operator");
1264
1265 QualType ArgTy[2];
1266 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1267 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1268 if (ArgTy[ArgIdx]->isArrayType())
1269 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1270 }
1271
1272 DeclarationName OpName =
1273 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1274 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1275 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1276
1277 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1278 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1279 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1280 return ExprError();
1281
1282 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1283}
1284
Steve Narofff69936d2007-09-16 03:34:24 +00001285/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1287/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1288/// multiple tokens. However, the common case is that StringToks points to one
1289/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001290///
John McCall60d7b3a2010-08-24 06:29:42 +00001291ExprResult
Richard Smith36f5cfe2012-03-09 08:00:36 +00001292Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1293 Scope *UDLScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 assert(NumStringToks && "Must have at least one string!");
1295
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001296 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001298 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
Chris Lattner5f9e2722011-07-23 10:55:15 +00001300 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 for (unsigned i = 0; i != NumStringToks; ++i)
1302 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001303
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001304 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001305 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001306 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001307 else if (Literal.isUTF16())
1308 StrTy = Context.Char16Ty;
1309 else if (Literal.isUTF32())
1310 StrTy = Context.Char32Ty;
Eli Friedman64f45a22011-11-01 02:23:42 +00001311 else if (Literal.isPascal())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001312 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001313
Douglas Gregor5cee1192011-07-27 05:40:30 +00001314 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1315 if (Literal.isWide())
1316 Kind = StringLiteral::Wide;
1317 else if (Literal.isUTF8())
1318 Kind = StringLiteral::UTF8;
1319 else if (Literal.isUTF16())
1320 Kind = StringLiteral::UTF16;
1321 else if (Literal.isUTF32())
1322 Kind = StringLiteral::UTF32;
1323
Douglas Gregor77a52232008-09-12 00:47:35 +00001324 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001325 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001326 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001327
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001328 // Get an array type for the string, according to C99 6.4.5. This includes
1329 // the nul terminator character as well as the string length for pascal
1330 // strings.
1331 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001332 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001333 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001336 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1337 Kind, Literal.Pascal, StrTy,
1338 &StringTokLocs[0],
1339 StringTokLocs.size());
1340 if (Literal.getUDSuffix().empty())
1341 return Owned(Lit);
1342
1343 // We're building a user-defined literal.
1344 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001345 SourceLocation UDSuffixLoc =
1346 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1347 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001348
Richard Smith36f5cfe2012-03-09 08:00:36 +00001349 // Make sure we're allowed user-defined literals here.
1350 if (!UDLScope)
1351 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1352
Richard Smith9fcce652012-03-07 08:35:16 +00001353 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1354 // operator "" X (str, len)
1355 QualType SizeType = Context.getSizeType();
1356 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1357 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1358 StringTokLocs[0]);
1359 Expr *Args[] = { Lit, LenArg };
Richard Smith36f5cfe2012-03-09 08:00:36 +00001360 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1361 Args, StringTokLocs.back());
Reid Spencer5f016e22007-07-11 17:01:13 +00001362}
1363
John McCall60d7b3a2010-08-24 06:29:42 +00001364ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001365Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001366 SourceLocation Loc,
1367 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001368 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001369 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001370}
1371
John McCall76a40212011-02-09 01:13:10 +00001372/// BuildDeclRefExpr - Build an expression that references a
1373/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001374ExprResult
John McCall76a40212011-02-09 01:13:10 +00001375Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001376 const DeclarationNameInfo &NameInfo,
1377 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001378 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001379 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1380 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1381 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1382 CalleeTarget = IdentifyCUDATarget(Callee);
1383 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1384 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1385 << CalleeTarget << D->getIdentifier() << CallerTarget;
1386 Diag(D->getLocation(), diag::note_previous_decl)
1387 << D->getIdentifier();
1388 return ExprError();
1389 }
1390 }
1391
John McCallf4b88a42012-03-10 09:33:50 +00001392 bool refersToEnclosingScope =
1393 (CurContext != D->getDeclContext() &&
1394 D->getDeclContext()->isFunctionOrMethod());
1395
Eli Friedman5f2987c2012-02-02 03:46:19 +00001396 DeclRefExpr *E = DeclRefExpr::Create(Context,
1397 SS ? SS->getWithLocInContext(Context)
1398 : NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00001399 SourceLocation(),
1400 D, refersToEnclosingScope,
1401 NameInfo, Ty, VK);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Eli Friedman5f2987c2012-02-02 03:46:19 +00001403 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001404
1405 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001406 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1407 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001408 E->setObjectKind(OK_BitField);
1409
1410 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001411}
1412
Abramo Bagnara25777432010-08-11 22:01:17 +00001413/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001414/// possibly a list of template arguments.
1415///
1416/// If this produces template arguments, it is permitted to call
1417/// DecomposeTemplateName.
1418///
1419/// This actually loses a lot of source location information for
1420/// non-standard name kinds; we should consider preserving that in
1421/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001422void
1423Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1424 TemplateArgumentListInfo &Buffer,
1425 DeclarationNameInfo &NameInfo,
1426 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001427 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1428 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1429 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1430
Benjamin Kramer5354e772012-08-23 23:38:35 +00001431 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001432 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001433 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001434
John McCall2b5289b2010-08-23 07:28:44 +00001435 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001436 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001437 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001438 TemplateArgs = &Buffer;
1439 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001440 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001441 TemplateArgs = 0;
1442 }
1443}
1444
John McCall578b69b2009-12-16 08:11:27 +00001445/// Diagnose an empty lookup.
1446///
1447/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001448bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001449 CorrectionCandidateCallback &CCC,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001450 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001451 llvm::ArrayRef<Expr *> Args) {
John McCall578b69b2009-12-16 08:11:27 +00001452 DeclarationName Name = R.getLookupName();
1453
John McCall578b69b2009-12-16 08:11:27 +00001454 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001455 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001456 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1457 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001458 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001459 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001460 diagnostic_suggest = diag::err_undeclared_use_suggest;
1461 }
John McCall578b69b2009-12-16 08:11:27 +00001462
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001463 // If the original lookup was an unqualified lookup, fake an
1464 // unqualified lookup. This is useful when (for example) the
1465 // original lookup would not have found something because it was a
1466 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001467 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1468 ? CurContext : 0;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001469 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001470 if (isa<CXXRecordDecl>(DC)) {
1471 LookupQualifiedName(R, DC);
1472
1473 if (!R.empty()) {
1474 // Don't give errors about ambiguities in this lookup.
1475 R.suppressDiagnostics();
1476
Francois Pichete6226ae2011-11-17 03:44:24 +00001477 // During a default argument instantiation the CurContext points
1478 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1479 // function parameter list, hence add an explicit check.
1480 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1481 ActiveTemplateInstantiations.back().Kind ==
1482 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001483 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1484 bool isInstance = CurMethod &&
1485 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001486 DC == CurMethod->getParent() && !isDefaultArgument;
1487
John McCall578b69b2009-12-16 08:11:27 +00001488
1489 // Give a code modification hint to insert 'this->'.
1490 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1491 // Actually quite difficult!
Nico Weber4b554f42012-06-20 20:21:42 +00001492 if (getLangOpts().MicrosoftMode)
1493 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001494 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001495 Diag(R.getNameLoc(), diagnostic) << Name
1496 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001497 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1498 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001499
1500
1501 CXXMethodDecl *DepMethod;
1502 if (CurMethod->getTemplatedKind() ==
1503 FunctionDecl::TK_FunctionTemplateSpecialization)
1504 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1505 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1506 else
1507 DepMethod = cast<CXXMethodDecl>(
1508 CurMethod->getInstantiatedFromMemberFunction());
1509 assert(DepMethod && "No template pattern found");
1510
1511 QualType DepThisType = DepMethod->getThisType(Context);
1512 CheckCXXThisCapture(R.getNameLoc());
1513 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1514 R.getNameLoc(), DepThisType, false);
1515 TemplateArgumentListInfo TList;
1516 if (ULE->hasExplicitTemplateArgs())
1517 ULE->copyTemplateArgumentsInto(TList);
1518
1519 CXXScopeSpec SS;
1520 SS.Adopt(ULE->getQualifierLoc());
1521 CXXDependentScopeMemberExpr *DepExpr =
1522 CXXDependentScopeMemberExpr::Create(
1523 Context, DepThis, DepThisType, true, SourceLocation(),
1524 SS.getWithLocInContext(Context),
1525 ULE->getTemplateKeywordLoc(), 0,
1526 R.getLookupNameInfo(),
1527 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1528 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001529 } else {
John McCall578b69b2009-12-16 08:11:27 +00001530 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001531 }
John McCall578b69b2009-12-16 08:11:27 +00001532
1533 // Do we really want to note all of these?
1534 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1535 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1536
Francois Pichete6226ae2011-11-17 03:44:24 +00001537 // Return true if we are inside a default argument instantiation
1538 // and the found name refers to an instance member function, otherwise
1539 // the function calling DiagnoseEmptyLookup will try to create an
1540 // implicit member call and this is wrong for default argument.
1541 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1542 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1543 return true;
1544 }
1545
John McCall578b69b2009-12-16 08:11:27 +00001546 // Tell the callee to try to recover.
1547 return false;
1548 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001549
1550 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001551 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001552
1553 // In Microsoft mode, if we are performing lookup from within a friend
1554 // function definition declared at class scope then we must set
1555 // DC to the lexical parent to be able to search into the parent
1556 // class.
David Blaikie4e4d0842012-03-11 07:00:24 +00001557 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001558 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1559 DC->getLexicalParent()->isRecord())
1560 DC = DC->getLexicalParent();
1561 else
1562 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001563 }
1564
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001565 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001566 TypoCorrection Corrected;
1567 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001568 S, &SS, CCC))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001569 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1570 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001571 R.setLookupName(Corrected.getCorrection());
1572
Hans Wennborg701d1e72011-07-12 08:45:31 +00001573 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001574 if (Corrected.isOverloaded()) {
1575 OverloadCandidateSet OCS(R.getNameLoc());
1576 OverloadCandidateSet::iterator Best;
1577 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1578 CDEnd = Corrected.end();
1579 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001580 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001581 dyn_cast<FunctionTemplateDecl>(*CD))
1582 AddTemplateOverloadCandidate(
1583 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001584 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001585 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1586 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1587 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001588 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001589 }
1590 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1591 case OR_Success:
1592 ND = Best->Function;
1593 break;
1594 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001595 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001596 }
1597 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001598 R.addDecl(ND);
1599 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001600 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001601 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1602 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001603 else
1604 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001605 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001606 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001607 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1608 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001609 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001610 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001611
1612 // Tell the callee to try to recover.
1613 return false;
1614 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001615
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001616 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001617 // FIXME: If we ended up with a typo for a type name or
1618 // Objective-C class name, we're in trouble because the parser
1619 // is in the wrong place to recover. Suggest the typo
1620 // correction, but don't make it a fix-it since we're not going
1621 // to recover well anyway.
1622 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001623 Diag(R.getNameLoc(), diagnostic_suggest)
1624 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001625 else
1626 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001627 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001628 << SS.getRange();
1629
1630 // Don't try to recover; it won't work.
1631 return true;
1632 }
1633 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001634 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001635 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001636 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001638 else
Douglas Gregord203a162010-01-01 00:15:04 +00001639 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001640 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001641 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001642 return true;
1643 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001644 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001645 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001646
1647 // Emit a special diagnostic for failed member lookups.
1648 // FIXME: computing the declaration context might fail here (?)
1649 if (!SS.isEmpty()) {
1650 Diag(R.getNameLoc(), diag::err_no_member)
1651 << Name << computeDeclContext(SS, false)
1652 << SS.getRange();
1653 return true;
1654 }
1655
John McCall578b69b2009-12-16 08:11:27 +00001656 // Give up, we can't recover.
1657 Diag(R.getNameLoc(), diagnostic) << Name;
1658 return true;
1659}
1660
John McCall60d7b3a2010-08-24 06:29:42 +00001661ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001662 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001663 SourceLocation TemplateKWLoc,
John McCallfb97e752010-08-24 22:52:39 +00001664 UnqualifiedId &Id,
1665 bool HasTrailingLParen,
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001666 bool IsAddressOfOperand,
1667 CorrectionCandidateCallback *CCC) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001668 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00001669 "cannot be direct & operand and have a trailing lparen");
1670
1671 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001672 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001673
John McCall129e2df2009-11-30 22:42:35 +00001674 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001675
1676 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001677 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001678 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001679 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001680
Abramo Bagnara25777432010-08-11 22:01:17 +00001681 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001682 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001683 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001684
John McCallf7a1a742009-11-24 19:00:30 +00001685 // C++ [temp.dep.expr]p3:
1686 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001687 // -- an identifier that was declared with a dependent type,
1688 // (note: handled after lookup)
1689 // -- a template-id that is dependent,
1690 // (note: handled in BuildTemplateIdExpr)
1691 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001692 // -- a nested-name-specifier that contains a class-name that
1693 // names a dependent type.
1694 // Determine whether this is a member of an unknown specialization;
1695 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001696 bool DependentID = false;
1697 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1698 Name.getCXXNameType()->isDependentType()) {
1699 DependentID = true;
1700 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001701 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001702 if (RequireCompleteDeclContext(SS, DC))
1703 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001704 } else {
1705 DependentID = true;
1706 }
1707 }
1708
Chris Lattner337e5502011-02-18 01:27:55 +00001709 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001710 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1711 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001712
John McCallf7a1a742009-11-24 19:00:30 +00001713 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001714 LookupResult R(*this, NameInfo,
1715 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1716 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001717 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001718 // Lookup the template name again to correctly establish the context in
1719 // which it was found. This is really unfortunate as we already did the
1720 // lookup to determine that it was a template name in the first place. If
1721 // this becomes a performance hit, we can work harder to preserve those
1722 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001723 bool MemberOfUnknownSpecialization;
1724 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1725 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001726
1727 if (MemberOfUnknownSpecialization ||
1728 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001729 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1730 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001731 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00001732 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001733 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001735 // If the result might be in a dependent base class, this is a dependent
1736 // id-expression.
1737 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1739 IsAddressOfOperand, TemplateArgs);
1740
John McCallf7a1a742009-11-24 19:00:30 +00001741 // If this reference is in an Objective-C method, then we need to do
1742 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001743 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001744 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001745 if (E.isInvalid())
1746 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Chris Lattner337e5502011-02-18 01:27:55 +00001748 if (Expr *Ex = E.takeAs<Expr>())
1749 return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001750 }
Chris Lattner8a934232008-03-31 00:36:02 +00001751 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001752
John McCallf7a1a742009-11-24 19:00:30 +00001753 if (R.isAmbiguous())
1754 return ExprError();
1755
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001756 // Determine whether this name might be a candidate for
1757 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001758 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001759
John McCallf7a1a742009-11-24 19:00:30 +00001760 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001762 // in C90, extension in C99, forbidden in C++).
David Blaikie4e4d0842012-03-11 07:00:24 +00001763 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCallf7a1a742009-11-24 19:00:30 +00001764 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1765 if (D) R.addDecl(D);
1766 }
1767
1768 // If this name wasn't predeclared and if this is not a function
1769 // call, diagnose the problem.
1770 if (R.empty()) {
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001771
1772 // In Microsoft mode, if we are inside a template class member function
1773 // and we can't resolve an identifier then assume the identifier is type
1774 // dependent. The goal is to postpone name lookup to instantiation time
1775 // to be able to search into type dependent base classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00001776 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001777 isa<CXXMethodDecl>(CurContext))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001778 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1779 IsAddressOfOperand, TemplateArgs);
Francois Pichetfce1a3a2011-09-24 10:38:05 +00001780
Kaelyn Uhrain4798f8d2012-01-18 05:58:54 +00001781 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00001782 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCall578b69b2009-12-16 08:11:27 +00001783 return ExprError();
1784
1785 assert(!R.empty() &&
1786 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001787
1788 // If we found an Objective-C instance variable, let
1789 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001790 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001791 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1792 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001793 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanianbc2b91a2011-09-23 23:11:38 +00001794 // In a hopelessly buggy code, Objective-C instance variable
1795 // lookup fails and no expression will be built to reference it.
1796 if (!E.isInvalid() && !E.get())
1797 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001798 return E;
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001799 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 }
1801 }
Mike Stump1eb44332009-09-09 15:08:12 +00001802
John McCallf7a1a742009-11-24 19:00:30 +00001803 // This is guaranteed from this point on.
1804 assert(!R.empty() || ADL);
1805
John McCallaa81e162009-12-01 22:10:20 +00001806 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001807 // C++ [class.mfct.non-static]p3:
1808 // When an id-expression that is not part of a class member access
1809 // syntax and not used to form a pointer to member is used in the
1810 // body of a non-static member function of class X, if name lookup
1811 // resolves the name in the id-expression to a non-static non-type
1812 // member of some class C, the id-expression is transformed into a
1813 // class member access expression using (*this) as the
1814 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001815 //
1816 // But we don't actually need to do this for '&' operands if R
1817 // resolved to a function or overloaded function set, because the
1818 // expression is ill-formed if it actually works out to be a
1819 // non-static member function:
1820 //
1821 // C++ [expr.ref]p4:
1822 // Otherwise, if E1.E2 refers to a non-static member function. . .
1823 // [t]he expression can be used only as the left-hand operand of a
1824 // member function call.
1825 //
1826 // There are other safeguards against such uses, but it's important
1827 // to get this right here so that we don't end up making a
1828 // spuriously dependent expression if we're inside a dependent
1829 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001830 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001831 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00001832 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00001833 MightBeImplicitMember = true;
1834 else if (!SS.isEmpty())
1835 MightBeImplicitMember = false;
1836 else if (R.isOverloadedResult())
1837 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001838 else if (R.isUnresolvableResult())
1839 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001840 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001841 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1842 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001843
1844 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001845 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1846 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001847 }
1848
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001849 if (TemplateArgs || TemplateKWLoc.isValid())
1850 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001851
John McCallf7a1a742009-11-24 19:00:30 +00001852 return BuildDeclarationNameExpr(SS, R, ADL);
1853}
1854
John McCall129e2df2009-11-30 22:42:35 +00001855/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1856/// declaration name, generally during template instantiation.
1857/// There's a large number of things which don't need to be done along
1858/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001859ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001860Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001861 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001862 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001863 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00001864 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1865 NameInfo, /*TemplateArgs=*/0);
John McCallf7a1a742009-11-24 19:00:30 +00001866
John McCall77bb1aa2010-05-01 00:40:08 +00001867 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001868 return ExprError();
1869
Abramo Bagnara25777432010-08-11 22:01:17 +00001870 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001871 LookupQualifiedName(R, DC);
1872
1873 if (R.isAmbiguous())
1874 return ExprError();
1875
1876 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001877 Diag(NameInfo.getLoc(), diag::err_no_member)
1878 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001879 return ExprError();
1880 }
1881
1882 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1883}
1884
1885/// LookupInObjCMethod - The parser has read a name in, and Sema has
1886/// detected that we're currently inside an ObjC method. Perform some
1887/// additional lookup.
1888///
1889/// Ideally, most of this would be done by lookup, but there's
1890/// actually quite a lot of extra work involved.
1891///
1892/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001893ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001894Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001895 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001896 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001897 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001898
John McCallf7a1a742009-11-24 19:00:30 +00001899 // There are two cases to handle here. 1) scoped lookup could have failed,
1900 // in which case we should look for an ivar. 2) scoped lookup could have
1901 // found a decl, but that decl is outside the current instance method (i.e.
1902 // a global variable). In these two cases, we do a lookup for an ivar with
1903 // this name, if the lookup sucedes, we replace it our current decl.
1904
1905 // If we're in a class method, we don't normally want to look for
1906 // ivars. But if we don't find anything else, and there's an
1907 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001908 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001909
1910 bool LookForIvars;
1911 if (Lookup.empty())
1912 LookForIvars = true;
1913 else if (IsClassMethod)
1914 LookForIvars = false;
1915 else
1916 LookForIvars = (Lookup.isSingleResult() &&
1917 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001918 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001919 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001920 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001921 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00001922 ObjCIvarDecl *IV = 0;
1923 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00001924 // Diagnose using an ivar in a class method.
1925 if (IsClassMethod)
1926 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1927 << IV->getDeclName());
1928
1929 // If we're referencing an invalid decl, just return this as a silent
1930 // error node. The error diagnostic was already emitted on the decl.
1931 if (IV->isInvalidDecl())
1932 return ExprError();
1933
1934 // Check if referencing a field with __attribute__((deprecated)).
1935 if (DiagnoseUseOfDecl(IV, Loc))
1936 return ExprError();
1937
1938 // Diagnose the use of an ivar outside of the declaring class.
1939 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001940 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001941 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00001942 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1943
1944 // FIXME: This should use a new expr for a direct reference, don't
1945 // turn this into Self->ivar, just return a BareIVarExpr or something.
1946 IdentifierInfo &II = Context.Idents.get("self");
1947 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001948 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001949 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001950 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001951 SourceLocation TemplateKWLoc;
1952 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001953 SelfName, false, false);
1954 if (SelfExpr.isInvalid())
1955 return ExprError();
1956
John Wiegley429bb272011-04-08 18:41:53 +00001957 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1958 if (SelfExpr.isInvalid())
1959 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001960
Eli Friedman5f2987c2012-02-02 03:46:19 +00001961 MarkAnyDeclReferenced(Loc, IV);
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001962
1963 ObjCMethodFamily MF = CurMethod->getMethodFamily();
1964 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1965 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
John McCallf7a1a742009-11-24 19:00:30 +00001966 return Owned(new (Context)
1967 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001968 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001969 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001970 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001971 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001972 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1973 ObjCInterfaceDecl *ClassDeclared;
1974 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1975 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00001976 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00001977 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1978 }
John McCallf7a1a742009-11-24 19:00:30 +00001979 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00001980 } else if (Lookup.isSingleResult() &&
1981 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1982 // If accessing a stand-alone ivar in a class method, this is an error.
1983 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1984 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1985 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00001986 }
1987
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001988 if (Lookup.empty() && II && AllowBuiltinCreation) {
1989 // FIXME. Consolidate this with similar code in LookupName.
1990 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001991 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001992 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1993 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1994 S, Lookup.isForRedeclaration(),
1995 Lookup.getNameLoc());
1996 if (D) Lookup.addDecl(D);
1997 }
1998 }
1999 }
John McCallf7a1a742009-11-24 19:00:30 +00002000 // Sentinel value saying that we didn't do anything special.
2001 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002002}
John McCallba135432009-11-21 08:51:07 +00002003
John McCall6bb80172010-03-30 21:47:33 +00002004/// \brief Cast a base object to a member's actual type.
2005///
2006/// Logically this happens in three phases:
2007///
2008/// * First we cast from the base type to the naming class.
2009/// The naming class is the class into which we were looking
2010/// when we found the member; it's the qualifier type if a
2011/// qualifier was provided, and otherwise it's the base type.
2012///
2013/// * Next we cast from the naming class to the declaring class.
2014/// If the member we found was brought into a class's scope by
2015/// a using declaration, this is that class; otherwise it's
2016/// the class declaring the member.
2017///
2018/// * Finally we cast from the declaring class to the "true"
2019/// declaring class of the member. This conversion does not
2020/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002021ExprResult
2022Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002023 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002024 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002025 NamedDecl *Member) {
2026 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2027 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002028 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002029
Douglas Gregor5fccd362010-03-03 23:55:11 +00002030 QualType DestRecordType;
2031 QualType DestType;
2032 QualType FromRecordType;
2033 QualType FromType = From->getType();
2034 bool PointerConversions = false;
2035 if (isa<FieldDecl>(Member)) {
2036 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002037
Douglas Gregor5fccd362010-03-03 23:55:11 +00002038 if (FromType->getAs<PointerType>()) {
2039 DestType = Context.getPointerType(DestRecordType);
2040 FromRecordType = FromType->getPointeeType();
2041 PointerConversions = true;
2042 } else {
2043 DestType = DestRecordType;
2044 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002045 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002046 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2047 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002048 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002049
Douglas Gregor5fccd362010-03-03 23:55:11 +00002050 DestType = Method->getThisType(Context);
2051 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002052
Douglas Gregor5fccd362010-03-03 23:55:11 +00002053 if (FromType->getAs<PointerType>()) {
2054 FromRecordType = FromType->getPointeeType();
2055 PointerConversions = true;
2056 } else {
2057 FromRecordType = FromType;
2058 DestType = DestRecordType;
2059 }
2060 } else {
2061 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002062 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002063 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002064
Douglas Gregor5fccd362010-03-03 23:55:11 +00002065 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002066 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002067
Douglas Gregor5fccd362010-03-03 23:55:11 +00002068 // If the unqualified types are the same, no conversion is necessary.
2069 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002070 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002071
John McCall6bb80172010-03-30 21:47:33 +00002072 SourceRange FromRange = From->getSourceRange();
2073 SourceLocation FromLoc = FromRange.getBegin();
2074
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002075 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002076
Douglas Gregor5fccd362010-03-03 23:55:11 +00002077 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002078 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002079 // class name.
2080 //
2081 // If the member was a qualified name and the qualified referred to a
2082 // specific base subobject type, we'll cast to that intermediate type
2083 // first and then to the object in which the member is declared. That allows
2084 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2085 //
2086 // class Base { public: int x; };
2087 // class Derived1 : public Base { };
2088 // class Derived2 : public Base { };
2089 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2090 //
2091 // void VeryDerived::f() {
2092 // x = 17; // error: ambiguous base subobjects
2093 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2094 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002095 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002096 QualType QType = QualType(Qualifier->getAsType(), 0);
2097 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2098 assert(QType->isRecordType() && "lookup done with non-record type");
2099
2100 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2101
2102 // In C++98, the qualifier type doesn't actually have to be a base
2103 // type of the object type, in which case we just ignore it.
2104 // Otherwise build the appropriate casts.
2105 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002106 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002107 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002108 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002109 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002110
Douglas Gregor5fccd362010-03-03 23:55:11 +00002111 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002112 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002113 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2114 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002115
2116 FromType = QType;
2117 FromRecordType = QRecordType;
2118
2119 // If the qualifier type was the same as the destination type,
2120 // we're done.
2121 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002122 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002123 }
2124 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002125
John McCall6bb80172010-03-30 21:47:33 +00002126 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002127
John McCall6bb80172010-03-30 21:47:33 +00002128 // If we actually found the member through a using declaration, cast
2129 // down to the using declaration's type.
2130 //
2131 // Pointer equality is fine here because only one declaration of a
2132 // class ever has member declarations.
2133 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2134 assert(isa<UsingShadowDecl>(FoundDecl));
2135 QualType URecordType = Context.getTypeDeclType(
2136 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2137
2138 // We only need to do this if the naming-class to declaring-class
2139 // conversion is non-trivial.
2140 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2141 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002142 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002143 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002144 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002145 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002146
John McCall6bb80172010-03-30 21:47:33 +00002147 QualType UType = URecordType;
2148 if (PointerConversions)
2149 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002150 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2151 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002152 FromType = UType;
2153 FromRecordType = URecordType;
2154 }
2155
2156 // We don't do access control for the conversion from the
2157 // declaring class to the true declaring class.
2158 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002159 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002160
John McCallf871d0c2010-08-07 06:22:56 +00002161 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002162 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2163 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002164 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002165 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002166
John Wiegley429bb272011-04-08 18:41:53 +00002167 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2168 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002169}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002170
John McCallf7a1a742009-11-24 19:00:30 +00002171bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002172 const LookupResult &R,
2173 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002174 // Only when used directly as the postfix-expression of a call.
2175 if (!HasTrailingLParen)
2176 return false;
2177
2178 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002179 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002180 return false;
2181
2182 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002183 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002184 return false;
2185
2186 // Turn off ADL when we find certain kinds of declarations during
2187 // normal lookup:
2188 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2189 NamedDecl *D = *I;
2190
2191 // C++0x [basic.lookup.argdep]p3:
2192 // -- a declaration of a class member
2193 // Since using decls preserve this property, we check this on the
2194 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002195 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002196 return false;
2197
2198 // C++0x [basic.lookup.argdep]p3:
2199 // -- a block-scope function declaration that is not a
2200 // using-declaration
2201 // NOTE: we also trigger this for function templates (in fact, we
2202 // don't check the decl type at all, since all other decl types
2203 // turn off ADL anyway).
2204 if (isa<UsingShadowDecl>(D))
2205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2206 else if (D->getDeclContext()->isFunctionOrMethod())
2207 return false;
2208
2209 // C++0x [basic.lookup.argdep]p3:
2210 // -- a declaration that is neither a function or a function
2211 // template
2212 // And also for builtin functions.
2213 if (isa<FunctionDecl>(D)) {
2214 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2215
2216 // But also builtin functions.
2217 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2218 return false;
2219 } else if (!isa<FunctionTemplateDecl>(D))
2220 return false;
2221 }
2222
2223 return true;
2224}
2225
2226
John McCallba135432009-11-21 08:51:07 +00002227/// Diagnoses obvious problems with the use of the given declaration
2228/// as an expression. This is only actually called for lookups that
2229/// were not overloaded, and it doesn't promise that the declaration
2230/// will in fact be used.
2231static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002232 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002233 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2234 return true;
2235 }
2236
2237 if (isa<ObjCInterfaceDecl>(D)) {
2238 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2239 return true;
2240 }
2241
2242 if (isa<NamespaceDecl>(D)) {
2243 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2244 return true;
2245 }
2246
2247 return false;
2248}
2249
John McCall60d7b3a2010-08-24 06:29:42 +00002250ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002251Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002252 LookupResult &R,
2253 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002254 // If this is a single, fully-resolved result and we don't need ADL,
2255 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002256 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002257 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2258 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002259
2260 // We only need to check the declaration if there's exactly one
2261 // result, because in the overloaded case the results can only be
2262 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002263 if (R.isSingleResult() &&
2264 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002265 return ExprError();
2266
John McCallc373d482010-01-27 01:50:18 +00002267 // Otherwise, just build an unresolved lookup expression. Suppress
2268 // any lookup-related diagnostics; we'll hash these out later, when
2269 // we've picked a target.
2270 R.suppressDiagnostics();
2271
John McCallba135432009-11-21 08:51:07 +00002272 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002273 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002274 SS.getWithLocInContext(Context),
2275 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002276 NeedsADL, R.isOverloadedResult(),
2277 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002278
2279 return Owned(ULE);
2280}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002281
John McCallba135432009-11-21 08:51:07 +00002282/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002283ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002284Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002285 const DeclarationNameInfo &NameInfo,
2286 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002287 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002288 assert(!isa<FunctionTemplateDecl>(D) &&
2289 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002290
Abramo Bagnara25777432010-08-11 22:01:17 +00002291 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002292 if (CheckDeclInExpr(*this, Loc, D))
2293 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002294
Douglas Gregor9af2f522009-12-01 16:58:18 +00002295 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2296 // Specifically diagnose references to class templates that are missing
2297 // a template argument list.
2298 Diag(Loc, diag::err_template_decl_ref)
2299 << Template << SS.getRange();
2300 Diag(Template->getLocation(), diag::note_template_decl_here);
2301 return ExprError();
2302 }
2303
2304 // Make sure that we're referring to a value.
2305 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2306 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002307 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002308 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002309 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002310 return ExprError();
2311 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002312
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002313 // Check whether this declaration can be used. Note that we suppress
2314 // this check when we're going to perform argument-dependent lookup
2315 // on this function name, because this might not be the function
2316 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002317 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002318 return ExprError();
2319
Steve Naroffdd972f22008-09-05 22:11:13 +00002320 // Only create DeclRefExpr's for valid Decl's.
2321 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002322 return ExprError();
2323
John McCall5808ce42011-02-03 08:15:49 +00002324 // Handle members of anonymous structs and unions. If we got here,
2325 // and the reference is to a class member indirect field, then this
2326 // must be the subject of a pointer-to-member expression.
2327 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2328 if (!indirectField->isCXXClassMember())
2329 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2330 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002331
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002332 {
John McCall76a40212011-02-09 01:13:10 +00002333 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002334 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002335
2336 switch (D->getKind()) {
2337 // Ignore all the non-ValueDecl kinds.
2338#define ABSTRACT_DECL(kind)
2339#define VALUE(type, base)
2340#define DECL(type, base) \
2341 case Decl::type:
2342#include "clang/AST/DeclNodes.inc"
2343 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002344
2345 // These shouldn't make it here.
2346 case Decl::ObjCAtDefsField:
2347 case Decl::ObjCIvar:
2348 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002349
2350 // Enum constants are always r-values and never references.
2351 // Unresolved using declarations are dependent.
2352 case Decl::EnumConstant:
2353 case Decl::UnresolvedUsingValue:
2354 valueKind = VK_RValue;
2355 break;
2356
2357 // Fields and indirect fields that got here must be for
2358 // pointer-to-member expressions; we just call them l-values for
2359 // internal consistency, because this subexpression doesn't really
2360 // exist in the high-level semantics.
2361 case Decl::Field:
2362 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002363 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002364 "building reference to field in C?");
2365
2366 // These can't have reference type in well-formed programs, but
2367 // for internal consistency we do this anyway.
2368 type = type.getNonReferenceType();
2369 valueKind = VK_LValue;
2370 break;
2371
2372 // Non-type template parameters are either l-values or r-values
2373 // depending on the type.
2374 case Decl::NonTypeTemplateParm: {
2375 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2376 type = reftype->getPointeeType();
2377 valueKind = VK_LValue; // even if the parameter is an r-value reference
2378 break;
2379 }
2380
2381 // For non-references, we need to strip qualifiers just in case
2382 // the template parameter was declared as 'const int' or whatever.
2383 valueKind = VK_RValue;
2384 type = type.getUnqualifiedType();
2385 break;
2386 }
2387
2388 case Decl::Var:
2389 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002390 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002391 !type.hasQualifiers() &&
2392 type->isVoidType()) {
2393 valueKind = VK_RValue;
2394 break;
2395 }
2396 // fallthrough
2397
2398 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002399 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002400 // These are always l-values.
2401 valueKind = VK_LValue;
2402 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002403
Douglas Gregor68932842012-02-18 05:51:20 +00002404 // FIXME: Does the addition of const really only apply in
2405 // potentially-evaluated contexts? Since the variable isn't actually
2406 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002407 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002408 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2409 if (!CapturedType.isNull())
2410 type = CapturedType;
2411 }
2412
John McCall76a40212011-02-09 01:13:10 +00002413 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002414 }
2415
John McCall76a40212011-02-09 01:13:10 +00002416 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002417 const FunctionType *fty = type->castAs<FunctionType>();
2418
2419 // If we're referring to a function with an __unknown_anytype
2420 // result type, make the entire expression __unknown_anytype.
2421 if (fty->getResultType() == Context.UnknownAnyTy) {
2422 type = Context.UnknownAnyTy;
2423 valueKind = VK_RValue;
2424 break;
2425 }
2426
John McCall76a40212011-02-09 01:13:10 +00002427 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002428 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002429 valueKind = VK_LValue;
2430 break;
2431 }
2432
2433 // C99 DR 316 says that, if a function type comes from a
2434 // function definition (without a prototype), that type is only
2435 // used for checking compatibility. Therefore, when referencing
2436 // the function, we pretend that we don't have the full function
2437 // type.
John McCall755d8492011-04-12 00:42:48 +00002438 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2439 isa<FunctionProtoType>(fty))
2440 type = Context.getFunctionNoProtoType(fty->getResultType(),
2441 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002442
2443 // Functions are r-values in C.
2444 valueKind = VK_RValue;
2445 break;
2446 }
2447
2448 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002449 // If we're referring to a method with an __unknown_anytype
2450 // result type, make the entire expression __unknown_anytype.
2451 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002452 if (const FunctionProtoType *proto
2453 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002454 if (proto->getResultType() == Context.UnknownAnyTy) {
2455 type = Context.UnknownAnyTy;
2456 valueKind = VK_RValue;
2457 break;
2458 }
2459
John McCall76a40212011-02-09 01:13:10 +00002460 // C++ methods are l-values if static, r-values if non-static.
2461 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2462 valueKind = VK_LValue;
2463 break;
2464 }
2465 // fallthrough
2466
2467 case Decl::CXXConversion:
2468 case Decl::CXXDestructor:
2469 case Decl::CXXConstructor:
2470 valueKind = VK_RValue;
2471 break;
2472 }
2473
2474 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002476}
2477
John McCall755d8492011-04-12 00:42:48 +00002478ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002479 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002480
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002482 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002483 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2484 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
Nico Weber28ad0632012-06-23 02:07:59 +00002485 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
Chris Lattnerd9f69102008-08-10 01:53:14 +00002486 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002488
Chris Lattnerfa28b302008-01-12 08:14:25 +00002489 // Pre-defined identifiers are of type char[x], where x is the length of the
2490 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Anders Carlsson3a082d82009-09-08 18:24:21 +00002492 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002493 if (!currentDecl && getCurBlock())
2494 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002495 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002496 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002497 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002498 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002499
Anders Carlsson773f3972009-09-11 01:22:35 +00002500 QualType ResTy;
2501 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2502 ResTy = Context.DependentTy;
2503 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002504 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002505
Anders Carlsson773f3972009-09-11 01:22:35 +00002506 llvm::APInt LengthI(32, Length + 1);
Nico Weberd68615f2012-06-29 16:39:58 +00002507 if (IT == PredefinedExpr::LFunction)
Nico Weber28ad0632012-06-23 02:07:59 +00002508 ResTy = Context.WCharTy.withConst();
2509 else
2510 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002511 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2512 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002513 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002514}
2515
Richard Smith36f5cfe2012-03-09 08:00:36 +00002516ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002517 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002518 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002519 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002520 if (Invalid)
2521 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002522
Benjamin Kramerddeea562010-02-27 13:44:12 +00002523 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002524 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002526 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002527
Chris Lattnere8337df2009-12-30 21:19:39 +00002528 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00002529 if (Literal.isWide())
2530 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002531 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002532 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002533 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002534 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00002535 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00002536 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002537 else
2538 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002539
Douglas Gregor5cee1192011-07-27 05:40:30 +00002540 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2541 if (Literal.isWide())
2542 Kind = CharacterLiteral::Wide;
2543 else if (Literal.isUTF16())
2544 Kind = CharacterLiteral::UTF16;
2545 else if (Literal.isUTF32())
2546 Kind = CharacterLiteral::UTF32;
2547
Richard Smithdd66be72012-03-08 01:34:56 +00002548 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2549 Tok.getLocation());
2550
2551 if (Literal.getUDSuffix().empty())
2552 return Owned(Lit);
2553
2554 // We're building a user-defined literal.
2555 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2556 SourceLocation UDSuffixLoc =
2557 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2558
Richard Smith36f5cfe2012-03-09 08:00:36 +00002559 // Make sure we're allowed user-defined literals here.
2560 if (!UDLScope)
2561 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2562
Richard Smithdd66be72012-03-08 01:34:56 +00002563 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2564 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002565 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2566 llvm::makeArrayRef(&Lit, 1),
2567 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002568}
2569
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002570ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2571 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2572 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2573 Context.IntTy, Loc));
2574}
2575
Richard Smithb453ad32012-03-08 08:45:32 +00002576static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2577 QualType Ty, SourceLocation Loc) {
2578 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2579
2580 using llvm::APFloat;
2581 APFloat Val(Format);
2582
2583 APFloat::opStatus result = Literal.GetFloatValue(Val);
2584
2585 // Overflow is always an error, but underflow is only an error if
2586 // we underflowed to zero (APFloat reports denormals as underflow).
2587 if ((result & APFloat::opOverflow) ||
2588 ((result & APFloat::opUnderflow) && Val.isZero())) {
2589 unsigned diagnostic;
2590 SmallString<20> buffer;
2591 if (result & APFloat::opOverflow) {
2592 diagnostic = diag::warn_float_overflow;
2593 APFloat::getLargest(Format).toString(buffer);
2594 } else {
2595 diagnostic = diag::warn_float_underflow;
2596 APFloat::getSmallest(Format).toString(buffer);
2597 }
2598
2599 S.Diag(Loc, diagnostic)
2600 << Ty
2601 << StringRef(buffer.data(), buffer.size());
2602 }
2603
2604 bool isExact = (result == APFloat::opOK);
2605 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2606}
2607
Richard Smith36f5cfe2012-03-09 08:00:36 +00002608ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002609 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00002610 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002612 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002613 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 }
Ted Kremenek28396602009-01-13 23:19:12 +00002615
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002616 SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002617 // Add padding so that NumericLiteralParser can overread by one character.
2618 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002619 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002620
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002622 bool Invalid = false;
2623 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2624 if (Invalid)
2625 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002626
Mike Stump1eb44332009-09-09 15:08:12 +00002627 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 Tok.getLocation(), PP);
2629 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002630 return ExprError();
2631
Richard Smithb453ad32012-03-08 08:45:32 +00002632 if (Literal.hasUDSuffix()) {
2633 // We're building a user-defined literal.
2634 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2635 SourceLocation UDSuffixLoc =
2636 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2637
Richard Smith36f5cfe2012-03-09 08:00:36 +00002638 // Make sure we're allowed user-defined literals here.
2639 if (!UDLScope)
2640 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00002641
Richard Smith36f5cfe2012-03-09 08:00:36 +00002642 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002643 if (Literal.isFloatingLiteral()) {
2644 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2645 // long double, the literal is treated as a call of the form
2646 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002647 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002648 } else {
2649 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2650 // unsigned long long, the literal is treated as a call of the form
2651 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00002652 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00002653 }
2654
Richard Smith36f5cfe2012-03-09 08:00:36 +00002655 DeclarationName OpName =
2656 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2657 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2658 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2659
2660 // Perform literal operator lookup to determine if we're building a raw
2661 // literal or a cooked one.
2662 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2663 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2664 /*AllowRawAndTemplate*/true)) {
2665 case LOLR_Error:
2666 return ExprError();
2667
2668 case LOLR_Cooked: {
2669 Expr *Lit;
2670 if (Literal.isFloatingLiteral()) {
2671 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2672 } else {
2673 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2674 if (Literal.GetIntegerValue(ResultVal))
2675 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2676 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2677 Tok.getLocation());
2678 }
2679 return BuildLiteralOperatorCall(R, OpNameInfo,
2680 llvm::makeArrayRef(&Lit, 1),
2681 Tok.getLocation());
2682 }
2683
2684 case LOLR_Raw: {
2685 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2686 // literal is treated as a call of the form
2687 // operator "" X ("n")
2688 SourceLocation TokLoc = Tok.getLocation();
2689 unsigned Length = Literal.getUDSuffixOffset();
2690 QualType StrTy = Context.getConstantArrayType(
2691 Context.CharTy, llvm::APInt(32, Length + 1),
2692 ArrayType::Normal, 0);
2693 Expr *Lit = StringLiteral::Create(
2694 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2695 /*Pascal*/false, StrTy, &TokLoc, 1);
2696 return BuildLiteralOperatorCall(R, OpNameInfo,
2697 llvm::makeArrayRef(&Lit, 1), TokLoc);
2698 }
2699
2700 case LOLR_Template:
2701 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2702 // template), L is treated as a call fo the form
2703 // operator "" X <'c1', 'c2', ... 'ck'>()
2704 // where n is the source character sequence c1 c2 ... ck.
2705 TemplateArgumentListInfo ExplicitArgs;
2706 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2707 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2708 llvm::APSInt Value(CharBits, CharIsUnsigned);
2709 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2710 Value = ThisTokBegin[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00002711 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00002712 TemplateArgumentLocInfo ArgInfo;
2713 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2714 }
2715 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2716 Tok.getLocation(), &ExplicitArgs);
2717 }
2718
2719 llvm_unreachable("unexpected literal operator lookup result");
Richard Smithb453ad32012-03-08 08:45:32 +00002720 }
2721
Chris Lattner5d661452007-08-26 03:42:43 +00002722 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002723
Chris Lattner5d661452007-08-26 03:42:43 +00002724 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002725 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002726 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002727 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002728 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002729 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002730 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002731 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002732
Richard Smithb453ad32012-03-08 08:45:32 +00002733 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002734
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002735 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002736 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002737 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikie4e4d0842012-03-11 07:00:24 +00002738 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002739 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002740 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002741 }
2742 }
Chris Lattner5d661452007-08-26 03:42:43 +00002743 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002744 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002745 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002746 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002747
Neil Boothb9449512007-08-29 22:00:19 +00002748 // long long is a C99 feature.
David Blaikie4e4d0842012-03-11 07:00:24 +00002749 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smithebaf0e62011-10-18 20:49:44 +00002750 Diag(Tok.getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002751 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00002752 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothb9449512007-08-29 22:00:19 +00002753
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00002755 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2756 // The microsoft literal suffix extensions support 128-bit literals, which
2757 // may be wider than [u]intmax_t.
2758 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2759 MaxWidth = 128;
2760 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002761
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 if (Literal.GetIntegerValue(ResultVal)) {
2763 // If this value didn't fit into uintmax_t, warn and force to ull.
2764 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002765 Ty = Context.UnsignedLongLongTy;
2766 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002767 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 } else {
2769 // If this value fits into a ULL, try to figure out what else it fits into
2770 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002771
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2773 // be an unsigned int.
2774 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2775
2776 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002777 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002778 if (!Literal.isLong && !Literal.isLongLong) {
2779 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002780 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002781
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 // Does it fit in a unsigned int?
2783 if (ResultVal.isIntN(IntSize)) {
2784 // Does it fit in a signed int?
2785 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002786 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002788 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002789 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002792
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002794 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002795 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002796
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 // Does it fit in a unsigned long?
2798 if (ResultVal.isIntN(LongSize)) {
2799 // Does it fit in a signed long?
2800 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002801 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002803 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002804 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002806 }
2807
Stephen Canonb9e05f12012-05-03 22:49:43 +00002808 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002809 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002810 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002811
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 // Does it fit in a unsigned long long?
2813 if (ResultVal.isIntN(LongLongSize)) {
2814 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002815 // To be compatible with MSVC, hex integer literals ending with the
2816 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002817 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002818 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002819 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002821 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002822 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002823 }
2824 }
Stephen Canonb9e05f12012-05-03 22:49:43 +00002825
2826 // If it doesn't fit in unsigned long long, and we're using Microsoft
2827 // extensions, then its a 128-bit integer literal.
2828 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2829 if (Literal.isUnsigned)
2830 Ty = Context.UnsignedInt128Ty;
2831 else
2832 Ty = Context.Int128Ty;
2833 Width = 128;
2834 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002835
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 // If we still couldn't decide a type, we probably have something that
2837 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002838 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002840 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002841 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002843
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002844 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002845 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002847 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002849
Chris Lattner5d661452007-08-26 03:42:43 +00002850 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2851 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002852 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002853 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002854
2855 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002856}
2857
Richard Trieuccd891a2011-09-09 01:45:06 +00002858ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002859 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002860 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002861}
2862
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002863static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2864 SourceLocation Loc,
2865 SourceRange ArgRange) {
2866 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2867 // scalar or vector data type argument..."
2868 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2869 // type (C99 6.2.5p18) or void.
2870 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2871 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2872 << T << ArgRange;
2873 return true;
2874 }
2875
2876 assert((T->isVoidType() || !T->isIncompleteType()) &&
2877 "Scalar types should always be complete");
2878 return false;
2879}
2880
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002881static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2882 SourceLocation Loc,
2883 SourceRange ArgRange,
2884 UnaryExprOrTypeTrait TraitKind) {
2885 // C99 6.5.3.4p1:
2886 if (T->isFunctionType()) {
2887 // alignof(function) is allowed as an extension.
2888 if (TraitKind == UETT_SizeOf)
2889 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2890 return false;
2891 }
2892
2893 // Allow sizeof(void)/alignof(void) as an extension.
2894 if (T->isVoidType()) {
2895 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2896 return false;
2897 }
2898
2899 return true;
2900}
2901
2902static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2903 SourceLocation Loc,
2904 SourceRange ArgRange,
2905 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00002906 // Reject sizeof(interface) and sizeof(interface<proto>) if the
2907 // runtime doesn't allow it.
2908 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002909 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2910 << T << (TraitKind == UETT_SizeOf)
2911 << ArgRange;
2912 return true;
2913 }
2914
2915 return false;
2916}
2917
Chandler Carruth9d342d02011-05-26 08:53:10 +00002918/// \brief Check the constrains on expression operands to unary type expression
2919/// and type traits.
2920///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002921/// Completes any types necessary and validates the constraints on the operand
2922/// expression. The logic mostly mirrors the type-based overload, but may modify
2923/// the expression as it completes the type for that expression through template
2924/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00002925bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002926 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002927 QualType ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002928
2929 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2930 // the result is the size of the referenced type."
2931 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2932 // result shall be the alignment of the referenced type."
2933 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2934 ExprTy = Ref->getPointeeType();
2935
2936 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00002937 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2938 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002939
2940 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00002941 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2942 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002943 return false;
2944
Richard Trieuccd891a2011-09-09 01:45:06 +00002945 if (RequireCompleteExprType(E,
Douglas Gregord10099e2012-05-04 16:32:21 +00002946 diag::err_sizeof_alignof_incomplete_type,
2947 ExprKind, E->getSourceRange()))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002948 return true;
2949
2950 // Completeing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00002951 ExprTy = E->getType();
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002952 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2953 ExprTy = Ref->getPointeeType();
2954
Richard Trieuccd891a2011-09-09 01:45:06 +00002955 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2956 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002957 return true;
2958
Nico Webercf739922011-06-15 02:47:03 +00002959 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002960 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00002961 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2962 QualType OType = PVD->getOriginalType();
2963 QualType Type = PVD->getType();
2964 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002965 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00002966 << Type << OType;
2967 Diag(PVD->getLocation(), diag::note_declared_at);
2968 }
2969 }
2970 }
2971 }
2972
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002973 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002974}
2975
2976/// \brief Check the constraints on operands to unary expression and type
2977/// traits.
2978///
2979/// This will complete any types necessary, and validate the various constraints
2980/// on those operands.
2981///
Reid Spencer5f016e22007-07-11 17:01:13 +00002982/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002983/// C99 6.3.2.1p[2-4] all state:
2984/// Except when it is the operand of the sizeof operator ...
2985///
2986/// C++ [expr.sizeof]p4
2987/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2988/// standard conversions are not applied to the operand of sizeof.
2989///
2990/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00002991bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002992 SourceLocation OpLoc,
2993 SourceRange ExprRange,
2994 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002995 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00002996 return false;
2997
Sebastian Redl5d484e82009-11-23 17:18:46 +00002998 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2999 // the result is the size of the referenced type."
3000 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3001 // result shall be the alignment of the referenced type."
Richard Trieuccd891a2011-09-09 01:45:06 +00003002 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3003 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003004
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003005 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003006 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003007
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003008 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003009 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003010 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003011 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Richard Trieuccd891a2011-09-09 01:45:06 +00003013 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003014 diag::err_sizeof_alignof_incomplete_type,
3015 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003016 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Richard Trieuccd891a2011-09-09 01:45:06 +00003018 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003019 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003020 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Chris Lattner1efaa952009-04-24 00:30:45 +00003022 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003023}
3024
Chandler Carruth9d342d02011-05-26 08:53:10 +00003025static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003026 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003027
Mike Stump1eb44332009-09-09 15:08:12 +00003028 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003029 if (isa<DeclRefExpr>(E))
3030 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003031
3032 // Cannot know anything else if the expression is dependent.
3033 if (E->isTypeDependent())
3034 return false;
3035
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003036 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003037 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3038 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003039 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003040 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003041
3042 // Alignment of a field access is always okay, so long as it isn't a
3043 // bit-field.
3044 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003045 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003046 return false;
3047
Chandler Carruth9d342d02011-05-26 08:53:10 +00003048 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003049}
3050
Chandler Carruth9d342d02011-05-26 08:53:10 +00003051bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003052 E = E->IgnoreParens();
3053
3054 // Cannot know anything else if the expression is dependent.
3055 if (E->isTypeDependent())
3056 return false;
3057
Chandler Carruth9d342d02011-05-26 08:53:10 +00003058 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003059}
3060
Douglas Gregorba498172009-03-13 21:01:28 +00003061/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003062ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003063Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3064 SourceLocation OpLoc,
3065 UnaryExprOrTypeTrait ExprKind,
3066 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003067 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003068 return ExprError();
3069
John McCalla93c9342009-12-07 02:54:59 +00003070 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003071
Douglas Gregorba498172009-03-13 21:01:28 +00003072 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003073 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003074 return ExprError();
3075
3076 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003077 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3078 Context.getSizeType(),
3079 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003080}
3081
3082/// \brief Build a sizeof or alignof expression given an expression
3083/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003084ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003085Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3086 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003087 ExprResult PE = CheckPlaceholderExpr(E);
3088 if (PE.isInvalid())
3089 return ExprError();
3090
3091 E = PE.get();
3092
Douglas Gregorba498172009-03-13 21:01:28 +00003093 // Verify that the operand is valid.
3094 bool isInvalid = false;
3095 if (E->isTypeDependent()) {
3096 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003097 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003098 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003099 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003100 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003101 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003102 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003103 isInvalid = true;
3104 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003105 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003106 }
3107
3108 if (isInvalid)
3109 return ExprError();
3110
Eli Friedman71b8fb52012-01-21 01:01:51 +00003111 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3112 PE = TranformToPotentiallyEvaluated(E);
3113 if (PE.isInvalid()) return ExprError();
3114 E = PE.take();
3115 }
3116
Douglas Gregorba498172009-03-13 21:01:28 +00003117 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003118 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003119 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003120 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003121}
3122
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003123/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3124/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003125/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003126ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003127Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003128 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003129 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003130 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003131 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003132
Richard Trieuccd891a2011-09-09 01:45:06 +00003133 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003134 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003135 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003136 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003137 }
Sebastian Redl05189992008-11-11 17:56:53 +00003138
Douglas Gregorba498172009-03-13 21:01:28 +00003139 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003140 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003141 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003142}
3143
John Wiegley429bb272011-04-08 18:41:53 +00003144static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003145 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003146 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003147 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003148
John McCallf6a16482010-12-04 03:47:34 +00003149 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003150 if (V.get()->getObjectKind() != OK_Ordinary) {
3151 V = S.DefaultLvalueConversion(V.take());
3152 if (V.isInvalid())
3153 return QualType();
3154 }
John McCallf6a16482010-12-04 03:47:34 +00003155
Chris Lattnercc26ed72007-08-26 05:39:26 +00003156 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003157 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003158 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Chris Lattnercc26ed72007-08-26 05:39:26 +00003160 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003161 if (V.get()->getType()->isArithmeticType())
3162 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003163
John McCall2cd11fe2010-10-12 02:09:17 +00003164 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003165 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003166 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003167 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003168 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003169 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003170 }
3171
Chris Lattnercc26ed72007-08-26 05:39:26 +00003172 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003173 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003174 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003175 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003176}
3177
3178
Reid Spencer5f016e22007-07-11 17:01:13 +00003179
John McCall60d7b3a2010-08-24 06:29:42 +00003180ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003181Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003182 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003183 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003184 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003185 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003186 case tok::plusplus: Opc = UO_PostInc; break;
3187 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003189
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003190 // Since this might is a postfix expression, get rid of ParenListExprs.
3191 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3192 if (Result.isInvalid()) return ExprError();
3193 Input = Result.take();
3194
John McCall9ae2f072010-08-23 23:25:46 +00003195 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003196}
3197
John McCall1503f0d2012-07-31 05:14:30 +00003198/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3199///
3200/// \return true on error
3201static bool checkArithmeticOnObjCPointer(Sema &S,
3202 SourceLocation opLoc,
3203 Expr *op) {
3204 assert(op->getType()->isObjCObjectPointerType());
3205 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3206 return false;
3207
3208 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3209 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3210 << op->getSourceRange();
3211 return true;
3212}
3213
John McCall60d7b3a2010-08-24 06:29:42 +00003214ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003215Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3216 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003217 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003218 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003219 if (Result.isInvalid()) return ExprError();
3220 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003221
John McCall9ae2f072010-08-23 23:25:46 +00003222 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003223
David Blaikie4e4d0842012-03-11 07:00:24 +00003224 if (getLangOpts().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003225 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003226 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003227 Context.DependentTy,
3228 VK_LValue, OK_Ordinary,
3229 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003230 }
3231
David Blaikie4e4d0842012-03-11 07:00:24 +00003232 if (getLangOpts().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003233 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003234 LHSExp->getType()->isEnumeralType() ||
3235 RHSExp->getType()->isRecordType() ||
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003236 RHSExp->getType()->isEnumeralType()) &&
3237 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCall9ae2f072010-08-23 23:25:46 +00003238 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003239 }
3240
John McCall9ae2f072010-08-23 23:25:46 +00003241 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003242}
3243
John McCall60d7b3a2010-08-24 06:29:42 +00003244ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003245Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003246 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003247 Expr *LHSExp = Base;
3248 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003249
Chris Lattner12d9ff62007-07-16 00:14:47 +00003250 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003251 if (!LHSExp->getType()->getAs<VectorType>()) {
3252 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3253 if (Result.isInvalid())
3254 return ExprError();
3255 LHSExp = Result.take();
3256 }
3257 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3258 if (Result.isInvalid())
3259 return ExprError();
3260 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003261
Chris Lattner12d9ff62007-07-16 00:14:47 +00003262 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003263 ExprValueKind VK = VK_LValue;
3264 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003265
Reid Spencer5f016e22007-07-11 17:01:13 +00003266 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003267 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003268 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003269 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003270 Expr *BaseExpr, *IndexExpr;
3271 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003272 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3273 BaseExpr = LHSExp;
3274 IndexExpr = RHSExp;
3275 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003276 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003277 BaseExpr = LHSExp;
3278 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003279 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003280 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003281 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003282 BaseExpr = LHSExp;
3283 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003284
3285 // Use custom logic if this should be the pseudo-object subscript
3286 // expression.
3287 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3288 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3289
Steve Naroff14108da2009-07-10 23:34:53 +00003290 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003291 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3292 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3293 << ResultType << BaseExpr->getSourceRange();
3294 return ExprError();
3295 }
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00003296 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3297 // Handle the uncommon case of "123[Ptr]".
3298 BaseExpr = RHSExp;
3299 IndexExpr = LHSExp;
3300 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003301 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003302 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003303 // Handle the uncommon case of "123[Ptr]".
3304 BaseExpr = RHSExp;
3305 IndexExpr = LHSExp;
3306 ResultType = PTy->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00003307 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3308 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3309 << ResultType << BaseExpr->getSourceRange();
3310 return ExprError();
3311 }
John McCall183700f2009-09-21 23:43:11 +00003312 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003313 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003314 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003315 VK = LHSExp->getValueKind();
3316 if (VK != VK_RValue)
3317 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003318
Chris Lattner12d9ff62007-07-16 00:14:47 +00003319 // FIXME: need to deal with const...
3320 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003321 } else if (LHSTy->isArrayType()) {
3322 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003323 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003324 // wasn't promoted because of the C90 rule that doesn't
3325 // allow promoting non-lvalue arrays. Warn, then
3326 // force the promotion here.
3327 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3328 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003329 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3330 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003331 LHSTy = LHSExp->getType();
3332
3333 BaseExpr = LHSExp;
3334 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003335 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003336 } else if (RHSTy->isArrayType()) {
3337 // Same as previous, except for 123[f().a] case
3338 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3339 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003340 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3341 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003342 RHSTy = RHSExp->getType();
3343
3344 BaseExpr = RHSExp;
3345 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003346 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003347 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003348 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3349 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003350 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003351 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003352 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003353 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3354 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003355
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003356 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003357 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3358 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003359 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3360
Douglas Gregore7450f52009-03-24 19:52:54 +00003361 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003362 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3363 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003364 // incomplete types are not object types.
3365 if (ResultType->isFunctionType()) {
3366 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3367 << ResultType << BaseExpr->getSourceRange();
3368 return ExprError();
3369 }
Mike Stump1eb44332009-09-09 15:08:12 +00003370
David Blaikie4e4d0842012-03-11 07:00:24 +00003371 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00003372 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003373 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3374 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003375
3376 // C forbids expressions of unqualified void type from being l-values.
3377 // See IsCForbiddenLValueType.
3378 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003379 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003380 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003381 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00003382 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003383
John McCall09431682010-11-18 19:01:18 +00003384 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003385 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003386
Mike Stumpeed9cac2009-02-19 03:04:26 +00003387 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003388 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003389}
3390
John McCall60d7b3a2010-08-24 06:29:42 +00003391ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003392 FunctionDecl *FD,
3393 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003394 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003395 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003396 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003397 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003398 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003399 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003400 return ExprError();
3401 }
3402
3403 if (Param->hasUninstantiatedDefaultArg()) {
3404 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003405
Richard Smithadb1d4c2012-07-22 23:45:10 +00003406 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3407 Param);
3408
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003409 // Instantiate the expression.
3410 MultiLevelTemplateArgumentList ArgList
3411 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003412
Nico Weber08e41a62010-11-29 18:19:25 +00003413 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003414 = ArgList.getInnermost();
Richard Smith7e54fb52012-07-16 01:09:10 +00003415 InstantiatingTemplate Inst(*this, CallLoc, Param,
3416 ArrayRef<TemplateArgument>(Innermost.first,
3417 Innermost.second));
Richard Smithab91ef12012-07-08 02:38:24 +00003418 if (Inst)
3419 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003420
Nico Weber08e41a62010-11-29 18:19:25 +00003421 ExprResult Result;
3422 {
3423 // C++ [dcl.fct.default]p5:
3424 // The names in the [default argument] expression are bound, and
3425 // the semantic constraints are checked, at the point where the
3426 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003427 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003428 LocalInstantiationScope Local(*this);
Nico Weber08e41a62010-11-29 18:19:25 +00003429 Result = SubstExpr(UninstExpr, ArgList);
3430 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003431 if (Result.isInvalid())
3432 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003434 // Check the expression as an initializer for the parameter.
3435 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003436 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003437 InitializationKind Kind
3438 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00003439 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003440 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003441
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003442 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00003443 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003444 if (Result.isInvalid())
3445 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003446
David Blaikiec1c07252012-04-30 18:21:31 +00003447 Expr *Arg = Result.takeAs<Expr>();
David Blaikie9fb1ac52012-05-15 21:57:38 +00003448 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003449 // Build the default argument expression.
David Blaikiec1c07252012-04-30 18:21:31 +00003450 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003451 }
3452
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003453 // If the default expression creates temporaries, we need to
3454 // push them to the current stack of expression temporaries so they'll
3455 // be properly destroyed.
3456 // FIXME: We should really be rebuilding the default argument with new
3457 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00003458 // We don't need to do that with block decls, though, because
3459 // blocks in default argument expression can never capture anything.
3460 if (isa<ExprWithCleanups>(Param->getInit())) {
3461 // Set the "needs cleanups" bit regardless of whether there are
3462 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00003463 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00003464
3465 // Append all the objects to the cleanup list. Right now, this
3466 // should always be a no-op, because blocks in default argument
3467 // expressions should never be able to capture anything.
3468 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3469 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003470 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003471
3472 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003473 // Just mark all of the declarations in this potentially-evaluated expression
3474 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00003475 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3476 /*SkipLocalVariables=*/true);
Douglas Gregor036aed12009-12-23 23:03:06 +00003477 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003478}
3479
Richard Smith831421f2012-06-25 20:30:08 +00003480
3481Sema::VariadicCallType
3482Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3483 Expr *Fn) {
3484 if (Proto && Proto->isVariadic()) {
3485 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3486 return VariadicConstructor;
3487 else if (Fn && Fn->getType()->isBlockPointerType())
3488 return VariadicBlock;
3489 else if (FDecl) {
3490 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3491 if (Method->isInstance())
3492 return VariadicMethod;
3493 }
3494 return VariadicFunction;
3495 }
3496 return VariadicDoesNotApply;
3497}
3498
Douglas Gregor88a35142008-12-22 05:46:06 +00003499/// ConvertArgumentsForCall - Converts the arguments specified in
3500/// Args/NumArgs to the parameter types of the function FDecl with
3501/// function prototype Proto. Call is the call expression itself, and
3502/// Fn is the function expression. For a C++ member function, this
3503/// routine does not attempt to convert the object argument. Returns
3504/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003505bool
3506Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003507 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003508 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003509 Expr **Args, unsigned NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003510 SourceLocation RParenLoc,
3511 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00003512 // Bail out early if calling a builtin with custom typechecking.
3513 // We don't need to do this in the
3514 if (FDecl)
3515 if (unsigned ID = FDecl->getBuiltinID())
3516 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3517 return false;
3518
Mike Stumpeed9cac2009-02-19 03:04:26 +00003519 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003520 // assignment, to the types of the corresponding parameter, ...
3521 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003522 bool Invalid = false;
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003523 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne1f240762011-10-02 23:49:29 +00003524 unsigned FnKind = Fn->getType()->isBlockPointerType()
3525 ? 1 /* block */
3526 : (IsExecConfig ? 3 /* kernel function (exec config) */
3527 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003528
Douglas Gregor88a35142008-12-22 05:46:06 +00003529 // If too few arguments are available (and we don't have default
3530 // arguments for the remaining parameters), don't make the call.
3531 if (NumArgs < NumArgsInProto) {
Peter Collingbourneaf15b4d2011-10-02 23:49:20 +00003532 if (NumArgs < MinArgs) {
Richard Smithf7b80562012-05-11 05:16:41 +00003533 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3534 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3535 ? diag::err_typecheck_call_too_few_args_one
3536 : diag::err_typecheck_call_too_few_args_at_least_one)
3537 << FnKind
3538 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3539 else
3540 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3541 ? diag::err_typecheck_call_too_few_args
3542 : diag::err_typecheck_call_too_few_args_at_least)
3543 << FnKind
3544 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003545
3546 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003547 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003548 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3549 << FDecl;
3550
3551 return true;
3552 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003553 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003554 }
3555
3556 // If too many are passed and not variadic, error on the extras and drop
3557 // them.
3558 if (NumArgs > NumArgsInProto) {
3559 if (!Proto->isVariadic()) {
Richard Smithc608c3c2012-05-15 06:21:54 +00003560 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3561 Diag(Args[NumArgsInProto]->getLocStart(),
3562 MinArgs == NumArgsInProto
3563 ? diag::err_typecheck_call_too_many_args_one
3564 : diag::err_typecheck_call_too_many_args_at_most_one)
3565 << FnKind
3566 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3567 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3568 Args[NumArgs-1]->getLocEnd());
3569 else
3570 Diag(Args[NumArgsInProto]->getLocStart(),
3571 MinArgs == NumArgsInProto
3572 ? diag::err_typecheck_call_too_many_args
3573 : diag::err_typecheck_call_too_many_args_at_most)
3574 << FnKind
3575 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3576 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3577 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003578
3579 // Emit the location of the prototype.
Peter Collingbourne1f240762011-10-02 23:49:29 +00003580 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003581 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3582 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003583
Douglas Gregor88a35142008-12-22 05:46:06 +00003584 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003585 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003586 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003587 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003588 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003589 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00003590 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3591
Daniel Dunbar96a00142012-03-09 18:35:03 +00003592 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003593 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003594 if (Invalid)
3595 return true;
3596 unsigned TotalNumArgs = AllArgs.size();
3597 for (unsigned i = 0; i < TotalNumArgs; ++i)
3598 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003599
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003600 return false;
3601}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003602
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003603bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3604 FunctionDecl *FDecl,
3605 const FunctionProtoType *Proto,
3606 unsigned FirstProtoArg,
3607 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003608 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00003609 VariadicCallType CallType,
3610 bool AllowExplicit) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003611 unsigned NumArgsInProto = Proto->getNumArgs();
3612 unsigned NumArgsToCheck = NumArgs;
3613 bool Invalid = false;
3614 if (NumArgs != NumArgsInProto)
3615 // Use default arguments for missing arguments
3616 NumArgsToCheck = NumArgsInProto;
3617 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003618 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003619 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003620 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003621
Douglas Gregor88a35142008-12-22 05:46:06 +00003622 Expr *Arg;
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003623 ParmVarDecl *Param;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003624 if (ArgIx < NumArgs) {
3625 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003626
Daniel Dunbar96a00142012-03-09 18:35:03 +00003627 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003628 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003629 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003630 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003631
Douglas Gregora188ff22009-12-22 16:09:06 +00003632 // Pass the argument
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003633 Param = 0;
Douglas Gregora188ff22009-12-22 16:09:06 +00003634 if (FDecl && i < FDecl->getNumParams())
3635 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003636
John McCall5acb0c92011-10-17 18:40:02 +00003637 // Strip the unbridged-cast placeholder expression off, if applicable.
3638 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3639 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3640 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3641 Arg = stripARCUnbridgedCast(Arg);
3642
Douglas Gregora188ff22009-12-22 16:09:06 +00003643 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003644 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003645 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3646 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003647 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003648 SourceLocation(),
Douglas Gregored878af2012-02-24 23:56:31 +00003649 Owned(Arg),
3650 /*TopLevelOfInitList=*/false,
3651 AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00003652 if (ArgE.isInvalid())
3653 return true;
3654
3655 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003656 } else {
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003657 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003658
John McCall60d7b3a2010-08-24 06:29:42 +00003659 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003660 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003661 if (ArgExpr.isInvalid())
3662 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003663
Anders Carlsson56c5e332009-08-25 03:49:14 +00003664 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003665 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003666
3667 // Check for array bounds violations for each argument to the call. This
3668 // check only triggers warnings when the argument isn't a more complex Expr
3669 // with its own checking, such as a BinaryOperator.
3670 CheckArrayAccess(Arg);
3671
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003672 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3673 CheckStaticArrayArgument(CallLoc, Param, Arg);
3674
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003675 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003676 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003677
Douglas Gregor88a35142008-12-22 05:46:06 +00003678 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003679 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003680 // Assume that extern "C" functions with variadic arguments that
3681 // return __unknown_anytype aren't *really* variadic.
3682 if (Proto->getResultType() == Context.UnknownAnyTy &&
3683 FDecl && FDecl->isExternC()) {
3684 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3685 ExprResult arg;
3686 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3687 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3688 else
3689 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3690 Invalid |= arg.isInvalid();
3691 AllArgs.push_back(arg.take());
3692 }
3693
3694 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3695 } else {
3696 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003697 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3698 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003699 Invalid |= Arg.isInvalid();
3700 AllArgs.push_back(Arg.take());
3701 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003702 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00003703
3704 // Check for array bounds violations.
3705 for (unsigned i = ArgIx; i != NumArgs; ++i)
3706 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00003707 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003708 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003709}
3710
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003711static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3712 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3713 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3714 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3715 << ATL->getLocalSourceRange();
3716}
3717
3718/// CheckStaticArrayArgument - If the given argument corresponds to a static
3719/// array parameter, check that it is non-null, and that if it is formed by
3720/// array-to-pointer decay, the underlying array is sufficiently large.
3721///
3722/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3723/// array type derivation, then for each call to the function, the value of the
3724/// corresponding actual argument shall provide access to the first element of
3725/// an array with at least as many elements as specified by the size expression.
3726void
3727Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3728 ParmVarDecl *Param,
3729 const Expr *ArgExpr) {
3730 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00003731 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00003732 return;
3733
3734 QualType OrigTy = Param->getOriginalType();
3735
3736 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3737 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3738 return;
3739
3740 if (ArgExpr->isNullPointerConstant(Context,
3741 Expr::NPC_NeverValueDependent)) {
3742 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3743 DiagnoseCalleeStaticArrayParam(*this, Param);
3744 return;
3745 }
3746
3747 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3748 if (!CAT)
3749 return;
3750
3751 const ConstantArrayType *ArgCAT =
3752 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3753 if (!ArgCAT)
3754 return;
3755
3756 if (ArgCAT->getSize().ult(CAT->getSize())) {
3757 Diag(CallLoc, diag::warn_static_array_too_small)
3758 << ArgExpr->getSourceRange()
3759 << (unsigned) ArgCAT->getSize().getZExtValue()
3760 << (unsigned) CAT->getSize().getZExtValue();
3761 DiagnoseCalleeStaticArrayParam(*this, Param);
3762 }
3763}
3764
John McCall755d8492011-04-12 00:42:48 +00003765/// Given a function expression of unknown-any type, try to rebuild it
3766/// to have a function type.
3767static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3768
Steve Narofff69936d2007-09-16 03:34:24 +00003769/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003770/// This provides the location of the left/right parens and a list of comma
3771/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003772ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003773Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003774 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003775 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003776 unsigned NumArgs = ArgExprs.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003777
3778 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003779 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003780 if (Result.isInvalid()) return ExprError();
3781 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Benjamin Kramer5354e772012-08-23 23:38:35 +00003783 Expr **Args = ArgExprs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00003784
David Blaikie4e4d0842012-03-11 07:00:24 +00003785 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003786 // If this is a pseudo-destructor expression, build the call immediately.
3787 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3788 if (NumArgs > 0) {
3789 // Pseudo-destructor calls should not have any arguments.
3790 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003791 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003792 SourceRange(Args[0]->getLocStart(),
3793 Args[NumArgs-1]->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00003794 }
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Douglas Gregora71d8192009-09-04 17:36:40 +00003796 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003797 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003798 }
Mike Stump1eb44332009-09-09 15:08:12 +00003799
Douglas Gregor17330012009-02-04 15:01:18 +00003800 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003801 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003802 // FIXME: Will need to cache the results of name lookup (including ADL) in
3803 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003804 bool Dependent = false;
3805 if (Fn->isTypeDependent())
3806 Dependent = true;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003807 else if (Expr::hasAnyTypeDependentArguments(
3808 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregor17330012009-02-04 15:01:18 +00003809 Dependent = true;
3810
Peter Collingbournee08ce652011-02-09 21:07:24 +00003811 if (Dependent) {
3812 if (ExecConfig) {
3813 return Owned(new (Context) CUDAKernelCallExpr(
3814 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3815 Context.DependentTy, VK_RValue, RParenLoc));
3816 } else {
3817 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3818 Context.DependentTy, VK_RValue,
3819 RParenLoc));
3820 }
3821 }
Douglas Gregor17330012009-02-04 15:01:18 +00003822
3823 // Determine whether this is a call to an object (C++ [over.call.object]).
3824 if (Fn->getType()->isRecordType())
3825 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003826 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003827
John McCall755d8492011-04-12 00:42:48 +00003828 if (Fn->getType() == Context.UnknownAnyTy) {
3829 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3830 if (result.isInvalid()) return ExprError();
3831 Fn = result.take();
3832 }
3833
John McCall864c0412011-04-26 20:42:42 +00003834 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003835 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003836 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003837 }
John McCall864c0412011-04-26 20:42:42 +00003838 }
John McCall129e2df2009-11-30 22:42:35 +00003839
John McCall864c0412011-04-26 20:42:42 +00003840 // Check for overloaded calls. This can happen even in C due to extensions.
3841 if (Fn->getType() == Context.OverloadTy) {
3842 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3843
Douglas Gregoree697e62011-10-13 18:10:35 +00003844 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00003845 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00003846 OverloadExpr *ovl = find.Expression;
3847 if (isa<UnresolvedLookupExpr>(ovl)) {
3848 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3849 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3850 RParenLoc, ExecConfig);
3851 } else {
John McCallaa81e162009-12-01 22:10:20 +00003852 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003853 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003854 }
3855 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003856 }
3857
Douglas Gregorfa047642009-02-04 00:32:51 +00003858 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00003859 if (Fn->getType() == Context.UnknownAnyTy) {
3860 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3861 if (result.isInvalid()) return ExprError();
3862 Fn = result.take();
3863 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003864
Eli Friedmanefa42f72009-12-26 03:35:45 +00003865 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003866
John McCall3b4294e2009-12-16 12:17:52 +00003867 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003868 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3869 if (UnOp->getOpcode() == UO_AddrOf)
3870 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3871
John McCall3b4294e2009-12-16 12:17:52 +00003872 if (isa<DeclRefExpr>(NakedFn))
3873 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003874 else if (isa<MemberExpr>(NakedFn))
3875 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003876
Peter Collingbournee08ce652011-02-09 21:07:24 +00003877 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003878 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003879}
3880
3881ExprResult
3882Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003883 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbournee08ce652011-02-09 21:07:24 +00003884 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3885 if (!ConfigDecl)
3886 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3887 << "cudaConfigureCall");
3888 QualType ConfigQTy = ConfigDecl->getType();
3889
3890 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCallf4b88a42012-03-10 09:33:50 +00003891 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedman5f2987c2012-02-02 03:46:19 +00003892 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00003893
Peter Collingbourne1f240762011-10-02 23:49:29 +00003894 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3895 /*IsExecConfig=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003896}
3897
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003898/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3899///
3900/// __builtin_astype( value, dst type )
3901///
Richard Trieuccd891a2011-09-09 01:45:06 +00003902ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003903 SourceLocation BuiltinLoc,
3904 SourceLocation RParenLoc) {
3905 ExprValueKind VK = VK_RValue;
3906 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00003907 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3908 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003909 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3910 return ExprError(Diag(BuiltinLoc,
3911 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003912 << DstTy
3913 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00003914 << E->getSourceRange());
3915 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieu67e29332011-08-02 04:35:43 +00003916 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003917}
3918
John McCall3b4294e2009-12-16 12:17:52 +00003919/// BuildResolvedCallExpr - Build a call to a resolved expression,
3920/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003921/// unary-convert to an expression of function-pointer or
3922/// block-pointer type.
3923///
3924/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003925ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003926Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3927 SourceLocation LParenLoc,
3928 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003929 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00003930 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00003931 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3932
Chris Lattner04421082008-04-08 04:40:51 +00003933 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003934 ExprResult Result = UsualUnaryConversions(Fn);
3935 if (Result.isInvalid())
3936 return ExprError();
3937 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003938
Chris Lattner925e60d2007-12-28 05:29:59 +00003939 // Make the call expr early, before semantic checks. This guarantees cleanup
3940 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003941 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00003942 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00003943 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3944 cast<CallExpr>(Config),
3945 Args, NumArgs,
3946 Context.BoolTy,
3947 VK_RValue,
3948 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00003949 else
Peter Collingbournee08ce652011-02-09 21:07:24 +00003950 TheCall = new (Context) CallExpr(Context, Fn,
3951 Args, NumArgs,
3952 Context.BoolTy,
3953 VK_RValue,
3954 RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003955
John McCall8e10f3b2011-02-26 05:39:39 +00003956 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3957
3958 // Bail out early if calling a builtin with custom typechecking.
3959 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3960 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3961
John McCall1de4d4e2011-04-07 08:22:57 +00003962 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003963 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003964 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003965 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3966 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003967 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003968 if (FuncT == 0)
3969 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3970 << Fn->getType() << Fn->getSourceRange());
3971 } else if (const BlockPointerType *BPT =
3972 Fn->getType()->getAs<BlockPointerType>()) {
3973 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3974 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003975 // Handle calls to expressions of unknown-any type.
3976 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003977 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003978 if (rewrite.isInvalid()) return ExprError();
3979 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003980 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003981 goto retry;
3982 }
3983
Sebastian Redl0eb23302009-01-19 00:08:26 +00003984 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3985 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003986 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003987
David Blaikie4e4d0842012-03-11 07:00:24 +00003988 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003989 if (Config) {
3990 // CUDA: Kernel calls must be to global functions
3991 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3992 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3993 << FDecl->getName() << Fn->getSourceRange());
3994
3995 // CUDA: Kernel function must have 'void' return type
3996 if (!FuncT->getResultType()->isVoidType())
3997 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3998 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00003999 } else {
4000 // CUDA: Calls to global functions must be configured
4001 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4002 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4003 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004004 }
4005 }
4006
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004007 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004008 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004009 Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004010 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004011 return ExprError();
4012
Chris Lattner925e60d2007-12-28 05:29:59 +00004013 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004014 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00004015 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004016
Richard Smith831421f2012-06-25 20:30:08 +00004017 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4018 if (Proto) {
John McCall9ae2f072010-08-23 23:25:46 +00004019 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004020 RParenLoc, IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004021 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004022 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004023 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004024
Douglas Gregor74734d52009-04-02 15:37:10 +00004025 if (FDecl) {
4026 // Check if we have too few/too many template arguments, based
4027 // on our knowledge of the function definition.
4028 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004029 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004030 Proto = Def->getType()->getAs<FunctionProtoType>();
Douglas Gregor46542412010-10-25 20:39:23 +00004031 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004032 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4033 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004034 }
Douglas Gregor46542412010-10-25 20:39:23 +00004035
4036 // If the function we're calling isn't a function prototype, but we have
4037 // a function prototype from a prior declaratiom, use that prototype.
4038 if (!FDecl->hasPrototype())
4039 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004040 }
4041
Steve Naroffb291ab62007-08-28 23:30:39 +00004042 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00004043 for (unsigned i = 0; i != NumArgs; i++) {
4044 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004045
4046 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00004047 InitializedEntity Entity
4048 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00004049 Proto->getArgType(i),
4050 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00004051 ExprResult ArgE = PerformCopyInitialization(Entity,
4052 SourceLocation(),
4053 Owned(Arg));
4054 if (ArgE.isInvalid())
4055 return true;
4056
4057 Arg = ArgE.takeAs<Expr>();
4058
4059 } else {
John Wiegley429bb272011-04-08 18:41:53 +00004060 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4061
4062 if (ArgE.isInvalid())
4063 return true;
4064
4065 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00004066 }
4067
Daniel Dunbar96a00142012-03-09 18:35:03 +00004068 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004069 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004070 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00004071 return ExprError();
4072
Chris Lattner925e60d2007-12-28 05:29:59 +00004073 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00004074 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004075 }
Chris Lattner925e60d2007-12-28 05:29:59 +00004076
Douglas Gregor88a35142008-12-22 05:46:06 +00004077 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4078 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004079 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4080 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00004081
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00004082 // Check for sentinels
4083 if (NDecl)
4084 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004085
Chris Lattner59907c42007-08-10 20:18:51 +00004086 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00004087 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004088 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004089 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004090
John McCall8e10f3b2011-02-26 05:39:39 +00004091 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00004092 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00004093 } else if (NDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00004094 if (CheckBlockCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00004095 return ExprError();
4096 }
Chris Lattner59907c42007-08-10 20:18:51 +00004097
John McCall9ae2f072010-08-23 23:25:46 +00004098 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00004099}
4100
John McCall60d7b3a2010-08-24 06:29:42 +00004101ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004102Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004103 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00004104 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00004105 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00004106 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00004107
4108 TypeSourceInfo *TInfo;
4109 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4110 if (!TInfo)
4111 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4112
John McCall9ae2f072010-08-23 23:25:46 +00004113 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00004114}
4115
John McCall60d7b3a2010-08-24 06:29:42 +00004116ExprResult
John McCall42f56b52010-01-18 19:35:47 +00004117Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00004118 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00004119 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00004120
Eli Friedman6223c222008-05-20 05:22:08 +00004121 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004122 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00004123 diag::err_illegal_decl_array_incomplete_type,
4124 SourceRange(LParenLoc,
4125 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00004126 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004127 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004128 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00004129 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004130 } else if (!literalType->isDependentType() &&
4131 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004132 diag::err_typecheck_decl_incomplete_type,
4133 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004134 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00004135
Douglas Gregor99a2e602009-12-16 01:38:02 +00004136 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00004137 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004138 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00004139 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004140 SourceRange(LParenLoc, RParenLoc),
4141 /*InitList=*/true);
Richard Trieuccd891a2011-09-09 01:45:06 +00004142 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004143 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4144 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00004145 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004146 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004147 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00004148
Chris Lattner371f2582008-12-04 23:50:19 +00004149 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00004150 if (isFileScope) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00004151 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004152 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00004153 }
Eli Friedman08544622009-12-22 02:35:53 +00004154
John McCallf89e55a2010-11-18 06:31:45 +00004155 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00004156 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00004157
Douglas Gregor751ec9b2011-06-17 04:59:12 +00004158 return MaybeBindToTemporary(
4159 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00004160 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00004161}
4162
John McCall60d7b3a2010-08-24 06:29:42 +00004163ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004164Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004165 SourceLocation RBraceLoc) {
Richard Trieuccd891a2011-09-09 01:45:06 +00004166 unsigned NumInit = InitArgList.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00004167 Expr **InitList = InitArgList.data();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00004168
John McCall3c3b7f92011-10-25 17:37:35 +00004169 // Immediately handle non-overload placeholders. Overloads can be
4170 // resolved contextually, but everything else here can't.
4171 for (unsigned I = 0; I != NumInit; ++I) {
John McCall32509f12011-11-15 01:35:18 +00004172 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00004173 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4174
4175 // Ignore failures; dropping the entire initializer list because
4176 // of one failure would be terrible for indexing/etc.
4177 if (result.isInvalid()) continue;
4178
4179 InitList[I] = result.take();
4180 }
4181 }
4182
Steve Naroff08d92e42007-09-15 18:49:24 +00004183 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00004184 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004185
Ted Kremenek709210f2010-04-13 23:39:13 +00004186 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4187 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00004188 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004189 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00004190}
4191
John McCalldc05b112011-09-10 01:16:55 +00004192/// Do an explicit extend of the given block pointer if we're in ARC.
4193static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4194 assert(E.get()->getType()->isBlockPointerType());
4195 assert(E.get()->isRValue());
4196
4197 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00004198 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00004199
4200 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00004201 CK_ARCExtendBlockObject, E.get(),
John McCalldc05b112011-09-10 01:16:55 +00004202 /*base path*/ 0, VK_RValue);
4203 S.ExprNeedsCleanups = true;
4204}
4205
4206/// Prepare a conversion of the given expression to an ObjC object
4207/// pointer type.
4208CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4209 QualType type = E.get()->getType();
4210 if (type->isObjCObjectPointerType()) {
4211 return CK_BitCast;
4212 } else if (type->isBlockPointerType()) {
4213 maybeExtendBlockObject(*this, E);
4214 return CK_BlockPointerToObjCPointerCast;
4215 } else {
4216 assert(type->isPointerType());
4217 return CK_CPointerToObjCPointerCast;
4218 }
4219}
4220
John McCallf3ea8cf2010-11-14 08:17:51 +00004221/// Prepares for a scalar cast, performing all the necessary stages
4222/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00004223CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00004224 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4225 // Also, callers should have filtered out the invalid cases with
4226 // pointers. Everything else should be possible.
4227
John Wiegley429bb272011-04-08 18:41:53 +00004228 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00004229 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00004230 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00004231
John McCall1d9b3b22011-09-09 05:25:32 +00004232 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004233 case Type::STK_MemberPointer:
4234 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00004235
John McCall1d9b3b22011-09-09 05:25:32 +00004236 case Type::STK_CPointer:
4237 case Type::STK_BlockPointer:
4238 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004239 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004240 case Type::STK_CPointer:
4241 return CK_BitCast;
4242 case Type::STK_BlockPointer:
4243 return (SrcKind == Type::STK_BlockPointer
4244 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4245 case Type::STK_ObjCObjectPointer:
4246 if (SrcKind == Type::STK_ObjCObjectPointer)
4247 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00004248 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00004249 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00004250 maybeExtendBlockObject(*this, Src);
4251 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004252 case Type::STK_Bool:
4253 return CK_PointerToBoolean;
4254 case Type::STK_Integral:
4255 return CK_PointerToIntegral;
4256 case Type::STK_Floating:
4257 case Type::STK_FloatingComplex:
4258 case Type::STK_IntegralComplex:
4259 case Type::STK_MemberPointer:
4260 llvm_unreachable("illegal cast from pointer");
4261 }
David Blaikie7530c032012-01-17 06:56:22 +00004262 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004263
John McCalldaa8e4e2010-11-15 09:13:47 +00004264 case Type::STK_Bool: // casting from bool is like casting from an integer
4265 case Type::STK_Integral:
4266 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00004267 case Type::STK_CPointer:
4268 case Type::STK_ObjCObjectPointer:
4269 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00004270 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00004271 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00004272 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00004273 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00004274 case Type::STK_Bool:
4275 return CK_IntegralToBoolean;
4276 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00004277 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004278 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004279 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00004280 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004281 Src = ImpCastExprToType(Src.take(),
4282 DestTy->castAs<ComplexType>()->getElementType(),
4283 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004284 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004285 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004286 Src = ImpCastExprToType(Src.take(),
4287 DestTy->castAs<ComplexType>()->getElementType(),
4288 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00004289 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004290 case Type::STK_MemberPointer:
4291 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004292 }
David Blaikie7530c032012-01-17 06:56:22 +00004293 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004294
John McCalldaa8e4e2010-11-15 09:13:47 +00004295 case Type::STK_Floating:
4296 switch (DestTy->getScalarTypeKind()) {
4297 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00004298 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004299 case Type::STK_Bool:
4300 return CK_FloatingToBoolean;
4301 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00004302 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00004303 case Type::STK_FloatingComplex:
John McCalla180f042011-10-06 23:25:11 +00004304 Src = ImpCastExprToType(Src.take(),
4305 DestTy->castAs<ComplexType>()->getElementType(),
4306 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00004307 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004308 case Type::STK_IntegralComplex:
John McCalla180f042011-10-06 23:25:11 +00004309 Src = ImpCastExprToType(Src.take(),
4310 DestTy->castAs<ComplexType>()->getElementType(),
4311 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00004312 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00004313 case Type::STK_CPointer:
4314 case Type::STK_ObjCObjectPointer:
4315 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004316 llvm_unreachable("valid float->pointer cast?");
4317 case Type::STK_MemberPointer:
4318 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004319 }
David Blaikie7530c032012-01-17 06:56:22 +00004320 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004321
John McCalldaa8e4e2010-11-15 09:13:47 +00004322 case Type::STK_FloatingComplex:
4323 switch (DestTy->getScalarTypeKind()) {
4324 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004325 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00004326 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004327 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00004328 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00004329 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4330 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004331 return CK_FloatingComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004332 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004333 return CK_FloatingCast;
4334 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004335 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004336 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004337 case Type::STK_Integral:
John McCalla180f042011-10-06 23:25:11 +00004338 Src = ImpCastExprToType(Src.take(),
4339 SrcTy->castAs<ComplexType>()->getElementType(),
4340 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004341 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00004342 case Type::STK_CPointer:
4343 case Type::STK_ObjCObjectPointer:
4344 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004345 llvm_unreachable("valid complex float->pointer cast?");
4346 case Type::STK_MemberPointer:
4347 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004348 }
David Blaikie7530c032012-01-17 06:56:22 +00004349 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00004350
John McCalldaa8e4e2010-11-15 09:13:47 +00004351 case Type::STK_IntegralComplex:
4352 switch (DestTy->getScalarTypeKind()) {
4353 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004354 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00004355 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00004356 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00004357 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00004358 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4359 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00004360 return CK_IntegralComplexToReal;
John McCalla180f042011-10-06 23:25:11 +00004361 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00004362 return CK_IntegralCast;
4363 }
John McCalldaa8e4e2010-11-15 09:13:47 +00004364 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00004365 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00004366 case Type::STK_Floating:
John McCalla180f042011-10-06 23:25:11 +00004367 Src = ImpCastExprToType(Src.take(),
4368 SrcTy->castAs<ComplexType>()->getElementType(),
4369 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00004370 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00004371 case Type::STK_CPointer:
4372 case Type::STK_ObjCObjectPointer:
4373 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00004374 llvm_unreachable("valid complex int->pointer cast?");
4375 case Type::STK_MemberPointer:
4376 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00004377 }
David Blaikie7530c032012-01-17 06:56:22 +00004378 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00004379 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004380
John McCallf3ea8cf2010-11-14 08:17:51 +00004381 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00004382}
4383
Anders Carlssonc3516322009-10-16 02:48:28 +00004384bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004385 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004386 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004387
Anders Carlssona64db8f2007-11-27 05:51:55 +00004388 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004389 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004390 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004391 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004392 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004393 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004394 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004395 } else
4396 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004397 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004398 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004399
John McCall2de56d12010-08-25 11:45:40 +00004400 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004401 return false;
4402}
4403
John Wiegley429bb272011-04-08 18:41:53 +00004404ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4405 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004406 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004407
Anders Carlsson16a89042009-10-16 05:23:41 +00004408 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004409
Nate Begeman9b10da62009-06-27 22:05:55 +00004410 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4411 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004412 // In OpenCL, casts between vectors of different types are not allowed.
4413 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00004414 if (SrcTy->isVectorType()) {
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004415 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00004416 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00004417 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004418 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004419 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004420 return ExprError();
4421 }
John McCall2de56d12010-08-25 11:45:40 +00004422 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004423 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004424 }
4425
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004426 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004427 // conversion will take place first from scalar to elt type, and then
4428 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004429 if (SrcTy->isPointerType())
4430 return Diag(R.getBegin(),
4431 diag::err_invalid_conversion_between_vector_and_scalar)
4432 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004433
4434 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004435 ExprResult CastExprRes = Owned(CastExpr);
John McCalla180f042011-10-06 23:25:11 +00004436 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00004437 if (CastExprRes.isInvalid())
4438 return ExprError();
4439 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004440
John McCall2de56d12010-08-25 11:45:40 +00004441 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004442 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004443}
4444
John McCall60d7b3a2010-08-24 06:29:42 +00004445ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004446Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4447 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00004448 SourceLocation RParenLoc, Expr *CastExpr) {
4449 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004450 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004451
Richard Trieuccd891a2011-09-09 01:45:06 +00004452 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004453 if (D.isInvalidType())
4454 return ExprError();
4455
David Blaikie4e4d0842012-03-11 07:00:24 +00004456 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004457 // Check that there are no default arguments (C++ only).
4458 CheckExtraCXXDefaultArguments(D);
4459 }
4460
John McCalle82247a2011-10-01 05:17:03 +00004461 checkUnusedDeclAttributes(D);
4462
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004463 QualType castType = castTInfo->getType();
4464 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004465
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004466 bool isVectorLiteral = false;
4467
4468 // Check for an altivec or OpenCL literal,
4469 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00004470 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4471 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00004472 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00004473 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004474 if (PLE && PLE->getNumExprs() == 0) {
4475 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4476 return ExprError();
4477 }
4478 if (PE || PLE->getNumExprs() == 1) {
4479 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4480 if (!E->getType()->isVectorType())
4481 isVectorLiteral = true;
4482 }
4483 else
4484 isVectorLiteral = true;
4485 }
4486
4487 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4488 // then handle it as such.
4489 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00004490 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004491
Nate Begeman2ef13e52009-08-10 23:49:36 +00004492 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004493 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4494 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00004495 if (isa<ParenListExpr>(CastExpr)) {
4496 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004497 if (Result.isInvalid()) return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00004498 CastExpr = Result.take();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004499 }
John McCallb042fdf2010-01-15 18:56:44 +00004500
Richard Trieuccd891a2011-09-09 01:45:06 +00004501 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004502}
4503
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004504ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4505 SourceLocation RParenLoc, Expr *E,
4506 TypeSourceInfo *TInfo) {
4507 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4508 "Expected paren or paren list expression");
4509
4510 Expr **exprs;
4511 unsigned numExprs;
4512 Expr *subExpr;
4513 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4514 exprs = PE->getExprs();
4515 numExprs = PE->getNumExprs();
4516 } else {
4517 subExpr = cast<ParenExpr>(E)->getSubExpr();
4518 exprs = &subExpr;
4519 numExprs = 1;
4520 }
4521
4522 QualType Ty = TInfo->getType();
4523 assert(Ty->isVectorType() && "Expected vector type");
4524
Chris Lattner5f9e2722011-07-23 10:55:15 +00004525 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004526 const VectorType *VTy = Ty->getAs<VectorType>();
4527 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4528
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004529 // '(...)' form of vector initialization in AltiVec: the number of
4530 // initializers must be one or must match the size of the vector.
4531 // If a single value is specified in the initializer then it will be
4532 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004533 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004534 // The number of initializers must be one or must match the size of the
4535 // vector. If a single value is specified in the initializer then it will
4536 // be replicated to all the components of the vector
4537 if (numExprs == 1) {
4538 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004539 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4540 if (Literal.isInvalid())
4541 return ExprError();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004542 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004543 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004544 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4545 }
4546 else if (numExprs < numElems) {
4547 Diag(E->getExprLoc(),
4548 diag::err_incorrect_number_of_vector_initializers);
4549 return ExprError();
4550 }
4551 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00004552 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004553 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004554 else {
4555 // For OpenCL, when the number of initializers is a single value,
4556 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00004557 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004558 VTy->getVectorKind() == VectorType::GenericVector &&
4559 numExprs == 1) {
4560 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00004561 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4562 if (Literal.isInvalid())
4563 return ExprError();
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004564 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00004565 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004566 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4567 }
4568
Benjamin Kramer14c59822012-02-14 12:06:21 +00004569 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004570 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004571 // FIXME: This means that pretty-printing the final AST will produce curly
4572 // braces instead of the original commas.
4573 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4574 &initExprs[0],
4575 initExprs.size(), RParenLoc);
4576 initE->setType(Ty);
4577 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4578}
4579
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004580/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4581/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004582ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00004583Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4584 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004585 if (!E)
Richard Trieuccd891a2011-09-09 01:45:06 +00004586 return Owned(OrigExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004587
John McCall60d7b3a2010-08-24 06:29:42 +00004588 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004589
Nate Begeman2ef13e52009-08-10 23:49:36 +00004590 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004591 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4592 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004593
John McCall9ae2f072010-08-23 23:25:46 +00004594 if (Result.isInvalid()) return ExprError();
4595
4596 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004597}
4598
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004599ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4600 SourceLocation R,
4601 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004602 unsigned nexprs = Val.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00004603 Expr **exprs = Val.data();
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004604 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004605 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004606 return Owned(expr);
4607}
4608
Chandler Carruth82214a82011-02-18 23:54:50 +00004609/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00004610/// constant and the other is not a pointer. Returns true if a diagnostic is
4611/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00004612bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00004613 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004614 Expr *NullExpr = LHSExpr;
4615 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004616 Expr::NullPointerConstantKind NullKind =
4617 NullExpr->isNullPointerConstant(Context,
4618 Expr::NPC_ValueDependentIsNotNull);
4619
4620 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00004621 NullExpr = RHSExpr;
4622 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00004623 NullKind =
4624 NullExpr->isNullPointerConstant(Context,
4625 Expr::NPC_ValueDependentIsNotNull);
4626 }
4627
4628 if (NullKind == Expr::NPCK_NotNull)
4629 return false;
4630
David Blaikie50800fc2012-08-08 17:33:31 +00004631 if (NullKind == Expr::NPCK_ZeroExpression)
4632 return false;
4633
4634 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00004635 // In this case, check to make sure that we got here from a "NULL"
4636 // string in the source code.
4637 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004638 SourceLocation loc = NullExpr->getExprLoc();
4639 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004640 return false;
4641 }
4642
4643 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4644 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4645 << NonPointerExpr->getType() << DiagType
4646 << NonPointerExpr->getSourceRange();
4647 return true;
4648}
4649
Richard Trieu26f96072011-09-02 01:51:02 +00004650/// \brief Return false if the condition expression is valid, true otherwise.
4651static bool checkCondition(Sema &S, Expr *Cond) {
4652 QualType CondTy = Cond->getType();
4653
4654 // C99 6.5.15p2
4655 if (CondTy->isScalarType()) return false;
4656
4657 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikie4e4d0842012-03-11 07:00:24 +00004658 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004659 return false;
4660
4661 // Emit the proper error message.
David Blaikie4e4d0842012-03-11 07:00:24 +00004662 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu26f96072011-09-02 01:51:02 +00004663 diag::err_typecheck_cond_expect_scalar :
4664 diag::err_typecheck_cond_expect_scalar_or_vector)
4665 << CondTy;
4666 return true;
4667}
4668
4669/// \brief Return false if the two expressions can be converted to a vector,
4670/// true otherwise
4671static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4672 ExprResult &RHS,
4673 QualType CondTy) {
4674 // Both operands should be of scalar type.
4675 if (!LHS.get()->getType()->isScalarType()) {
4676 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4677 << CondTy;
4678 return true;
4679 }
4680 if (!RHS.get()->getType()->isScalarType()) {
4681 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4682 << CondTy;
4683 return true;
4684 }
4685
4686 // Implicity convert these scalars to the type of the condition.
4687 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4688 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4689 return false;
4690}
4691
4692/// \brief Handle when one or both operands are void type.
4693static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4694 ExprResult &RHS) {
4695 Expr *LHSExpr = LHS.get();
4696 Expr *RHSExpr = RHS.get();
4697
4698 if (!LHSExpr->getType()->isVoidType())
4699 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4700 << RHSExpr->getSourceRange();
4701 if (!RHSExpr->getType()->isVoidType())
4702 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4703 << LHSExpr->getSourceRange();
4704 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4705 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4706 return S.Context.VoidTy;
4707}
4708
4709/// \brief Return false if the NullExpr can be promoted to PointerTy,
4710/// true otherwise.
4711static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4712 QualType PointerTy) {
4713 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4714 !NullExpr.get()->isNullPointerConstant(S.Context,
4715 Expr::NPC_ValueDependentIsNull))
4716 return true;
4717
4718 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4719 return false;
4720}
4721
4722/// \brief Checks compatibility between two pointers and return the resulting
4723/// type.
4724static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4725 ExprResult &RHS,
4726 SourceLocation Loc) {
4727 QualType LHSTy = LHS.get()->getType();
4728 QualType RHSTy = RHS.get()->getType();
4729
4730 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4731 // Two identical pointers types are always compatible.
4732 return LHSTy;
4733 }
4734
4735 QualType lhptee, rhptee;
4736
4737 // Get the pointee types.
John McCall1d9b3b22011-09-09 05:25:32 +00004738 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4739 lhptee = LHSBTy->getPointeeType();
4740 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004741 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00004742 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4743 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00004744 }
4745
Eli Friedmanae916a12012-04-05 22:30:04 +00004746 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4747 // differently qualified versions of compatible types, the result type is
4748 // a pointer to an appropriately qualified version of the composite
4749 // type.
4750
4751 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4752 // clause doesn't make sense for our extensions. E.g. address space 2 should
4753 // be incompatible with address space 3: they may live on different devices or
4754 // anything.
4755 Qualifiers lhQual = lhptee.getQualifiers();
4756 Qualifiers rhQual = rhptee.getQualifiers();
4757
4758 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4759 lhQual.removeCVRQualifiers();
4760 rhQual.removeCVRQualifiers();
4761
4762 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4763 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4764
4765 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4766
4767 if (CompositeTy.isNull()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004768 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4769 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4770 << RHS.get()->getSourceRange();
4771 // In this situation, we assume void* type. No especially good
4772 // reason, but this is what gcc does, and we do have to pick
4773 // to get a consistent AST.
4774 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4775 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4776 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4777 return incompatTy;
4778 }
4779
4780 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00004781 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4782 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00004783
Eli Friedmanae916a12012-04-05 22:30:04 +00004784 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4785 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4786 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004787}
4788
4789/// \brief Return the resulting type when the operands are both block pointers.
4790static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4791 ExprResult &LHS,
4792 ExprResult &RHS,
4793 SourceLocation Loc) {
4794 QualType LHSTy = LHS.get()->getType();
4795 QualType RHSTy = RHS.get()->getType();
4796
4797 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4798 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4799 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4800 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4801 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4802 return destType;
4803 }
4804 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4805 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4806 << RHS.get()->getSourceRange();
4807 return QualType();
4808 }
4809
4810 // We have 2 block pointer types.
4811 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4812}
4813
4814/// \brief Return the resulting type when the operands are both pointers.
4815static QualType
4816checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4817 ExprResult &RHS,
4818 SourceLocation Loc) {
4819 // get the pointer types
4820 QualType LHSTy = LHS.get()->getType();
4821 QualType RHSTy = RHS.get()->getType();
4822
4823 // get the "pointed to" types
4824 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4825 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4826
4827 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4828 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4829 // Figure out necessary qualifiers (C99 6.5.15p6)
4830 QualType destPointee
4831 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4832 QualType destType = S.Context.getPointerType(destPointee);
4833 // Add qualifiers if necessary.
4834 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4835 // Promote to void*.
4836 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4837 return destType;
4838 }
4839 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4840 QualType destPointee
4841 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4842 QualType destType = S.Context.getPointerType(destPointee);
4843 // Add qualifiers if necessary.
4844 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4845 // Promote to void*.
4846 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4847 return destType;
4848 }
4849
4850 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4851}
4852
4853/// \brief Return false if the first expression is not an integer and the second
4854/// expression is not a pointer, true otherwise.
4855static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4856 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004857 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00004858 if (!PointerExpr->getType()->isPointerType() ||
4859 !Int.get()->getType()->isIntegerType())
4860 return false;
4861
Richard Trieuccd891a2011-09-09 01:45:06 +00004862 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4863 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00004864
4865 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4866 << Expr1->getType() << Expr2->getType()
4867 << Expr1->getSourceRange() << Expr2->getSourceRange();
4868 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4869 CK_IntegralToPointer);
4870 return true;
4871}
4872
Richard Trieu33fc7572011-09-06 20:06:39 +00004873/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4874/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004875/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004876QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4877 ExprResult &RHS, ExprValueKind &VK,
4878 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004879 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004880
Richard Trieu33fc7572011-09-06 20:06:39 +00004881 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4882 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004883 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004884
Richard Trieu33fc7572011-09-06 20:06:39 +00004885 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4886 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004887 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004888
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004889 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00004890 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004891 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004892
4893 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004894 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004895
John Wiegley429bb272011-04-08 18:41:53 +00004896 Cond = UsualUnaryConversions(Cond.take());
4897 if (Cond.isInvalid())
4898 return QualType();
4899 LHS = UsualUnaryConversions(LHS.take());
4900 if (LHS.isInvalid())
4901 return QualType();
4902 RHS = UsualUnaryConversions(RHS.take());
4903 if (RHS.isInvalid())
4904 return QualType();
4905
4906 QualType CondTy = Cond.get()->getType();
4907 QualType LHSTy = LHS.get()->getType();
4908 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004909
Reid Spencer5f016e22007-07-11 17:01:13 +00004910 // first, check the condition.
Richard Trieu26f96072011-09-02 01:51:02 +00004911 if (checkCondition(*this, Cond.get()))
4912 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004913
Chris Lattner70d67a92008-01-06 22:42:25 +00004914 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004915 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004916 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004917
Nate Begeman6155d732010-09-20 22:41:17 +00004918 // OpenCL: If the condition is a vector, and both operands are scalar,
4919 // attempt to implicity convert them to the vector type to act like the
4920 // built in select.
David Blaikie4e4d0842012-03-11 07:00:24 +00004921 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu26f96072011-09-02 01:51:02 +00004922 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begeman6155d732010-09-20 22:41:17 +00004923 return QualType();
Nate Begeman6155d732010-09-20 22:41:17 +00004924
Chris Lattner70d67a92008-01-06 22:42:25 +00004925 // If both operands have arithmetic type, do the usual arithmetic conversions
4926 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004927 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4928 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004929 if (LHS.isInvalid() || RHS.isInvalid())
4930 return QualType();
4931 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004932 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004933
Chris Lattner70d67a92008-01-06 22:42:25 +00004934 // If both operands are the same structure or union type, the result is that
4935 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004936 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4937 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004938 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004939 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004940 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004941 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004942 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004943 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004944
Chris Lattner70d67a92008-01-06 22:42:25 +00004945 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004946 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004947 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00004948 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00004949 }
Richard Trieu26f96072011-09-02 01:51:02 +00004950
Steve Naroffb6d54e52008-01-08 01:11:38 +00004951 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4952 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00004953 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4954 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004955
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004956 // All objective-c pointer type analysis is done here.
4957 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4958 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004959 if (LHS.isInvalid() || RHS.isInvalid())
4960 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004961 if (!compositeType.isNull())
4962 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004963
4964
Steve Naroff7154a772009-07-01 14:36:47 +00004965 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00004966 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4967 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4968 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004969
Steve Naroff7154a772009-07-01 14:36:47 +00004970 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00004971 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4972 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4973 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004974
John McCall404cd162010-11-13 01:35:44 +00004975 // GCC compatibility: soften pointer/integer mismatch. Note that
4976 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00004977 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4978 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00004979 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00004980 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4981 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00004982 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004983
Chandler Carruth82214a82011-02-18 23:54:50 +00004984 // Emit a better diagnostic if one of the expressions is a null pointer
4985 // constant and the other is not a pointer type. In this case, the user most
4986 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004987 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004988 return QualType();
4989
Chris Lattner70d67a92008-01-06 22:42:25 +00004990 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004991 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004992 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4993 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004994 return QualType();
4995}
4996
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004997/// FindCompositeObjCPointerType - Helper method to find composite type of
4998/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004999QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00005000 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00005001 QualType LHSTy = LHS.get()->getType();
5002 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005003
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005004 // Handle things like Class and struct objc_class*. Here we case the result
5005 // to the pseudo-builtin, because that will be implicitly cast back to the
5006 // redefinition type if an attempt is made to access its fields.
5007 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005008 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005009 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005010 return LHSTy;
5011 }
5012 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005013 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005014 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005015 return RHSTy;
5016 }
5017 // And the same for struct objc_object* / id
5018 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005019 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005020 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005021 return LHSTy;
5022 }
5023 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005024 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall1d9b3b22011-09-09 05:25:32 +00005025 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005026 return RHSTy;
5027 }
5028 // And the same for struct objc_selector* / SEL
5029 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005030 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005031 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005032 return LHSTy;
5033 }
5034 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005035 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005036 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005037 return RHSTy;
5038 }
5039 // Check constraints for Objective-C object pointers types.
5040 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005041
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005042 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5043 // Two identical object pointer types are always compatible.
5044 return LHSTy;
5045 }
John McCall1d9b3b22011-09-09 05:25:32 +00005046 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5047 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005048 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005049
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005050 // If both operands are interfaces and either operand can be
5051 // assigned to the other, use that type as the composite
5052 // type. This allows
5053 // xxx ? (A*) a : (B*) b
5054 // where B is a subclass of A.
5055 //
5056 // Additionally, as for assignment, if either type is 'id'
5057 // allow silent coercion. Finally, if the types are
5058 // incompatible then make sure to use 'id' as the composite
5059 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005060
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005061 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5062 // It could return the composite type.
5063 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5064 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5065 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5066 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5067 } else if ((LHSTy->isObjCQualifiedIdType() ||
5068 RHSTy->isObjCQualifiedIdType()) &&
5069 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5070 // Need to handle "id<xx>" explicitly.
5071 // GCC allows qualified id and any Objective-C type to devolve to
5072 // id. Currently localizing to here until clear this should be
5073 // part of ObjCQualifiedIdTypesAreCompatible.
5074 compositeType = Context.getObjCIdType();
5075 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5076 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005077 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005078 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5079 ;
5080 else {
5081 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5082 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005084 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00005085 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5086 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005087 return incompatTy;
5088 }
5089 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005090 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5091 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005092 return compositeType;
5093 }
5094 // Check Objective-C object pointer types and 'void *'
5095 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005096 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005097 // ARC forbids the implicit conversion of object pointers to 'void *',
5098 // so these types are not compatible.
5099 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5100 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5101 LHS = RHS = true;
5102 return QualType();
5103 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005104 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5105 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5106 QualType destPointee
5107 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5108 QualType destType = Context.getPointerType(destPointee);
5109 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005110 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005111 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005112 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005113 return destType;
5114 }
5115 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005116 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00005117 // ARC forbids the implicit conversion of object pointers to 'void *',
5118 // so these types are not compatible.
5119 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5120 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5121 LHS = RHS = true;
5122 return QualType();
5123 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005124 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5125 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5126 QualType destPointee
5127 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5128 QualType destType = Context.getPointerType(destPointee);
5129 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005130 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005131 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005132 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005133 return destType;
5134 }
5135 return QualType();
5136}
5137
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005138/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005139/// ParenRange in parentheses.
5140static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005141 const PartialDiagnostic &Note,
5142 SourceRange ParenRange) {
5143 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5144 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5145 EndLoc.isValid()) {
5146 Self.Diag(Loc, Note)
5147 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5148 << FixItHint::CreateInsertion(EndLoc, ")");
5149 } else {
5150 // We can't display the parentheses, so just show the bare note.
5151 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005152 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005153}
5154
5155static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5156 return Opc >= BO_Mul && Opc <= BO_Shr;
5157}
5158
Hans Wennborg2f072b42011-06-09 17:06:51 +00005159/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5160/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00005161/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5162/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00005163static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00005164 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005165 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5166 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005167 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00005168 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005169
5170 // Built-in binary operator.
5171 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5172 if (IsArithmeticOp(OP->getOpcode())) {
5173 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00005174 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00005175 return true;
5176 }
5177 }
5178
5179 // Overloaded operator.
5180 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5181 if (Call->getNumArgs() != 2)
5182 return false;
5183
5184 // Make sure this is really a binary operator that is safe to pass into
5185 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5186 OverloadedOperatorKind OO = Call->getOperator();
5187 if (OO < OO_Plus || OO > OO_Arrow)
5188 return false;
5189
5190 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5191 if (IsArithmeticOp(OpKind)) {
5192 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00005193 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00005194 return true;
5195 }
5196 }
5197
5198 return false;
5199}
5200
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005201static bool IsLogicOp(BinaryOperatorKind Opc) {
5202 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5203}
5204
Hans Wennborg2f072b42011-06-09 17:06:51 +00005205/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5206/// or is a logical expression such as (x==y) which has int type, but is
5207/// commonly interpreted as boolean.
5208static bool ExprLooksBoolean(Expr *E) {
5209 E = E->IgnoreParenImpCasts();
5210
5211 if (E->getType()->isBooleanType())
5212 return true;
5213 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5214 return IsLogicOp(OP->getOpcode());
5215 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5216 return OP->getOpcode() == UO_LNot;
5217
5218 return false;
5219}
5220
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005221/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5222/// and binary operator are mixed in a way that suggests the programmer assumed
5223/// the conditional operator has higher precedence, for example:
5224/// "int x = a + someBinaryCondition ? 1 : 2".
5225static void DiagnoseConditionalPrecedence(Sema &Self,
5226 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005227 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00005228 Expr *LHSExpr,
5229 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00005230 BinaryOperatorKind CondOpcode;
5231 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005232
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005233 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00005234 return;
5235 if (!ExprLooksBoolean(CondRHS))
5236 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005237
Hans Wennborg2f072b42011-06-09 17:06:51 +00005238 // The condition is an arithmetic binary expression, with a right-
5239 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005240
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005241 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00005242 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00005243 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005244
Chandler Carruthf0b60d62011-06-16 01:05:14 +00005245 SuggestParentheses(Self, OpLoc,
5246 Self.PDiag(diag::note_precedence_conditional_silence)
5247 << BinaryOperator::getOpcodeStr(CondOpcode),
5248 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00005249
5250 SuggestParentheses(Self, OpLoc,
5251 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00005252 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005253}
5254
Steve Narofff69936d2007-09-16 03:34:24 +00005255/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00005256/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00005257ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00005258 SourceLocation ColonLoc,
5259 Expr *CondExpr, Expr *LHSExpr,
5260 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00005261 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5262 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00005263 OpaqueValueExpr *opaqueValue = 0;
5264 Expr *commonExpr = 0;
5265 if (LHSExpr == 0) {
5266 commonExpr = CondExpr;
5267
5268 // We usually want to apply unary conversions *before* saving, except
5269 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00005270 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00005271 && !commonExpr->isTypeDependent()
5272 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5273 && commonExpr->isGLValue()
5274 && commonExpr->isOrdinaryOrBitFieldObject()
5275 && RHSExpr->isOrdinaryOrBitFieldObject()
5276 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005277 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5278 if (commonRes.isInvalid())
5279 return ExprError();
5280 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00005281 }
5282
5283 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5284 commonExpr->getType(),
5285 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00005286 commonExpr->getObjectKind(),
5287 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00005288 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00005289 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005290
John McCallf89e55a2010-11-18 06:31:45 +00005291 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005292 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00005293 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5294 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005295 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005296 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5297 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005298 return ExprError();
5299
Hans Wennborg9cfdae32011-06-03 18:00:36 +00005300 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5301 RHS.get());
5302
John McCall56ca35d2011-02-17 10:25:35 +00005303 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00005304 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5305 LHS.take(), ColonLoc,
5306 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005307
5308 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005309 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005310 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5311 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005312}
5313
John McCalle4be87e2011-01-31 23:13:11 +00005314// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005315// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005316// routine is it effectively iqnores the qualifiers on the top level pointee.
5317// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5318// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005319static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005320checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5321 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5322 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005323
Reid Spencer5f016e22007-07-11 17:01:13 +00005324 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005325 const Type *lhptee, *rhptee;
5326 Qualifiers lhq, rhq;
Richard Trieu1da27a12011-09-06 20:21:22 +00005327 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5328 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005329
John McCalle4be87e2011-01-31 23:13:11 +00005330 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005331
5332 // C99 6.5.16.1p1: This following citation is common to constraints
5333 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5334 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005335 Qualifiers lq;
5336
John McCallf85e1932011-06-15 23:02:42 +00005337 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5338 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5339 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5340 // Ignore lifetime for further calculation.
5341 lhq.removeObjCLifetime();
5342 rhq.removeObjCLifetime();
5343 }
5344
John McCall86c05f32011-02-01 00:10:29 +00005345 if (!lhq.compatiblyIncludes(rhq)) {
5346 // Treat address-space mismatches as fatal. TODO: address subspaces
5347 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5348 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5349
John McCallf85e1932011-06-15 23:02:42 +00005350 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005351 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00005352 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00005353 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00005354 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00005355 && (lhptee->isVoidType() || rhptee->isVoidType()))
5356 ; // keep old
5357
John McCallf85e1932011-06-15 23:02:42 +00005358 // Treat lifetime mismatches as fatal.
5359 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5360 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5361
John McCall86c05f32011-02-01 00:10:29 +00005362 // For GCC compatibility, other qualifier mismatches are treated
5363 // as still compatible in C.
5364 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5365 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005366
Mike Stumpeed9cac2009-02-19 03:04:26 +00005367 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5368 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005369 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005370 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005371 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005372 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005373
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005374 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005375 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005376 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005377 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005378
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005379 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005380 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005381 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005382
5383 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005384 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005385 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005386 }
John McCall86c05f32011-02-01 00:10:29 +00005387
Mike Stumpeed9cac2009-02-19 03:04:26 +00005388 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005389 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005390 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5391 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005392 // Check if the pointee types are compatible ignoring the sign.
5393 // We explicitly check for char so that we catch "char" vs
5394 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005395 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005396 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005397 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005398 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005399
Chris Lattner6a2b9262009-10-17 20:33:28 +00005400 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005401 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005402 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005403 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005404
John McCall86c05f32011-02-01 00:10:29 +00005405 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005406 // Types are compatible ignoring the sign. Qualifier incompatibility
5407 // takes priority over sign incompatibility because the sign
5408 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005409 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005410 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005411
John McCalle4be87e2011-01-31 23:13:11 +00005412 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005413 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005414
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005415 // If we are a multi-level pointer, it's possible that our issue is simply
5416 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5417 // the eventual target type is the same and the pointers have the same
5418 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005419 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005420 do {
John McCall86c05f32011-02-01 00:10:29 +00005421 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5422 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005423 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005424
John McCall86c05f32011-02-01 00:10:29 +00005425 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005426 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005427 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005428
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005429 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005430 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005431 }
David Blaikie4e4d0842012-03-11 07:00:24 +00005432 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005433 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5434 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005435 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005436}
5437
John McCalle4be87e2011-01-31 23:13:11 +00005438/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005439/// block pointer types are compatible or whether a block and normal pointer
5440/// are compatible. It is more restrict than comparing two function pointer
5441// types.
John McCalle4be87e2011-01-31 23:13:11 +00005442static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005443checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5444 QualType RHSType) {
5445 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5446 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005447
Steve Naroff1c7d0672008-09-04 15:10:53 +00005448 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005449
Steve Naroff1c7d0672008-09-04 15:10:53 +00005450 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00005451 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5452 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005453
John McCalle4be87e2011-01-31 23:13:11 +00005454 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00005455 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00005456 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005457
John McCalle4be87e2011-01-31 23:13:11 +00005458 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005459
Steve Naroff1c7d0672008-09-04 15:10:53 +00005460 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005461 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5462 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005463
Richard Trieu1da27a12011-09-06 20:21:22 +00005464 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005465 return Sema::IncompatibleBlockPointer;
5466
Steve Naroff1c7d0672008-09-04 15:10:53 +00005467 return ConvTy;
5468}
5469
John McCalle4be87e2011-01-31 23:13:11 +00005470/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005471/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005472static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00005473checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5474 QualType RHSType) {
5475 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5476 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00005477
Richard Trieu1da27a12011-09-06 20:21:22 +00005478 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005479 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00005480 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5481 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005482 return Sema::IncompatiblePointer;
5483 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005484 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005485 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00005486 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5487 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00005488 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00005489 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005490 }
Richard Trieu1da27a12011-09-06 20:21:22 +00005491 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5492 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005493
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00005494 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5495 // make an exception for id<P>
5496 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005497 return Sema::CompatiblePointerDiscardsQualifiers;
5498
Richard Trieu1da27a12011-09-06 20:21:22 +00005499 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00005500 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00005501 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005502 return Sema::IncompatibleObjCQualifiedId;
5503 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005504}
5505
John McCall1c23e912010-11-16 02:32:08 +00005506Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005507Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00005508 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00005509 // Fake up an opaque expression. We don't actually care about what
5510 // cast operations are required, so if CheckAssignmentConstraints
5511 // adds casts to this they'll be wasted, but fortunately that doesn't
5512 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00005513 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5514 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00005515 CastKind K = CK_Invalid;
5516
Richard Trieu1da27a12011-09-06 20:21:22 +00005517 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00005518}
5519
Mike Stumpeed9cac2009-02-19 03:04:26 +00005520/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5521/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005522/// pointers. Here are some objectionable examples that GCC considers warnings:
5523///
5524/// int a, *pint;
5525/// short *pshort;
5526/// struct foo *pfoo;
5527///
5528/// pint = pshort; // warning: assignment from incompatible pointer type
5529/// a = pint; // warning: assignment makes integer from pointer without a cast
5530/// pint = a; // warning: assignment makes pointer from integer without a cast
5531/// pint = pfoo; // warning: assignment from incompatible pointer type
5532///
5533/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005534/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005535///
John McCalldaa8e4e2010-11-15 09:13:47 +00005536/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005537Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00005538Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00005539 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00005540 QualType RHSType = RHS.get()->getType();
5541 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00005542
Chris Lattnerfc144e22008-01-04 23:18:45 +00005543 // Get canonical types. We're not formatting these types, just comparing
5544 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00005545 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5546 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005547
Eli Friedmanb001de72011-10-06 23:00:33 +00005548
John McCallb6cfa242011-01-31 22:28:28 +00005549 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00005550 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005551 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005552 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005553 }
5554
Eli Friedman860a3192012-06-16 02:19:17 +00005555 // If we have an atomic type, try a non-atomic assignment, then just add an
5556 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00005557 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00005558 Sema::AssignConvertType result =
5559 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5560 if (result != Compatible)
5561 return result;
5562 if (Kind != CK_NoOp)
5563 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5564 Kind = CK_NonAtomicToAtomic;
5565 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00005566 }
5567
Douglas Gregor9d293df2008-10-28 00:22:11 +00005568 // If the left-hand side is a reference type, then we are in a
5569 // (rare!) case where we've allowed the use of references in C,
5570 // e.g., as a parameter type in a built-in function. In this case,
5571 // just make sure that the type referenced is compatible with the
5572 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00005573 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00005574 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005575 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5576 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005577 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005578 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005579 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005580 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005581 }
John McCallb6cfa242011-01-31 22:28:28 +00005582
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005583 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5584 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005585 if (LHSType->isExtVectorType()) {
5586 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005587 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00005588 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005589 // CK_VectorSplat does T -> vector T, so first cast to the
5590 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005591 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5592 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00005593 Kind = PrepareScalarCast(RHS, elType);
Richard Trieufacef2e2011-09-06 20:30:53 +00005594 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005595 }
5596 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005597 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005598 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005599 }
Mike Stump1eb44332009-09-09 15:08:12 +00005600
John McCallb6cfa242011-01-31 22:28:28 +00005601 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00005602 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5603 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005604 // Allow assignments of an AltiVec vector type to an equivalent GCC
5605 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00005606 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005607 Kind = CK_BitCast;
5608 return Compatible;
5609 }
5610
Douglas Gregor255210e2010-08-06 10:14:59 +00005611 // If we are allowing lax vector conversions, and LHS and RHS are both
5612 // vectors, the total size only needs to be the same. This is a bitcast;
5613 // no bits are changed but the result type is different.
David Blaikie4e4d0842012-03-11 07:00:24 +00005614 if (getLangOpts().LaxVectorConversions &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005615 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005616 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005617 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005618 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005619 }
5620 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005621 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005622
John McCallb6cfa242011-01-31 22:28:28 +00005623 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00005624 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005625 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00005626 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005627 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005628 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005629
John McCallb6cfa242011-01-31 22:28:28 +00005630 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005631 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005632 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005633 if (isa<PointerType>(RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005634 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005635 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005636 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005637
John McCallb6cfa242011-01-31 22:28:28 +00005638 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00005639 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005640 Kind = CK_IntegralToPointer; // FIXME: null?
5641 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005642 }
John McCallb6cfa242011-01-31 22:28:28 +00005643
5644 // C pointers are not compatible with ObjC object pointers,
5645 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005646 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005647 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005648 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005649 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00005650 return Compatible;
5651 }
5652
5653 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005654 if (RHSType->isObjCClassType() &&
5655 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005656 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005657 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005658 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005659 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00005660
John McCallb6cfa242011-01-31 22:28:28 +00005661 Kind = CK_BitCast;
5662 return IncompatiblePointer;
5663 }
5664
5665 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00005666 if (RHSType->getAs<BlockPointerType>()) {
5667 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005668 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005669 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005670 }
Steve Naroffb4406862008-09-29 18:10:17 +00005671 }
John McCallb6cfa242011-01-31 22:28:28 +00005672
Steve Naroff1c7d0672008-09-04 15:10:53 +00005673 return Incompatible;
5674 }
5675
John McCallb6cfa242011-01-31 22:28:28 +00005676 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005677 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005678 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005679 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005680 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00005681 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00005682 }
5683
5684 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005685 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005686 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005687 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005688 }
5689
John McCallb6cfa242011-01-31 22:28:28 +00005690 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00005691 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005692 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005693 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005694 }
Steve Naroffb4406862008-09-29 18:10:17 +00005695
John McCallb6cfa242011-01-31 22:28:28 +00005696 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00005697 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005698 if (RHSPT->getPointeeType()->isVoidType()) {
5699 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005700 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005701 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005702
Chris Lattnerfc144e22008-01-04 23:18:45 +00005703 return Incompatible;
5704 }
5705
John McCallb6cfa242011-01-31 22:28:28 +00005706 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00005707 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005708 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00005709 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00005710 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005711 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00005712 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00005713 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005714 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00005715 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005716 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005717 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005718 }
5719
5720 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005721 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005722 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005723 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005724 }
5725
John McCallb6cfa242011-01-31 22:28:28 +00005726 // In general, C pointers are not compatible with ObjC object pointers,
5727 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00005728 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00005729 Kind = CK_CPointerToObjCPointerCast;
5730
John McCallb6cfa242011-01-31 22:28:28 +00005731 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00005732 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005733 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005734 }
5735
5736 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00005737 if (LHSType->isObjCClassType() &&
5738 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00005739 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00005740 return Compatible;
5741 }
5742
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005743 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005744 }
John McCallb6cfa242011-01-31 22:28:28 +00005745
5746 // T^ -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00005747 if (RHSType->isBlockPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00005748 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00005749 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005750 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005751 }
5752
Steve Naroff14108da2009-07-10 23:34:53 +00005753 return Incompatible;
5754 }
John McCallb6cfa242011-01-31 22:28:28 +00005755
5756 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005757 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005758 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005759 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005760 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005761 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005762 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005763
John McCallb6cfa242011-01-31 22:28:28 +00005764 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005765 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005766 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005767 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005768 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005769
Chris Lattnerfc144e22008-01-04 23:18:45 +00005770 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005771 }
John McCallb6cfa242011-01-31 22:28:28 +00005772
5773 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00005774 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005775 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00005776 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005777 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005778 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005779 }
Steve Naroff14108da2009-07-10 23:34:53 +00005780
John McCallb6cfa242011-01-31 22:28:28 +00005781 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00005782 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005783 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005784 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005785 }
5786
Steve Naroff14108da2009-07-10 23:34:53 +00005787 return Incompatible;
5788 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005789
John McCallb6cfa242011-01-31 22:28:28 +00005790 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00005791 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5792 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005793 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005794 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005795 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005796 }
John McCallb6cfa242011-01-31 22:28:28 +00005797
Reid Spencer5f016e22007-07-11 17:01:13 +00005798 return Incompatible;
5799}
5800
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005801/// \brief Constructs a transparent union from an expression that is
5802/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005803static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5804 ExprResult &EResult, QualType UnionType,
5805 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005806 // Build an initializer list that designates the appropriate member
5807 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005808 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005809 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005810 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005811 SourceLocation());
5812 Initializer->setType(UnionType);
5813 Initializer->setInitializedFieldInUnion(Field);
5814
5815 // Build a compound literal constructing a value of the transparent
5816 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005817 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005818 EResult = S.Owned(
5819 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5820 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005821}
5822
5823Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005824Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00005825 ExprResult &RHS) {
5826 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005827
Mike Stump1eb44332009-09-09 15:08:12 +00005828 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005829 // transparent_union GCC extension.
5830 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005831 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005832 return Incompatible;
5833
5834 // The field to initialize within the transparent union.
5835 RecordDecl *UD = UT->getDecl();
5836 FieldDecl *InitField = 0;
5837 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005838 for (RecordDecl::field_iterator it = UD->field_begin(),
5839 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005840 it != itend; ++it) {
5841 if (it->getType()->isPointerType()) {
5842 // If the transparent union contains a pointer type, we allow:
5843 // 1) void pointer
5844 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00005845 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00005846 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005847 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie581deb32012-06-06 20:45:41 +00005848 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005849 break;
5850 }
Mike Stump1eb44332009-09-09 15:08:12 +00005851
Richard Trieuf7720da2011-09-06 20:40:12 +00005852 if (RHS.get()->isNullPointerConstant(Context,
5853 Expr::NPC_ValueDependentIsNull)) {
5854 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5855 CK_NullToPointer);
David Blaikie581deb32012-06-06 20:45:41 +00005856 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005857 break;
5858 }
5859 }
5860
John McCalldaa8e4e2010-11-15 09:13:47 +00005861 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00005862 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005863 == Compatible) {
Richard Trieuf7720da2011-09-06 20:40:12 +00005864 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie581deb32012-06-06 20:45:41 +00005865 InitField = *it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005866 break;
5867 }
5868 }
5869
5870 if (!InitField)
5871 return Incompatible;
5872
Richard Trieuf7720da2011-09-06 20:40:12 +00005873 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005874 return Compatible;
5875}
5876
Chris Lattner5cf216b2008-01-04 18:04:52 +00005877Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00005878Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5879 bool Diagnose) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005880 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00005881 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005882 // C++ 5.17p3: If the left operand is not of class type, the
5883 // expression is implicitly converted (C++ 4) to the
5884 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00005885 ExprResult Res;
5886 if (Diagnose) {
5887 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5888 AA_Assigning);
5889 } else {
5890 ImplicitConversionSequence ICS =
5891 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5892 /*SuppressUserConversions=*/false,
5893 /*AllowExplicit=*/false,
5894 /*InOverloadResolution=*/false,
5895 /*CStyle=*/false,
5896 /*AllowObjCWritebackConversion=*/false);
5897 if (ICS.isFailure())
5898 return Incompatible;
5899 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5900 ICS, AA_Assigning);
5901 }
John Wiegley429bb272011-04-08 18:41:53 +00005902 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005903 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005904 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00005905 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00005906 !CheckObjCARCUnavailableWeakConversion(LHSType,
5907 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005908 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005909 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005910 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005911 }
5912
5913 // FIXME: Currently, we fall through and treat C++ classes like C
5914 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00005915 // FIXME: We also fall through for atomics; not sure what should
5916 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00005917 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005918
Steve Naroff529a4ad2007-11-27 17:58:44 +00005919 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5920 // a null pointer constant.
Richard Trieuf7720da2011-09-06 20:40:12 +00005921 if ((LHSType->isPointerType() ||
5922 LHSType->isObjCObjectPointerType() ||
5923 LHSType->isBlockPointerType())
5924 && RHS.get()->isNullPointerConstant(Context,
5925 Expr::NPC_ValueDependentIsNull)) {
5926 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005927 return Compatible;
5928 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005929
Chris Lattner943140e2007-10-16 02:55:40 +00005930 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005931 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005932 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005933 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005934 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005935 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00005936 if (!LHSType->isReferenceType()) {
5937 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5938 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00005939 return Incompatible;
5940 }
Steve Narofff1120de2007-08-24 22:33:52 +00005941
John McCalldaa8e4e2010-11-15 09:13:47 +00005942 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005943 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00005944 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005945
Steve Narofff1120de2007-08-24 22:33:52 +00005946 // C99 6.5.16.1p2: The value of the right operand is converted to the
5947 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005948 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5949 // so that we can use references in built-in functions even in C.
5950 // The getNonReferenceType() call makes sure that the resulting expression
5951 // does not have reference type.
Richard Trieuf7720da2011-09-06 20:40:12 +00005952 if (result != Incompatible && RHS.get()->getType() != LHSType)
5953 RHS = ImpCastExprToType(RHS.take(),
5954 LHSType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005955 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005956}
5957
Richard Trieuf7720da2011-09-06 20:40:12 +00005958QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5959 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005960 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00005961 << LHS.get()->getType() << RHS.get()->getType()
5962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005963 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005964}
5965
Richard Trieu08062aa2011-09-06 21:01:04 +00005966QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00005967 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00005968 if (!IsCompAssign) {
5969 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5970 if (LHS.isInvalid())
5971 return QualType();
5972 }
5973 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5974 if (RHS.isInvalid())
5975 return QualType();
5976
Mike Stumpeed9cac2009-02-19 03:04:26 +00005977 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005978 // For example, "const float" and "float" are equivalent.
Richard Trieu08062aa2011-09-06 21:01:04 +00005979 QualType LHSType =
5980 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5981 QualType RHSType =
5982 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005983
Nate Begemanbe2341d2008-07-14 18:02:46 +00005984 // If the vector types are identical, return.
Richard Trieu08062aa2011-09-06 21:01:04 +00005985 if (LHSType == RHSType)
5986 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005987
Douglas Gregor255210e2010-08-06 10:14:59 +00005988 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu08062aa2011-09-06 21:01:04 +00005989 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5990 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5991 if (LHSType->isExtVectorType()) {
5992 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5993 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005994 }
5995
Richard Trieuccd891a2011-09-09 01:45:06 +00005996 if (!IsCompAssign)
Richard Trieu08062aa2011-09-06 21:01:04 +00005997 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5998 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00005999 }
6000
David Blaikie4e4d0842012-03-11 07:00:24 +00006001 if (getLangOpts().LaxVectorConversions &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006002 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006003 // If we are allowing lax vector conversions, and LHS and RHS are both
6004 // vectors, the total size only needs to be the same. This is a
6005 // bitcast; no bits are changed but the result type is different.
6006 // FIXME: Should we really be allowing this?
Richard Trieu08062aa2011-09-06 21:01:04 +00006007 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6008 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006009 }
6010
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006011 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6012 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6013 bool swapped = false;
Richard Trieuccd891a2011-09-09 01:45:06 +00006014 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006015 swapped = true;
Richard Trieu08062aa2011-09-06 21:01:04 +00006016 std::swap(RHS, LHS);
6017 std::swap(RHSType, LHSType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006018 }
Mike Stump1eb44332009-09-09 15:08:12 +00006019
Nate Begemandde25982009-06-28 19:12:57 +00006020 // Handle the case of an ext vector and scalar.
Richard Trieu08062aa2011-09-06 21:01:04 +00006021 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006022 QualType EltTy = LV->getElementType();
Richard Trieu08062aa2011-09-06 21:01:04 +00006023 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6024 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006025 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006026 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006027 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006028 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6029 if (swapped) std::swap(RHS, LHS);
6030 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006031 }
6032 }
Richard Trieu08062aa2011-09-06 21:01:04 +00006033 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6034 RHSType->isRealFloatingType()) {
6035 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006036 if (order > 0)
Richard Trieu08062aa2011-09-06 21:01:04 +00006037 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006038 if (order >= 0) {
Richard Trieu08062aa2011-09-06 21:01:04 +00006039 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6040 if (swapped) std::swap(RHS, LHS);
6041 return LHSType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006042 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006043 }
6044 }
Mike Stump1eb44332009-09-09 15:08:12 +00006045
Nate Begemandde25982009-06-28 19:12:57 +00006046 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu08062aa2011-09-06 21:01:04 +00006047 if (swapped) std::swap(RHS, LHS);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006048 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu08062aa2011-09-06 21:01:04 +00006049 << LHS.get()->getType() << RHS.get()->getType()
6050 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006051 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006052}
6053
Richard Trieu481037f2011-09-16 00:53:10 +00006054// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6055// expression. These are mainly cases where the null pointer is used as an
6056// integer instead of a pointer.
6057static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6058 SourceLocation Loc, bool IsCompare) {
6059 // The canonical way to check for a GNU null is with isNullPointerConstant,
6060 // but we use a bit of a hack here for speed; this is a relatively
6061 // hot path, and isNullPointerConstant is slow.
6062 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6063 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6064
6065 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6066
6067 // Avoid analyzing cases where the result will either be invalid (and
6068 // diagnosed as such) or entirely valid and not something to warn about.
6069 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6070 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6071 return;
6072
6073 // Comparison operations would not make sense with a null pointer no matter
6074 // what the other expression is.
6075 if (!IsCompare) {
6076 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6077 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6078 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6079 return;
6080 }
6081
6082 // The rest of the operations only make sense with a null pointer
6083 // if the other expression is a pointer.
6084 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6085 NonNullType->canDecayToPointerType())
6086 return;
6087
6088 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6089 << LHSNull /* LHS is NULL */ << NonNullType
6090 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6091}
6092
Richard Trieu08062aa2011-09-06 21:01:04 +00006093QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006094 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006095 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00006096 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6097
Richard Trieu08062aa2011-09-06 21:01:04 +00006098 if (LHS.get()->getType()->isVectorType() ||
6099 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006100 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006101
Richard Trieuccd891a2011-09-09 01:45:06 +00006102 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006103 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006104 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006105
David Chisnall7a7ee302012-01-16 17:27:18 +00006106
Eli Friedman860a3192012-06-16 02:19:17 +00006107 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006108 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006109
Chris Lattner7ef655a2010-01-12 21:23:57 +00006110 // Check for division by zero.
Richard Trieuccd891a2011-09-09 01:45:06 +00006111 if (IsDiv &&
Richard Trieu08062aa2011-09-06 21:01:04 +00006112 RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006113 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006114 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6115 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006116
Chris Lattner7ef655a2010-01-12 21:23:57 +00006117 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006118}
6119
Chris Lattner7ef655a2010-01-12 21:23:57 +00006120QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00006121 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006122 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6123
Richard Trieu08062aa2011-09-06 21:01:04 +00006124 if (LHS.get()->getType()->isVectorType() ||
6125 RHS.get()->getType()->isVectorType()) {
6126 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6127 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00006128 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006129 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00006130 }
Steve Naroff90045e82007-07-13 23:32:42 +00006131
Richard Trieuccd891a2011-09-09 01:45:06 +00006132 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00006133 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006134 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006135
Eli Friedman860a3192012-06-16 02:19:17 +00006136 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00006137 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006138
Chris Lattner7ef655a2010-01-12 21:23:57 +00006139 // Check for remainder by zero.
Richard Trieu08062aa2011-09-06 21:01:04 +00006140 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00006141 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu08062aa2011-09-06 21:01:04 +00006142 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6143 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006144
Chris Lattner7ef655a2010-01-12 21:23:57 +00006145 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006146}
6147
Chandler Carruth13b21be2011-06-27 08:02:19 +00006148/// \brief Diagnose invalid arithmetic on two void pointers.
6149static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006150 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006151 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006152 ? diag::err_typecheck_pointer_arith_void_type
6153 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00006154 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6155 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006156}
6157
6158/// \brief Diagnose invalid arithmetic on a void pointer.
6159static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6160 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006161 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006162 ? diag::err_typecheck_pointer_arith_void_type
6163 : diag::ext_gnu_void_ptr)
6164 << 0 /* one pointer */ << Pointer->getSourceRange();
6165}
6166
6167/// \brief Diagnose invalid arithmetic on two function pointers.
6168static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6169 Expr *LHS, Expr *RHS) {
6170 assert(LHS->getType()->isAnyPointerType());
6171 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006172 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006173 ? diag::err_typecheck_pointer_arith_function_type
6174 : diag::ext_gnu_ptr_func_arith)
6175 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6176 // We only show the second type if it differs from the first.
6177 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6178 RHS->getType())
6179 << RHS->getType()->getPointeeType()
6180 << LHS->getSourceRange() << RHS->getSourceRange();
6181}
6182
6183/// \brief Diagnose invalid arithmetic on a function pointer.
6184static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6185 Expr *Pointer) {
6186 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00006187 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00006188 ? diag::err_typecheck_pointer_arith_function_type
6189 : diag::ext_gnu_ptr_func_arith)
6190 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6191 << 0 /* one pointer, so only one type */
6192 << Pointer->getSourceRange();
6193}
6194
Richard Trieud9f19342011-09-12 18:08:02 +00006195/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00006196///
6197/// \returns True if pointer has incomplete type
6198static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6199 Expr *Operand) {
John McCall1503f0d2012-07-31 05:14:30 +00006200 assert(Operand->getType()->isAnyPointerType() &&
6201 !Operand->getType()->isDependentType());
6202 QualType PointeeTy = Operand->getType()->getPointeeType();
6203 return S.RequireCompleteType(Loc, PointeeTy,
6204 diag::err_typecheck_arithmetic_incomplete_type,
6205 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00006206}
6207
Chandler Carruth13b21be2011-06-27 08:02:19 +00006208/// \brief Check the validity of an arithmetic pointer operand.
6209///
6210/// If the operand has pointer type, this code will check for pointer types
6211/// which are invalid in arithmetic operations. These will be diagnosed
6212/// appropriately, including whether or not the use is supported as an
6213/// extension.
6214///
6215/// \returns True when the operand is valid to use (even if as an extension).
6216static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6217 Expr *Operand) {
6218 if (!Operand->getType()->isAnyPointerType()) return true;
6219
6220 QualType PointeeTy = Operand->getType()->getPointeeType();
6221 if (PointeeTy->isVoidType()) {
6222 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006223 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006224 }
6225 if (PointeeTy->isFunctionType()) {
6226 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00006227 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006228 }
6229
Richard Trieu097ecd22011-09-02 02:15:37 +00006230 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006231
6232 return true;
6233}
6234
6235/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6236/// operands.
6237///
6238/// This routine will diagnose any invalid arithmetic on pointer operands much
6239/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6240/// for emitting a single diagnostic even for operations where both LHS and RHS
6241/// are (potentially problematic) pointers.
6242///
6243/// \returns True when the operand is valid to use (even if as an extension).
6244static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006245 Expr *LHSExpr, Expr *RHSExpr) {
6246 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6247 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006248 if (!isLHSPointer && !isRHSPointer) return true;
6249
6250 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00006251 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6252 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00006253
6254 // Check for arithmetic on pointers to incomplete types.
6255 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6256 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6257 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006258 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6259 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6260 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006261
David Blaikie4e4d0842012-03-11 07:00:24 +00006262 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006263 }
6264
6265 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6266 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6267 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00006268 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6269 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6270 RHSExpr);
6271 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00006272
David Blaikie4e4d0842012-03-11 07:00:24 +00006273 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00006274 }
6275
John McCall1503f0d2012-07-31 05:14:30 +00006276 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6277 return false;
6278 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6279 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00006280
Chandler Carruth13b21be2011-06-27 08:02:19 +00006281 return true;
6282}
6283
Nico Weber1cb2d742012-03-02 22:01:22 +00006284/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6285/// literal.
6286static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6287 Expr *LHSExpr, Expr *RHSExpr) {
6288 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6289 Expr* IndexExpr = RHSExpr;
6290 if (!StrExpr) {
6291 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6292 IndexExpr = LHSExpr;
6293 }
6294
6295 bool IsStringPlusInt = StrExpr &&
6296 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6297 if (!IsStringPlusInt)
6298 return;
6299
6300 llvm::APSInt index;
6301 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6302 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6303 if (index.isNonNegative() &&
6304 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6305 index.isUnsigned()))
6306 return;
6307 }
6308
6309 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6310 Self.Diag(OpLoc, diag::warn_string_plus_int)
6311 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6312
6313 // Only print a fixit for "str" + int, not for int + "str".
6314 if (IndexExpr == RHSExpr) {
6315 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6316 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6317 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6318 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6319 << FixItHint::CreateInsertion(EndLoc, "]");
6320 } else
6321 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6322}
6323
Richard Trieud9f19342011-09-12 18:08:02 +00006324/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00006325static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006326 Expr *LHSExpr, Expr *RHSExpr) {
6327 assert(LHSExpr->getType()->isAnyPointerType());
6328 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00006329 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00006330 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6331 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00006332}
6333
Chris Lattner7ef655a2010-01-12 21:23:57 +00006334QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00006335 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6336 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006337 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6338
Richard Trieudef75842011-09-06 21:13:51 +00006339 if (LHS.get()->getType()->isVectorType() ||
6340 RHS.get()->getType()->isVectorType()) {
6341 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006342 if (CompLHSTy) *CompLHSTy = compType;
6343 return compType;
6344 }
Steve Naroff49b45262007-07-13 16:58:59 +00006345
Richard Trieudef75842011-09-06 21:13:51 +00006346 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6347 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006348 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006349
Nico Weber1cb2d742012-03-02 22:01:22 +00006350 // Diagnose "string literal" '+' int.
6351 if (Opc == BO_Add)
6352 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6353
Reid Spencer5f016e22007-07-11 17:01:13 +00006354 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006355 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006356 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006357 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006358 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006359
John McCall1503f0d2012-07-31 05:14:30 +00006360 // Type-checking. Ultimately the pointer's going to be in PExp;
6361 // note that we bias towards the LHS being the pointer.
6362 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006363
John McCall1503f0d2012-07-31 05:14:30 +00006364 bool isObjCPointer;
6365 if (PExp->getType()->isPointerType()) {
6366 isObjCPointer = false;
6367 } else if (PExp->getType()->isObjCObjectPointerType()) {
6368 isObjCPointer = true;
6369 } else {
6370 std::swap(PExp, IExp);
6371 if (PExp->getType()->isPointerType()) {
6372 isObjCPointer = false;
6373 } else if (PExp->getType()->isObjCObjectPointerType()) {
6374 isObjCPointer = true;
6375 } else {
6376 return InvalidOperands(Loc, LHS, RHS);
6377 }
6378 }
6379 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00006380
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006381 if (!IExp->getType()->isIntegerType())
6382 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006383
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006384 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6385 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006386
John McCall1503f0d2012-07-31 05:14:30 +00006387 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006388 return QualType();
6389
6390 // Check array bounds for pointer arithemtic
6391 CheckArrayAccess(PExp, IExp);
6392
6393 if (CompLHSTy) {
6394 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6395 if (LHSTy.isNull()) {
6396 LHSTy = LHS.get()->getType();
6397 if (LHSTy->isPromotableIntegerType())
6398 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00006399 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006400 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00006401 }
6402
Richard Trieu6eef9fb2011-09-12 18:37:54 +00006403 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006404}
6405
Chris Lattnereca7be62008-04-07 05:30:13 +00006406// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00006407QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006408 SourceLocation Loc,
6409 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00006410 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6411
Richard Trieudef75842011-09-06 21:13:51 +00006412 if (LHS.get()->getType()->isVectorType() ||
6413 RHS.get()->getType()->isVectorType()) {
6414 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006415 if (CompLHSTy) *CompLHSTy = compType;
6416 return compType;
6417 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006418
Richard Trieudef75842011-09-06 21:13:51 +00006419 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6420 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006421 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006422
Chris Lattner6e4ab612007-12-09 21:53:25 +00006423 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006424
Chris Lattner6e4ab612007-12-09 21:53:25 +00006425 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00006426 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006427 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006428 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006429 }
Mike Stump1eb44332009-09-09 15:08:12 +00006430
Chris Lattner6e4ab612007-12-09 21:53:25 +00006431 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00006432 if (LHS.get()->getType()->isAnyPointerType()) {
6433 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006434
Chris Lattnerb5f15622009-04-24 23:50:08 +00006435 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00006436 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6437 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00006438 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006439
Chris Lattner6e4ab612007-12-09 21:53:25 +00006440 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00006441 if (RHS.get()->getType()->isIntegerType()) {
6442 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006443 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006444
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006445 // Check array bounds for pointer arithemtic
Richard Smith25b009a2011-12-16 19:31:14 +00006446 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6447 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006448
Richard Trieudef75842011-09-06 21:13:51 +00006449 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6450 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00006451 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006452
Chris Lattner6e4ab612007-12-09 21:53:25 +00006453 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00006454 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00006455 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00006456 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006457
David Blaikie4e4d0842012-03-11 07:00:24 +00006458 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00006459 // Pointee types must be the same: C++ [expr.add]
6460 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00006461 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006462 }
6463 } else {
6464 // Pointee types must be compatible C99 6.5.6p3
6465 if (!Context.typesAreCompatible(
6466 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6467 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00006468 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00006469 return QualType();
6470 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006471 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006472
Chandler Carruth13b21be2011-06-27 08:02:19 +00006473 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00006474 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00006475 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006476
Richard Trieudef75842011-09-06 21:13:51 +00006477 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006478 return Context.getPointerDiffType();
6479 }
6480 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006481
Richard Trieudef75842011-09-06 21:13:51 +00006482 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00006483}
6484
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006485static bool isScopedEnumerationType(QualType T) {
6486 if (const EnumType *ET = dyn_cast<EnumType>(T))
6487 return ET->getDecl()->isScoped();
6488 return false;
6489}
6490
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006491static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00006492 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006493 QualType LHSType) {
Chandler Carruth21206d52011-02-23 23:34:11 +00006494 llvm::APSInt Right;
6495 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006496 if (RHS.get()->isValueDependent() ||
6497 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006498 return;
6499
6500 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006501 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006502 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006503 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006504 return;
6505 }
6506 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006507 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006508 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006509 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006510 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006511 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006512 return;
6513 }
6514 if (Opc != BO_Shl)
6515 return;
6516
6517 // When left shifting an ICE which is signed, we can check for overflow which
6518 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6519 // integers have defined behavior modulo one more than the maximum value
6520 // representable in the result type, so never warn for those.
6521 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006522 if (LHS.get()->isValueDependent() ||
6523 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6524 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00006525 return;
6526 llvm::APInt ResultBits =
6527 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6528 if (LeftBits.uge(ResultBits))
6529 return;
6530 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6531 Result = Result.shl(Right);
6532
Ted Kremenekfa821382011-06-15 00:54:52 +00006533 // Print the bit representation of the signed integer as an unsigned
6534 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006535 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00006536 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6537
Chandler Carruth21206d52011-02-23 23:34:11 +00006538 // If we are only missing a sign bit, this is less likely to result in actual
6539 // bugs -- if the result is cast back to an unsigned type, it will have the
6540 // expected value. Thus we place this behind a different warning that can be
6541 // turned off separately if needed.
6542 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006543 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006544 << HexResult.str() << LHSType
6545 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006546 return;
6547 }
6548
6549 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006550 << HexResult.str() << Result.getMinSignedBits() << LHSType
6551 << Left.getBitWidth() << LHS.get()->getSourceRange()
6552 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006553}
6554
Chris Lattnereca7be62008-04-07 05:30:13 +00006555// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006556QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006557 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006558 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00006559 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6560
Chris Lattnerca5eede2007-12-12 05:47:28 +00006561 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006562 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6563 !RHS.get()->getType()->hasIntegerRepresentation())
6564 return InvalidOperands(Loc, LHS, RHS);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006565
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006566 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6567 // hasIntegerRepresentation() above instead of this.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006568 if (isScopedEnumerationType(LHS.get()->getType()) ||
6569 isScopedEnumerationType(RHS.get()->getType())) {
6570 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006571 }
6572
Nate Begeman2207d792009-10-25 02:26:48 +00006573 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006574 if (LHS.get()->getType()->isVectorType() ||
6575 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006576 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006577
Chris Lattnerca5eede2007-12-12 05:47:28 +00006578 // Shifts don't perform usual arithmetic conversions, they just do integer
6579 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006580
John McCall1bc80af2010-12-16 19:28:59 +00006581 // For the LHS, do usual unary conversions, but then reset them away
6582 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006583 ExprResult OldLHS = LHS;
6584 LHS = UsualUnaryConversions(LHS.take());
6585 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006586 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006587 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00006588 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00006589
6590 // The RHS is simpler.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006591 RHS = UsualUnaryConversions(RHS.take());
6592 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006593 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006594
Ryan Flynnd0439682009-08-07 16:20:20 +00006595 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006596 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00006597
Chris Lattnerca5eede2007-12-12 05:47:28 +00006598 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00006599 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006600}
6601
Chandler Carruth99919472010-07-10 12:30:03 +00006602static bool IsWithinTemplateSpecialization(Decl *D) {
6603 if (DeclContext *DC = D->getDeclContext()) {
6604 if (isa<ClassTemplateSpecializationDecl>(DC))
6605 return true;
6606 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6607 return FD->isFunctionTemplateSpecialization();
6608 }
6609 return false;
6610}
6611
Richard Trieue648ac32011-09-02 03:48:46 +00006612/// If two different enums are compared, raise a warning.
Richard Trieuba261492011-09-06 21:27:33 +00006613static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6614 ExprResult &RHS) {
6615 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6616 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00006617
6618 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6619 if (!LHSEnumType)
6620 return;
6621 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6622 if (!RHSEnumType)
6623 return;
6624
6625 // Ignore anonymous enums.
6626 if (!LHSEnumType->getDecl()->getIdentifier())
6627 return;
6628 if (!RHSEnumType->getDecl()->getIdentifier())
6629 return;
6630
6631 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6632 return;
6633
6634 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6635 << LHSStrippedType << RHSStrippedType
Richard Trieuba261492011-09-06 21:27:33 +00006636 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00006637}
6638
Richard Trieu7be1be02011-09-02 02:55:45 +00006639/// \brief Diagnose bad pointer comparisons.
6640static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006641 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006642 bool IsError) {
6643 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00006644 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00006645 << LHS.get()->getType() << RHS.get()->getType()
6646 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006647}
6648
6649/// \brief Returns false if the pointers are converted to a composite type,
6650/// true otherwise.
6651static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006652 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00006653 // C++ [expr.rel]p2:
6654 // [...] Pointer conversions (4.10) and qualification
6655 // conversions (4.4) are performed on pointer operands (or on
6656 // a pointer operand and a null pointer constant) to bring
6657 // them to their composite pointer type. [...]
6658 //
6659 // C++ [expr.eq]p1 uses the same notion for (in)equality
6660 // comparisons of pointers.
6661
6662 // C++ [expr.eq]p2:
6663 // In addition, pointers to members can be compared, or a pointer to
6664 // member and a null pointer constant. Pointer to member conversions
6665 // (4.11) and qualification conversions (4.4) are performed to bring
6666 // them to a common type. If one operand is a null pointer constant,
6667 // the common type is the type of the other operand. Otherwise, the
6668 // common type is a pointer to member type similar (4.4) to the type
6669 // of one of the operands, with a cv-qualification signature (4.4)
6670 // that is the union of the cv-qualification signatures of the operand
6671 // types.
6672
Richard Trieuba261492011-09-06 21:27:33 +00006673 QualType LHSType = LHS.get()->getType();
6674 QualType RHSType = RHS.get()->getType();
6675 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6676 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00006677
6678 bool NonStandardCompositeType = false;
Richard Trieu43dff1b2011-09-02 21:44:27 +00006679 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00006680 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00006681 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00006682 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00006683 return true;
6684 }
6685
6686 if (NonStandardCompositeType)
6687 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00006688 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6689 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006690
Richard Trieuba261492011-09-06 21:27:33 +00006691 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6692 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00006693 return false;
6694}
6695
6696static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00006697 ExprResult &LHS,
6698 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00006699 bool IsError) {
6700 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6701 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00006702 << LHS.get()->getType() << RHS.get()->getType()
6703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00006704}
6705
Jordan Rose9f63a452012-06-08 21:14:25 +00006706static bool isObjCObjectLiteral(ExprResult &E) {
6707 switch (E.get()->getStmtClass()) {
6708 case Stmt::ObjCArrayLiteralClass:
6709 case Stmt::ObjCDictionaryLiteralClass:
6710 case Stmt::ObjCStringLiteralClass:
6711 case Stmt::ObjCBoxedExprClass:
6712 return true;
6713 default:
6714 // Note that ObjCBoolLiteral is NOT an object literal!
6715 return false;
6716 }
6717}
6718
Jordan Rose8d872ca2012-07-17 17:46:40 +00006719static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6720 // Get the LHS object's interface type.
6721 QualType Type = LHS->getType();
6722 QualType InterfaceType;
6723 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6724 InterfaceType = PTy->getPointeeType();
6725 if (const ObjCObjectType *iQFaceTy =
6726 InterfaceType->getAsObjCQualifiedInterfaceType())
6727 InterfaceType = iQFaceTy->getBaseType();
6728 } else {
6729 // If this is not actually an Objective-C object, bail out.
6730 return false;
6731 }
6732
6733 // If the RHS isn't an Objective-C object, bail out.
6734 if (!RHS->getType()->isObjCObjectPointerType())
6735 return false;
6736
6737 // Try to find the -isEqual: method.
6738 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6739 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6740 InterfaceType,
6741 /*instance=*/true);
6742 if (!Method) {
6743 if (Type->isObjCIdType()) {
6744 // For 'id', just check the global pool.
6745 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6746 /*receiverId=*/true,
6747 /*warn=*/false);
6748 } else {
6749 // Check protocols.
6750 Method = S.LookupMethodInQualifiedType(IsEqualSel,
6751 cast<ObjCObjectPointerType>(Type),
6752 /*instance=*/true);
6753 }
6754 }
6755
6756 if (!Method)
6757 return false;
6758
6759 QualType T = Method->param_begin()[0]->getType();
6760 if (!T->isObjCObjectPointerType())
6761 return false;
6762
6763 QualType R = Method->getResultType();
6764 if (!R->isScalarType())
6765 return false;
6766
6767 return true;
6768}
6769
6770static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6771 ExprResult &LHS, ExprResult &RHS,
6772 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00006773 Expr *Literal;
6774 Expr *Other;
6775 if (isObjCObjectLiteral(LHS)) {
6776 Literal = LHS.get();
6777 Other = RHS.get();
6778 } else {
6779 Literal = RHS.get();
6780 Other = LHS.get();
6781 }
6782
6783 // Don't warn on comparisons against nil.
6784 Other = Other->IgnoreParenCasts();
6785 if (Other->isNullPointerConstant(S.getASTContext(),
6786 Expr::NPC_ValueDependentIsNotNull))
6787 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00006788
Jordan Roseeec207f2012-07-17 17:46:44 +00006789 // This should be kept in sync with warn_objc_literal_comparison.
Jordan Rosed5209ae2012-07-17 17:46:48 +00006790 // LK_String should always be last, since it has its own warning flag.
Jordan Roseeec207f2012-07-17 17:46:44 +00006791 enum {
6792 LK_Array,
6793 LK_Dictionary,
6794 LK_Numeric,
6795 LK_Boxed,
6796 LK_String
6797 } LiteralKind;
6798
Jordan Rose9f63a452012-06-08 21:14:25 +00006799 switch (Literal->getStmtClass()) {
6800 case Stmt::ObjCStringLiteralClass:
6801 // "string literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006802 LiteralKind = LK_String;
Jordan Rose9f63a452012-06-08 21:14:25 +00006803 break;
6804 case Stmt::ObjCArrayLiteralClass:
6805 // "array literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006806 LiteralKind = LK_Array;
Jordan Rose9f63a452012-06-08 21:14:25 +00006807 break;
6808 case Stmt::ObjCDictionaryLiteralClass:
6809 // "dictionary literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006810 LiteralKind = LK_Dictionary;
Jordan Rose9f63a452012-06-08 21:14:25 +00006811 break;
6812 case Stmt::ObjCBoxedExprClass: {
6813 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6814 switch (Inner->getStmtClass()) {
6815 case Stmt::IntegerLiteralClass:
6816 case Stmt::FloatingLiteralClass:
6817 case Stmt::CharacterLiteralClass:
6818 case Stmt::ObjCBoolLiteralExprClass:
6819 case Stmt::CXXBoolLiteralExprClass:
6820 // "numeric literal"
Jordan Roseeec207f2012-07-17 17:46:44 +00006821 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006822 break;
6823 case Stmt::ImplicitCastExprClass: {
6824 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6825 // Boolean literals can be represented by implicit casts.
6826 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
Jordan Roseeec207f2012-07-17 17:46:44 +00006827 LiteralKind = LK_Numeric;
Jordan Rose9f63a452012-06-08 21:14:25 +00006828 break;
6829 }
6830 // FALLTHROUGH
6831 }
6832 default:
6833 // "boxed expression"
Jordan Roseeec207f2012-07-17 17:46:44 +00006834 LiteralKind = LK_Boxed;
Jordan Rose9f63a452012-06-08 21:14:25 +00006835 break;
6836 }
6837 break;
6838 }
6839 default:
6840 llvm_unreachable("Unknown Objective-C object literal kind");
6841 }
6842
Jordan Roseeec207f2012-07-17 17:46:44 +00006843 if (LiteralKind == LK_String)
6844 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6845 << Literal->getSourceRange();
6846 else
6847 S.Diag(Loc, diag::warn_objc_literal_comparison)
6848 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00006849
Jordan Rose8d872ca2012-07-17 17:46:40 +00006850 if (BinaryOperator::isEqualityOp(Opc) &&
6851 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6852 SourceLocation Start = LHS.get()->getLocStart();
6853 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6854 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00006855
Jordan Rose8d872ca2012-07-17 17:46:40 +00006856 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6857 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6858 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6859 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00006860 }
Jordan Rose9f63a452012-06-08 21:14:25 +00006861}
6862
Douglas Gregor0c6db942009-05-04 06:07:12 +00006863// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00006864QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006865 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00006866 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00006867 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6868
John McCall2de56d12010-08-25 11:45:40 +00006869 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006870
Chris Lattner02dd4b12009-12-05 05:40:13 +00006871 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00006872 if (LHS.get()->getType()->isVectorType() ||
6873 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00006874 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006875
Richard Trieuf1775fb2011-09-06 21:43:51 +00006876 QualType LHSType = LHS.get()->getType();
6877 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00006878
Richard Trieuf1775fb2011-09-06 21:43:51 +00006879 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6880 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006881
Richard Trieuf1775fb2011-09-06 21:43:51 +00006882 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth543cb652011-02-17 08:37:06 +00006883
Richard Trieuf1775fb2011-09-06 21:43:51 +00006884 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00006885 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00006886 !LHS.get()->getLocStart().isMacroID() &&
6887 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006888 // For non-floating point types, check for self-comparisons of the form
6889 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6890 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006891 //
6892 // NOTE: Don't warn about comparison expressions resulting from macro
6893 // expansion. Also don't warn about comparisons which are only self
6894 // comparisons within a template specialization. The warnings should catch
6895 // obvious cases in the definition of the template anyways. The idea is to
6896 // warn when the typed comparison operator will always evaluate to the same
6897 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006898 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006899 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006900 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006901 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006902 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006903 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006904 << (Opc == BO_EQ
6905 || Opc == BO_LE
6906 || Opc == BO_GE));
Richard Trieuf1775fb2011-09-06 21:43:51 +00006907 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregord64fdd02010-06-08 19:50:34 +00006908 !DRL->getDecl()->getType()->isReferenceType() &&
6909 !DRR->getDecl()->getType()->isReferenceType()) {
6910 // what is it always going to eval to?
6911 char always_evals_to;
6912 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006913 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006914 always_evals_to = 0; // false
6915 break;
John McCall2de56d12010-08-25 11:45:40 +00006916 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006917 always_evals_to = 1; // true
6918 break;
6919 default:
6920 // best we can say is 'a constant'
6921 always_evals_to = 2; // e.g. array1 <= array2
6922 break;
6923 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006924 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006925 << 1 // array
6926 << always_evals_to);
6927 }
6928 }
Chandler Carruth99919472010-07-10 12:30:03 +00006929 }
Mike Stump1eb44332009-09-09 15:08:12 +00006930
Chris Lattner55660a72009-03-08 19:39:53 +00006931 if (isa<CastExpr>(LHSStripped))
6932 LHSStripped = LHSStripped->IgnoreParenCasts();
6933 if (isa<CastExpr>(RHSStripped))
6934 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006935
Chris Lattner55660a72009-03-08 19:39:53 +00006936 // Warn about comparisons against a string constant (unless the other
6937 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006938 Expr *literalString = 0;
6939 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006940 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006941 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006942 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006943 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006944 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006945 } else if ((isa<StringLiteral>(RHSStripped) ||
6946 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006947 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006948 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006949 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006950 literalStringStripped = RHSStripped;
6951 }
6952
6953 if (literalString) {
6954 std::string resultComparison;
6955 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006956 case BO_LT: resultComparison = ") < 0"; break;
6957 case BO_GT: resultComparison = ") > 0"; break;
6958 case BO_LE: resultComparison = ") <= 0"; break;
6959 case BO_GE: resultComparison = ") >= 0"; break;
6960 case BO_EQ: resultComparison = ") == 0"; break;
6961 case BO_NE: resultComparison = ") != 0"; break;
David Blaikieb219cfc2011-09-23 05:06:16 +00006962 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregora86b8322009-04-06 18:45:53 +00006963 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006964
Ted Kremenek351ba912011-02-23 01:52:04 +00006965 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006966 PDiag(diag::warn_stringcompare)
6967 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006968 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006969 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006970 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006971
Douglas Gregord64fdd02010-06-08 19:50:34 +00006972 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieuf1775fb2011-09-06 21:43:51 +00006973 if (LHS.get()->getType()->isArithmeticType() &&
6974 RHS.get()->getType()->isArithmeticType()) {
6975 UsualArithmeticConversions(LHS, RHS);
6976 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006977 return QualType();
6978 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006979 else {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006980 LHS = UsualUnaryConversions(LHS.take());
6981 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006982 return QualType();
6983
Richard Trieuf1775fb2011-09-06 21:43:51 +00006984 RHS = UsualUnaryConversions(RHS.take());
6985 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006986 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006987 }
6988
Richard Trieuf1775fb2011-09-06 21:43:51 +00006989 LHSType = LHS.get()->getType();
6990 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006991
Douglas Gregor447b69e2008-11-19 03:25:36 +00006992 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006993 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006994
Richard Trieuccd891a2011-09-09 01:45:06 +00006995 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00006996 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006997 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006998 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006999 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007000 if (LHSType->hasFloatingRepresentation())
7001 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007002
Richard Trieuf1775fb2011-09-06 21:43:51 +00007003 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007004 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007005 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007006
Richard Trieuf1775fb2011-09-06 21:43:51 +00007007 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007008 Expr::NPC_ValueDependentIsNull);
Richard Trieuf1775fb2011-09-06 21:43:51 +00007009 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007010 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007011
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007012 // All of the following pointer-related warnings are GCC extensions, except
7013 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007014 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007015 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007016 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00007017 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00007018 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007019
David Blaikie4e4d0842012-03-11 07:00:24 +00007020 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007021 if (LCanPointeeTy == RCanPointeeTy)
7022 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00007023 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007024 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7025 // Valid unless comparison between non-null pointer and function pointer
7026 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007027 // In a SFINAE context, we treat this as a hard error to maintain
7028 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007029 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7030 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00007031 diagnoseFunctionPointerToVoidComparison(
Richard Trieuf1775fb2011-09-06 21:43:51 +00007032 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007033
7034 if (isSFINAEContext())
7035 return QualType();
7036
Richard Trieuf1775fb2011-09-06 21:43:51 +00007037 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007038 return ResultTy;
7039 }
7040 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007041
Richard Trieuf1775fb2011-09-06 21:43:51 +00007042 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00007043 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007044 else
7045 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00007046 }
Eli Friedman3075e762009-08-23 00:27:47 +00007047 // C99 6.5.9p2 and C99 6.5.8p2
7048 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7049 RCanPointeeTy.getUnqualifiedType())) {
7050 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00007051 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00007052 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007053 << LHSType << RHSType << LHS.get()->getSourceRange()
7054 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007055 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007056 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00007057 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7058 // Valid unless comparison between non-null pointer and function pointer
7059 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00007060 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007061 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007062 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00007063 } else {
7064 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00007065 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00007066 }
John McCall34d6f932011-03-11 04:25:25 +00007067 if (LCanPointeeTy != RCanPointeeTy) {
7068 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007069 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007070 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007071 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007072 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007073 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007074 }
Mike Stump1eb44332009-09-09 15:08:12 +00007075
David Blaikie4e4d0842012-03-11 07:00:24 +00007076 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007077 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007078 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007079 return ResultTy;
7080
Mike Stump1eb44332009-09-09 15:08:12 +00007081 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007082 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007083 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007084 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007085 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007086 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7087 RHS = ImpCastExprToType(RHS.take(), LHSType,
7088 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007089 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007090 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007091 return ResultTy;
7092 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007093 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007094 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00007095 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007096 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7097 LHS = ImpCastExprToType(LHS.take(), RHSType,
7098 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007099 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007100 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007101 return ResultTy;
7102 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007103
7104 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007105 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007106 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7107 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00007108 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00007109 else
7110 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00007111 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007112
7113 // Handle scoped enumeration types specifically, since they don't promote
7114 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00007115 if (LHS.get()->getType()->isEnumeralType() &&
7116 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7117 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007118 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007119 }
Mike Stump1eb44332009-09-09 15:08:12 +00007120
Steve Naroff1c7d0672008-09-04 15:10:53 +00007121 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00007122 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007123 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00007124 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7125 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007126
Steve Naroff1c7d0672008-09-04 15:10:53 +00007127 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007128 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007129 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007130 << LHSType << RHSType << LHS.get()->getSourceRange()
7131 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007132 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007133 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007134 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007135 }
John Wiegley429bb272011-04-08 18:41:53 +00007136
Steve Naroff59f53942008-09-28 01:11:11 +00007137 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00007138 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00007139 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7140 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007141 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00007142 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007143 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00007144 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007145 ->getPointeeType()->isVoidType())))
7146 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007147 << LHSType << RHSType << LHS.get()->getSourceRange()
7148 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007149 }
John McCall34d6f932011-03-11 04:25:25 +00007150 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007151 LHS = ImpCastExprToType(LHS.take(), RHSType,
7152 RHSType->isPointerType() ? CK_BitCast
7153 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007154 else
John McCall1d9b3b22011-09-09 05:25:32 +00007155 RHS = ImpCastExprToType(RHS.take(), LHSType,
7156 LHSType->isPointerType() ? CK_BitCast
7157 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007158 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007159 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007160
Richard Trieuf1775fb2011-09-06 21:43:51 +00007161 if (LHSType->isObjCObjectPointerType() ||
7162 RHSType->isObjCObjectPointerType()) {
7163 const PointerType *LPT = LHSType->getAs<PointerType>();
7164 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00007165 if (LPT || RPT) {
7166 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7167 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007168
Steve Naroffa8069f12008-11-17 19:49:16 +00007169 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00007170 !Context.typesAreCompatible(LHSType, RHSType)) {
7171 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007172 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00007173 }
John McCall34d6f932011-03-11 04:25:25 +00007174 if (LHSIsNull && !RHSIsNull)
John McCall1d9b3b22011-09-09 05:25:32 +00007175 LHS = ImpCastExprToType(LHS.take(), RHSType,
7176 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00007177 else
John McCall1d9b3b22011-09-09 05:25:32 +00007178 RHS = ImpCastExprToType(RHS.take(), LHSType,
7179 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007180 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007181 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007182 if (LHSType->isObjCObjectPointerType() &&
7183 RHSType->isObjCObjectPointerType()) {
7184 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7185 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00007186 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00007187 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00007188 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00007189
John McCall34d6f932011-03-11 04:25:25 +00007190 if (LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007191 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007192 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007193 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007194 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007195 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007196 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00007197 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7198 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007199 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007200 bool isError = false;
Richard Trieuf1775fb2011-09-06 21:43:51 +00007201 if ((LHSIsNull && LHSType->isIntegerType()) ||
7202 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007203 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007204 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00007205 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007206 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00007207 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007208 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7209 isError = true;
7210 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007211 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007212
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007213 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007214 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00007215 << LHSType << RHSType << LHS.get()->getSourceRange()
7216 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007217 if (isError)
7218 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007219 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007220
Richard Trieuf1775fb2011-09-06 21:43:51 +00007221 if (LHSType->isIntegerType())
7222 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00007223 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007224 else
Richard Trieuf1775fb2011-09-06 21:43:51 +00007225 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00007226 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007227 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007228 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007229
Steve Naroff39218df2008-09-04 16:56:14 +00007230 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00007231 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007232 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7233 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007234 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007235 }
Richard Trieuccd891a2011-09-09 01:45:06 +00007236 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00007237 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7238 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007239 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007240 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007241
Richard Trieuf1775fb2011-09-06 21:43:51 +00007242 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007243}
7244
Tanya Lattner4f692c22012-01-16 21:02:28 +00007245
7246// Return a signed type that is of identical size and number of elements.
7247// For floating point vectors, return an integer type of identical size
7248// and number of elements.
7249QualType Sema::GetSignedVectorType(QualType V) {
7250 const VectorType *VTy = V->getAs<VectorType>();
7251 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7252 if (TypeSize == Context.getTypeSize(Context.CharTy))
7253 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7254 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7255 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7256 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7257 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7258 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7259 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7260 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7261 "Unhandled vector element size in vector compare");
7262 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7263}
7264
Nate Begemanbe2341d2008-07-14 18:02:46 +00007265/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007266/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007267/// like a scalar comparison, a vector comparison produces a vector of integer
7268/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007269QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007270 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007271 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007272 // Check to make sure we're operating on vectors of the same type and width,
7273 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007274 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007275 if (vType.isNull())
7276 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007277
Richard Trieu9f60dee2011-09-07 01:19:57 +00007278 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007279
Anton Yartsev7870b132011-03-27 15:36:07 +00007280 // If AltiVec, the comparison results in a numeric type, i.e.
7281 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007282 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007283 return Context.getLogicalOperationType();
7284
Nate Begemanbe2341d2008-07-14 18:02:46 +00007285 // For non-floating point types, check for self-comparisons of the form
7286 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7287 // often indicate logic errors in the program.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007288 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith9c129f82011-10-28 03:31:48 +00007289 if (DeclRefExpr* DRL
7290 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7291 if (DeclRefExpr* DRR
7292 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007293 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007294 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007295 PDiag(diag::warn_comparison_always)
7296 << 0 // self-
7297 << 2 // "a constant"
7298 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007299 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007300
Nate Begemanbe2341d2008-07-14 18:02:46 +00007301 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00007302 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00007303 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00007304 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007305 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00007306
7307 // Return a signed type for the vector.
7308 return GetSignedVectorType(LHSType);
7309}
Mike Stumpeed9cac2009-02-19 03:04:26 +00007310
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00007311QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7312 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00007313 // Ensure that either both operands are of the same vector type, or
7314 // one operand is of a vector type and the other is of its element type.
7315 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7316 if (vType.isNull() || vType->isFloatingType())
7317 return InvalidOperands(Loc, LHS, RHS);
7318
7319 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007320}
7321
Reid Spencer5f016e22007-07-11 17:01:13 +00007322inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007323 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007324 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7325
Richard Trieu9f60dee2011-09-07 01:19:57 +00007326 if (LHS.get()->getType()->isVectorType() ||
7327 RHS.get()->getType()->isVectorType()) {
7328 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7329 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007330 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00007331
Richard Trieu9f60dee2011-09-07 01:19:57 +00007332 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00007333 }
Steve Naroff90045e82007-07-13 23:32:42 +00007334
Richard Trieu9f60dee2011-09-07 01:19:57 +00007335 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7336 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00007337 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00007338 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007339 return QualType();
Richard Trieu9f60dee2011-09-07 01:19:57 +00007340 LHS = LHSResult.take();
7341 RHS = RHSResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007342
Eli Friedman860a3192012-06-16 02:19:17 +00007343 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007344 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00007345 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007346}
7347
7348inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00007349 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007350
Tanya Lattner4f692c22012-01-16 21:02:28 +00007351 // Check vector operands differently.
7352 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7353 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7354
Chris Lattner90a8f272010-07-13 19:41:32 +00007355 // Diagnose cases where the user write a logical and/or but probably meant a
7356 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7357 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007358 if (LHS.get()->getType()->isIntegerType() &&
7359 !LHS.get()->getType()->isBooleanType() &&
7360 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00007361 // Don't warn in macros or template instantiations.
7362 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00007363 // If the RHS can be constant folded, and if it constant folds to something
7364 // that isn't 0 or 1 (which indicate a potential logical operation that
7365 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00007366 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00007367 llvm::APSInt Result;
7368 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikie4e4d0842012-03-11 07:00:24 +00007369 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith909c5552011-10-16 23:01:09 +00007370 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00007371 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00007372 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007373 << (Opc == BO_LAnd ? "&&" : "||");
7374 // Suggest replacing the logical operator with the bitwise version
7375 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7376 << (Opc == BO_LAnd ? "&" : "|")
7377 << FixItHint::CreateReplacement(SourceRange(
7378 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007379 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007380 Opc == BO_LAnd ? "&" : "|");
7381 if (Opc == BO_LAnd)
7382 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7383 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7384 << FixItHint::CreateRemoval(
7385 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00007386 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007387 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00007388 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00007389 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00007390 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00007391 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007392
David Blaikie4e4d0842012-03-11 07:00:24 +00007393 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieu9f60dee2011-09-07 01:19:57 +00007394 LHS = UsualUnaryConversions(LHS.take());
7395 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007396 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007397
Richard Trieu9f60dee2011-09-07 01:19:57 +00007398 RHS = UsualUnaryConversions(RHS.take());
7399 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007400 return QualType();
7401
Richard Trieu9f60dee2011-09-07 01:19:57 +00007402 if (!LHS.get()->getType()->isScalarType() ||
7403 !RHS.get()->getType()->isScalarType())
7404 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007405
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007406 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007407 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007408
John McCall75f7c0f2010-06-04 00:29:51 +00007409 // The following is safe because we only use this method for
7410 // non-overloadable operands.
7411
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007412 // C++ [expr.log.and]p1
7413 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007414 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00007415 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7416 if (LHSRes.isInvalid())
7417 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007418 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00007419
Richard Trieu9f60dee2011-09-07 01:19:57 +00007420 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7421 if (RHSRes.isInvalid())
7422 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007423 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007424
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007425 // C++ [expr.log.and]p2
7426 // C++ [expr.log.or]p2
7427 // The result is a bool.
7428 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007429}
7430
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007431/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7432/// is a read-only property; return true if so. A readonly property expression
7433/// depends on various declarations and thus must be treated specially.
7434///
Mike Stump1eb44332009-09-09 15:08:12 +00007435static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007436 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7437 if (!PropExpr) return false;
7438 if (PropExpr->isImplicitProperty()) return false;
John McCall12f78a62010-12-02 01:19:52 +00007439
John McCall3c3b7f92011-10-25 17:37:35 +00007440 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7441 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCall12f78a62010-12-02 01:19:52 +00007442 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007443 PropExpr->getBase()->getType();
7444
John McCall3c3b7f92011-10-25 17:37:35 +00007445 if (const ObjCObjectPointerType *OPT =
7446 BaseType->getAsObjCInterfacePointerType())
7447 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7448 if (S.isPropertyReadonly(PDecl, IFace))
7449 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007450 return false;
7451}
7452
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007453static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00007454 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7455 if (!ME) return false;
7456 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7457 ObjCMessageExpr *Base =
7458 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7459 if (!Base) return false;
7460 return Base->getMethodDecl() != 0;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007461}
7462
John McCall78dae242012-03-13 00:37:01 +00007463/// Is the given expression (which must be 'const') a reference to a
7464/// variable which was originally non-const, but which has become
7465/// 'const' due to being captured within a block?
7466enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7467static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7468 assert(E->isLValue() && E->getType().isConstQualified());
7469 E = E->IgnoreParens();
7470
7471 // Must be a reference to a declaration from an enclosing scope.
7472 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7473 if (!DRE) return NCCK_None;
7474 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7475
7476 // The declaration must be a variable which is not declared 'const'.
7477 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7478 if (!var) return NCCK_None;
7479 if (var->getType().isConstQualified()) return NCCK_None;
7480 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7481
7482 // Decide whether the first capture was for a block or a lambda.
7483 DeclContext *DC = S.CurContext;
7484 while (DC->getParent() != var->getDeclContext())
7485 DC = DC->getParent();
7486 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7487}
7488
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007489/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7490/// emit an error and return true. If so, return false.
7491static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00007492 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007493 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007494 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007495 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007496 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7497 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007498 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7499 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007500 if (IsLV == Expr::MLV_Valid)
7501 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007502
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007503 unsigned Diag = 0;
7504 bool NeedType = false;
7505 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00007506 case Expr::MLV_ConstQualified:
7507 Diag = diag::err_typecheck_assign_const;
7508
John McCall78dae242012-03-13 00:37:01 +00007509 // Use a specialized diagnostic when we're assigning to an object
7510 // from an enclosing function or block.
7511 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7512 if (NCCK == NCCK_Block)
7513 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7514 else
7515 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7516 break;
7517 }
7518
John McCall7acddac2011-06-17 06:42:21 +00007519 // In ARC, use some specialized diagnostics for occasions where we
7520 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00007521 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00007522 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7523 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7524 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7525
John McCall7acddac2011-06-17 06:42:21 +00007526 // Use the normal diagnostic if it's pseudo-__strong but the
7527 // user actually wrote 'const'.
7528 if (var->isARCPseudoStrong() &&
7529 (!var->getTypeSourceInfo() ||
7530 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7531 // There are two pseudo-strong cases:
7532 // - self
John McCallf85e1932011-06-15 23:02:42 +00007533 ObjCMethodDecl *method = S.getCurMethodDecl();
7534 if (method && var == method->getSelfDecl())
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00007535 Diag = method->isClassMethod()
7536 ? diag::err_typecheck_arc_assign_self_class_method
7537 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00007538
7539 // - fast enumeration variables
7540 else
John McCallf85e1932011-06-15 23:02:42 +00007541 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00007542
John McCallf85e1932011-06-15 23:02:42 +00007543 SourceRange Assign;
7544 if (Loc != OrigLoc)
7545 Assign = SourceRange(OrigLoc, OrigLoc);
7546 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7547 // We need to preserve the AST regardless, so migration tool
7548 // can do its job.
7549 return false;
7550 }
7551 }
7552 }
7553
7554 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007555 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00007556 case Expr::MLV_ArrayTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007557 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7558 NeedType = true;
7559 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007560 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007561 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7562 NeedType = true;
7563 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007564 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007565 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7566 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007567 case Expr::MLV_Valid:
7568 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007569 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007570 case Expr::MLV_MemberFunction:
7571 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007572 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7573 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007574 case Expr::MLV_IncompleteType:
7575 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007576 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007577 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007578 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007579 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7580 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007581 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007582 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00007583 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007584 case Expr::MLV_InvalidMessageExpression:
7585 Diag = diag::error_readonly_message_assignment;
7586 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007587 case Expr::MLV_SubObjCPropertySetting:
7588 Diag = diag::error_no_subobject_property_setting;
7589 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007590 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007591
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007592 SourceRange Assign;
7593 if (Loc != OrigLoc)
7594 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007595 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007596 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007597 else
Mike Stump1eb44332009-09-09 15:08:12 +00007598 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007599 return true;
7600}
7601
Nico Weber7c81b432012-07-03 02:03:06 +00007602static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7603 SourceLocation Loc,
7604 Sema &Sema) {
7605 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00007606 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7607 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7608 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7609 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00007610 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00007611 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007612
Nico Weber7c81b432012-07-03 02:03:06 +00007613 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00007614 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7615 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7616 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7617 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7618 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7619 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00007620 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00007621 }
7622}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007623
7624// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00007625QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007626 SourceLocation Loc,
7627 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00007628 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7629
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007630 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00007631 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007632 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007633
Richard Trieu268942b2011-09-07 01:33:52 +00007634 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00007635 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7636 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007637 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007638 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00007639 Expr *RHSCheck = RHS.get();
7640
Nico Weber7c81b432012-07-03 02:03:06 +00007641 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00007642
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007643 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007644 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007645 if (RHS.isInvalid())
7646 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007647 // Special case of NSObject attributes on c-style pointer types.
7648 if (ConvTy == IncompatiblePointer &&
7649 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007650 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007651 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007652 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007653 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007654
John McCallf89e55a2010-11-18 06:31:45 +00007655 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00007656 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00007657 Diag(Loc, diag::err_objc_object_assignment)
7658 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00007659
Chris Lattner2c156472008-08-21 18:04:13 +00007660 // If the RHS is a unary plus or minus, check to see if they = and + are
7661 // right next to each other. If so, the user may have typo'd "x =+ 4"
7662 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00007663 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7664 RHSCheck = ICE->getSubExpr();
7665 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007666 if ((UO->getOpcode() == UO_Plus ||
7667 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007668 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007669 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007670 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00007671 // And there is a space or other character before the subexpr of the
7672 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00007673 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00007674 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007675 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007676 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007677 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007678 }
Chris Lattner2c156472008-08-21 18:04:13 +00007679 }
John McCallf85e1932011-06-15 23:02:42 +00007680
7681 if (ConvTy == Compatible) {
7682 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieu268942b2011-09-07 01:33:52 +00007683 checkRetainCycles(LHSExpr, RHS.get());
David Blaikie4e4d0842012-03-11 07:00:24 +00007684 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieu268942b2011-09-07 01:33:52 +00007685 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00007686 }
Chris Lattner2c156472008-08-21 18:04:13 +00007687 } else {
7688 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007689 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007690 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007691
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007692 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007693 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007694 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007695
Richard Trieu268942b2011-09-07 01:33:52 +00007696 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007697
Reid Spencer5f016e22007-07-11 17:01:13 +00007698 // C99 6.5.16p3: The type of an assignment expression is the type of the
7699 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007700 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007701 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7702 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00007703 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00007704 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007705 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00007706 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007707}
7708
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007709// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00007710static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00007711 SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00007712 LHS = S.CheckPlaceholderExpr(LHS.take());
7713 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007714 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007715 return QualType();
7716
John McCallcf2e5062010-10-12 07:14:40 +00007717 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7718 // operands, but not unary promotions.
7719 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007720
John McCallf6a16482010-12-04 03:47:34 +00007721 // So we treat the LHS as a ignored value, and in C++ we allow the
7722 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007723 LHS = S.IgnoredValueConversions(LHS.take());
7724 if (LHS.isInvalid())
7725 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007726
Eli Friedmana6115062012-05-24 00:47:05 +00007727 S.DiagnoseUnusedExprResult(LHS.get());
7728
David Blaikie4e4d0842012-03-11 07:00:24 +00007729 if (!S.getLangOpts().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007730 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7731 if (RHS.isInvalid())
7732 return QualType();
7733 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007734 S.RequireCompleteType(Loc, RHS.get()->getType(),
7735 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007736 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007737
John Wiegley429bb272011-04-08 18:41:53 +00007738 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007739}
7740
Steve Naroff49b45262007-07-13 16:58:59 +00007741/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7742/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007743static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7744 ExprValueKind &VK,
7745 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007746 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007747 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007748 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007749
Chris Lattner3528d352008-11-21 07:05:48 +00007750 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00007751 // Atomic types can be used for increment / decrement where the non-atomic
7752 // versions can, so ignore the _Atomic() specifier for the purpose of
7753 // checking.
7754 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7755 ResType = ResAtomicType->getValueType();
7756
Chris Lattner3528d352008-11-21 07:05:48 +00007757 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007758
David Blaikie4e4d0842012-03-11 07:00:24 +00007759 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007760 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00007761 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00007762 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007763 return QualType();
7764 }
7765 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007766 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007767 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007768 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00007769 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007770 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007771 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007772 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00007773 } else if (ResType->isObjCObjectPointerType()) {
7774 // On modern runtimes, ObjC pointer arithmetic is forbidden.
7775 // Otherwise, we just need a complete type.
7776 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7777 checkArithmeticOnObjCPointer(S, OpLoc, Op))
7778 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00007779 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007780 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007781 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007782 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007783 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007784 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007785 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007786 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007787 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00007788 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00007789 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007790 } else {
John McCall09431682010-11-18 19:01:18 +00007791 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00007792 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007793 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007794 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007795 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007796 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007797 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007798 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007799 // In C++, a prefix increment is the same type as the operand. Otherwise
7800 // (in C or with postfix), the increment is the unqualified type of the
7801 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00007802 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00007803 VK = VK_LValue;
7804 return ResType;
7805 } else {
7806 VK = VK_RValue;
7807 return ResType.getUnqualifiedType();
7808 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007809}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007810
7811
Anders Carlsson369dee42008-02-01 07:15:58 +00007812/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007813/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007814/// where the declaration is needed for type checking. We only need to
7815/// handle cases when the expression references a function designator
7816/// or is an lvalue. Here are some examples:
7817/// - &(x) => x
7818/// - &*****f => f for f a function designator.
7819/// - &s.xx => s
7820/// - &s.zz[1].yy -> s, if zz is an array
7821/// - *(x + 1) -> x, if x is an array
7822/// - &"123"[2] -> 0
7823/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007824static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007825 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007826 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007827 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007828 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007829 // If this is an arrow operator, the address is an offset from
7830 // the base's value, so the object the base refers to is
7831 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007832 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007833 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007834 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007835 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007836 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007837 // FIXME: This code shouldn't be necessary! We should catch the implicit
7838 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007839 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7840 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7841 if (ICE->getSubExpr()->getType()->isArrayType())
7842 return getPrimaryDecl(ICE->getSubExpr());
7843 }
7844 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007845 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007846 case Stmt::UnaryOperatorClass: {
7847 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007848
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007849 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007850 case UO_Real:
7851 case UO_Imag:
7852 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007853 return getPrimaryDecl(UO->getSubExpr());
7854 default:
7855 return 0;
7856 }
7857 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007858 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007859 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007860 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007861 // If the result of an implicit cast is an l-value, we care about
7862 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007863 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007864 default:
7865 return 0;
7866 }
7867}
7868
Richard Trieu5520f232011-09-07 21:46:33 +00007869namespace {
7870 enum {
7871 AO_Bit_Field = 0,
7872 AO_Vector_Element = 1,
7873 AO_Property_Expansion = 2,
7874 AO_Register_Variable = 3,
7875 AO_No_Error = 4
7876 };
7877}
Richard Trieu09a26ad2011-09-02 00:47:55 +00007878/// \brief Diagnose invalid operand for address of operations.
7879///
7880/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00007881static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7882 Expr *E, unsigned Type) {
7883 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7884}
7885
Reid Spencer5f016e22007-07-11 17:01:13 +00007886/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007887/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007888/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007889/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007890/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007891/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007892/// we allow the '&' but retain the overloaded-function type.
John McCall3c3b7f92011-10-25 17:37:35 +00007893static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall09431682010-11-18 19:01:18 +00007894 SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00007895 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7896 if (PTy->getKind() == BuiltinType::Overload) {
7897 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7898 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7899 << OrigOp.get()->getSourceRange();
7900 return QualType();
7901 }
7902
7903 return S.Context.OverloadTy;
7904 }
7905
7906 if (PTy->getKind() == BuiltinType::UnknownAny)
7907 return S.Context.UnknownAnyTy;
7908
7909 if (PTy->getKind() == BuiltinType::BoundMember) {
7910 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7911 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00007912 return QualType();
7913 }
John McCall3c3b7f92011-10-25 17:37:35 +00007914
7915 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7916 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00007917 }
John McCall9c72c602010-08-27 09:08:28 +00007918
John McCall3c3b7f92011-10-25 17:37:35 +00007919 if (OrigOp.get()->isTypeDependent())
7920 return S.Context.DependentTy;
7921
7922 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007923
John McCall9c72c602010-08-27 09:08:28 +00007924 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00007925 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007926
David Blaikie4e4d0842012-03-11 07:00:24 +00007927 if (S.getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007928 // Implement C99-only parts of addressof rules.
7929 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007930 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007931 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7932 // (assuming the deref expression is valid).
7933 return uOp->getSubExpr()->getType();
7934 }
7935 // Technically, there should be a check for array subscript
7936 // expressions here, but the result of one is always an lvalue anyway.
7937 }
John McCall5808ce42011-02-03 08:15:49 +00007938 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007939 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5520f232011-09-07 21:46:33 +00007940 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007941
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007942 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007943 bool sfinae = S.isSFINAEContext();
7944 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7945 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007946 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007947 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007948 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007949 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007950 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007951 } else if (lval == Expr::LV_MemberFunction) {
7952 // If it's an instance method, make a member pointer.
7953 // The expression must have exactly the form &A::foo.
7954
7955 // If the underlying expression isn't a decl ref, give up.
7956 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007957 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007958 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007959 return QualType();
7960 }
7961 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7962 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7963
7964 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00007965 if (OrigOp.get() != DRE) {
John McCall09431682010-11-18 19:01:18 +00007966 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00007967 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00007968
7969 // The method was named without a qualifier.
7970 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007971 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007972 << op->getSourceRange();
7973 }
7974
John McCall09431682010-11-18 19:01:18 +00007975 return S.Context.getMemberPointerType(op->getType(),
7976 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007977 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007978 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007979 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007980 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00007981 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00007982 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00007983 AddressOfError = AO_Property_Expansion;
7984 } else {
7985 // FIXME: emit more specific diag...
7986 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7987 << op->getSourceRange();
7988 return QualType();
7989 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007990 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007991 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007992 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00007993 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00007994 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007995 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00007996 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00007997 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007998 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007999 // with the register storage-class specifier.
8000 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008001 // in C++ it is not error to take address of a register
8002 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008003 if (vd->getStorageClass() == SC_Register &&
David Blaikie4e4d0842012-03-11 07:00:24 +00008004 !S.getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00008005 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00008006 }
John McCallba135432009-11-21 08:51:07 +00008007 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008008 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008009 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008010 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008011 // Could be a pointer to member, though, if there is an explicit
8012 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008013 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008014 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008015 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008016 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008017 S.Diag(OpLoc,
8018 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008019 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008020 return QualType();
8021 }
Mike Stump1eb44332009-09-09 15:08:12 +00008022
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008023 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8024 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008025 return S.Context.getMemberPointerType(op->getType(),
8026 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008027 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008028 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00008029 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00008030 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008031 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008032
Richard Trieu5520f232011-09-07 21:46:33 +00008033 if (AddressOfError != AO_No_Error) {
8034 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8035 return QualType();
8036 }
8037
Eli Friedman441cf102009-05-16 23:27:50 +00008038 if (lval == Expr::LV_IncompleteVoidType) {
8039 // Taking the address of a void variable is technically illegal, but we
8040 // allow it in cases which are otherwise valid.
8041 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008042 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008043 }
8044
Reid Spencer5f016e22007-07-11 17:01:13 +00008045 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008046 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008047 return S.Context.getObjCObjectPointerType(op->getType());
8048 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008049}
8050
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008051/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008052static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8053 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008054 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008055 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008056
John Wiegley429bb272011-04-08 18:41:53 +00008057 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8058 if (ConvResult.isInvalid())
8059 return QualType();
8060 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008061 QualType OpTy = Op->getType();
8062 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008063
8064 if (isa<CXXReinterpretCastExpr>(Op)) {
8065 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8066 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8067 Op->getSourceRange());
8068 }
8069
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008070 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8071 // is an incomplete type or void. It would be possible to warn about
8072 // dereferencing a void pointer, but it's completely well-defined, and such a
8073 // warning is unlikely to catch any mistakes.
8074 if (const PointerType *PT = OpTy->getAs<PointerType>())
8075 Result = PT->getPointeeType();
8076 else if (const ObjCObjectPointerType *OPT =
8077 OpTy->getAs<ObjCObjectPointerType>())
8078 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008079 else {
John McCallfb8721c2011-04-10 19:13:55 +00008080 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008081 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008082 if (PR.take() != Op)
8083 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008084 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008085
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008086 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008087 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008088 << OpTy << Op->getSourceRange();
8089 return QualType();
8090 }
John McCall09431682010-11-18 19:01:18 +00008091
8092 // Dereferences are usually l-values...
8093 VK = VK_LValue;
8094
8095 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00008096 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00008097 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008098
8099 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008100}
8101
John McCall2de56d12010-08-25 11:45:40 +00008102static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008103 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008104 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008105 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008106 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008107 case tok::periodstar: Opc = BO_PtrMemD; break;
8108 case tok::arrowstar: Opc = BO_PtrMemI; break;
8109 case tok::star: Opc = BO_Mul; break;
8110 case tok::slash: Opc = BO_Div; break;
8111 case tok::percent: Opc = BO_Rem; break;
8112 case tok::plus: Opc = BO_Add; break;
8113 case tok::minus: Opc = BO_Sub; break;
8114 case tok::lessless: Opc = BO_Shl; break;
8115 case tok::greatergreater: Opc = BO_Shr; break;
8116 case tok::lessequal: Opc = BO_LE; break;
8117 case tok::less: Opc = BO_LT; break;
8118 case tok::greaterequal: Opc = BO_GE; break;
8119 case tok::greater: Opc = BO_GT; break;
8120 case tok::exclaimequal: Opc = BO_NE; break;
8121 case tok::equalequal: Opc = BO_EQ; break;
8122 case tok::amp: Opc = BO_And; break;
8123 case tok::caret: Opc = BO_Xor; break;
8124 case tok::pipe: Opc = BO_Or; break;
8125 case tok::ampamp: Opc = BO_LAnd; break;
8126 case tok::pipepipe: Opc = BO_LOr; break;
8127 case tok::equal: Opc = BO_Assign; break;
8128 case tok::starequal: Opc = BO_MulAssign; break;
8129 case tok::slashequal: Opc = BO_DivAssign; break;
8130 case tok::percentequal: Opc = BO_RemAssign; break;
8131 case tok::plusequal: Opc = BO_AddAssign; break;
8132 case tok::minusequal: Opc = BO_SubAssign; break;
8133 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8134 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8135 case tok::ampequal: Opc = BO_AndAssign; break;
8136 case tok::caretequal: Opc = BO_XorAssign; break;
8137 case tok::pipeequal: Opc = BO_OrAssign; break;
8138 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008139 }
8140 return Opc;
8141}
8142
John McCall2de56d12010-08-25 11:45:40 +00008143static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008144 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008145 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008146 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00008147 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008148 case tok::plusplus: Opc = UO_PreInc; break;
8149 case tok::minusminus: Opc = UO_PreDec; break;
8150 case tok::amp: Opc = UO_AddrOf; break;
8151 case tok::star: Opc = UO_Deref; break;
8152 case tok::plus: Opc = UO_Plus; break;
8153 case tok::minus: Opc = UO_Minus; break;
8154 case tok::tilde: Opc = UO_Not; break;
8155 case tok::exclaim: Opc = UO_LNot; break;
8156 case tok::kw___real: Opc = UO_Real; break;
8157 case tok::kw___imag: Opc = UO_Imag; break;
8158 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008159 }
8160 return Opc;
8161}
8162
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008163/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8164/// This warning is only emitted for builtin assignment operations. It is also
8165/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00008166static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008167 SourceLocation OpLoc) {
8168 if (!S.ActiveTemplateInstantiations.empty())
8169 return;
8170 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8171 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008172 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8173 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8174 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8175 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8176 if (!LHSDeclRef || !RHSDeclRef ||
8177 LHSDeclRef->getLocation().isMacroID() ||
8178 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008179 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008180 const ValueDecl *LHSDecl =
8181 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8182 const ValueDecl *RHSDecl =
8183 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8184 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008185 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008186 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008187 return;
Richard Trieu268942b2011-09-07 01:33:52 +00008188 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008189 if (RefTy->getPointeeType().isVolatileQualified())
8190 return;
8191
8192 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00008193 << LHSDeclRef->getType()
8194 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008195}
8196
Douglas Gregoreaebc752008-11-06 23:29:22 +00008197/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8198/// operator @p Opc at location @c TokLoc. This routine only supports
8199/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008200ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008201 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008202 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008203 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008204 // The syntax only allows initializer lists on the RHS of assignment,
8205 // so we don't need to worry about accepting invalid code for
8206 // non-assignment operators.
8207 // C++11 5.17p9:
8208 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8209 // of x = {} is x = T().
8210 InitializationKind Kind =
8211 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8212 InitializedEntity Entity =
8213 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8214 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +00008215 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00008216 if (Init.isInvalid())
8217 return Init;
8218 RHSExpr = Init.take();
8219 }
8220
Richard Trieu78ea78b2011-09-07 01:49:20 +00008221 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008222 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008223 // The following two variables are used for compound assignment operators
8224 QualType CompLHSTy; // Type of LHS after promotions for computation
8225 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008226 ExprValueKind VK = VK_RValue;
8227 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008228
8229 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008230 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008231 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +00008232 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +00008233 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8234 VK = LHS.get()->getValueKind();
8235 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008236 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008237 if (!ResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008238 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008239 break;
John McCall2de56d12010-08-25 11:45:40 +00008240 case BO_PtrMemD:
8241 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008242 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008243 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008244 break;
John McCall2de56d12010-08-25 11:45:40 +00008245 case BO_Mul:
8246 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008247 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008248 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008249 break;
John McCall2de56d12010-08-25 11:45:40 +00008250 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008251 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008252 break;
John McCall2de56d12010-08-25 11:45:40 +00008253 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +00008254 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008255 break;
John McCall2de56d12010-08-25 11:45:40 +00008256 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008257 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008258 break;
John McCall2de56d12010-08-25 11:45:40 +00008259 case BO_Shl:
8260 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008261 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008262 break;
John McCall2de56d12010-08-25 11:45:40 +00008263 case BO_LE:
8264 case BO_LT:
8265 case BO_GE:
8266 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008267 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008268 break;
John McCall2de56d12010-08-25 11:45:40 +00008269 case BO_EQ:
8270 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008271 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008272 break;
John McCall2de56d12010-08-25 11:45:40 +00008273 case BO_And:
8274 case BO_Xor:
8275 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008276 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008277 break;
John McCall2de56d12010-08-25 11:45:40 +00008278 case BO_LAnd:
8279 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008280 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008281 break;
John McCall2de56d12010-08-25 11:45:40 +00008282 case BO_MulAssign:
8283 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008284 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008285 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008286 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008287 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8288 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008289 break;
John McCall2de56d12010-08-25 11:45:40 +00008290 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008291 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008292 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008293 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8294 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008295 break;
John McCall2de56d12010-08-25 11:45:40 +00008296 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +00008297 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +00008298 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8299 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008300 break;
John McCall2de56d12010-08-25 11:45:40 +00008301 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008302 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8303 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8304 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008305 break;
John McCall2de56d12010-08-25 11:45:40 +00008306 case BO_ShlAssign:
8307 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008308 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008309 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008310 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8311 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008312 break;
John McCall2de56d12010-08-25 11:45:40 +00008313 case BO_AndAssign:
8314 case BO_XorAssign:
8315 case BO_OrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008316 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008317 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008318 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8319 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008320 break;
John McCall2de56d12010-08-25 11:45:40 +00008321 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +00008322 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +00008323 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +00008324 VK = RHS.get()->getValueKind();
8325 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008326 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008327 break;
8328 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008329 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008330 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008331
8332 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +00008333 CheckArrayAccess(LHS.get());
8334 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008335
Eli Friedmanab3a8522009-03-28 01:22:36 +00008336 if (CompResultTy.isNull())
Richard Trieu78ea78b2011-09-07 01:49:20 +00008337 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008338 ResultTy, VK, OK, OpLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00008339 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +00008340 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008341 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008342 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008343 }
Richard Trieu78ea78b2011-09-07 01:49:20 +00008344 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008345 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008346 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008347}
8348
Sebastian Redlaee3c932009-10-27 12:10:02 +00008349/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8350/// operators are mixed in a way that suggests that the programmer forgot that
8351/// comparison operators have higher precedence. The most typical example of
8352/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008353static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00008354 SourceLocation OpLoc, Expr *LHSExpr,
8355 Expr *RHSExpr) {
Sebastian Redlaee3c932009-10-27 12:10:02 +00008356 typedef BinaryOperator BinOp;
Richard Trieu78ea78b2011-09-07 01:49:20 +00008357 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8358 RHSopc = static_cast<BinOp::Opcode>(-1);
8359 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8360 LHSopc = BO->getOpcode();
8361 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8362 RHSopc = BO->getOpcode();
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008363
8364 // Subs are not binary operators.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008365 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008366 return;
8367
8368 // Bitwise operations are sometimes used as eager logical ops.
8369 // Don't diagnose this.
Richard Trieu78ea78b2011-09-07 01:49:20 +00008370 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8371 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008372 return;
8373
Richard Trieu78ea78b2011-09-07 01:49:20 +00008374 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8375 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008376 if (!isLeftComp && !isRightComp) return;
8377
Richard Trieu78ea78b2011-09-07 01:49:20 +00008378 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8379 OpLoc)
8380 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8381 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8382 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu70979d42011-08-10 22:41:34 +00008383 SourceRange ParensRange = isLeftComp ?
Richard Trieu78ea78b2011-09-07 01:49:20 +00008384 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8385 RHSExpr->getLocEnd())
8386 : SourceRange(LHSExpr->getLocStart(),
8387 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu70979d42011-08-10 22:41:34 +00008388
8389 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8390 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8391 SuggestParentheses(Self, OpLoc,
8392 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +00008393 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +00008394 SuggestParentheses(Self, OpLoc,
8395 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8396 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008397}
8398
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008399/// \brief It accepts a '&' expr that is inside a '|' one.
8400/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8401/// in parentheses.
8402static void
8403EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8404 BinaryOperator *Bop) {
8405 assert(Bop->getOpcode() == BO_And);
8406 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8407 << Bop->getSourceRange() << OpLoc;
8408 SuggestParentheses(Self, Bop->getOperatorLoc(),
8409 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8410 Bop->getSourceRange());
8411}
8412
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008413/// \brief It accepts a '&&' expr that is inside a '||' one.
8414/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8415/// in parentheses.
8416static void
8417EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008418 BinaryOperator *Bop) {
8419 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008420 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8421 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008422 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008423 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00008424 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008425}
8426
8427/// \brief Returns true if the given expression can be evaluated as a constant
8428/// 'true'.
8429static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8430 bool Res;
8431 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8432}
8433
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008434/// \brief Returns true if the given expression can be evaluated as a constant
8435/// 'false'.
8436static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8437 bool Res;
8438 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8439}
8440
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008441/// \brief Look for '&&' in the left hand of a '||' expr.
8442static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008443 Expr *LHSExpr, Expr *RHSExpr) {
8444 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008445 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008446 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008447 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008448 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008449 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8450 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8451 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8452 } else if (Bop->getOpcode() == BO_LOr) {
8453 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8454 // If it's "a || b && 1 || c" we didn't warn earlier for
8455 // "a || b && 1", but warn now.
8456 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8457 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8458 }
8459 }
8460 }
8461}
8462
8463/// \brief Look for '&&' in the right hand of a '||' expr.
8464static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +00008465 Expr *LHSExpr, Expr *RHSExpr) {
8466 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008467 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008468 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +00008469 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008470 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008471 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8472 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8473 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008474 }
8475 }
8476}
8477
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008478/// \brief Look for '&' in the left or right hand of a '|' expr.
8479static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8480 Expr *OrArg) {
8481 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8482 if (Bop->getOpcode() == BO_And)
8483 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8484 }
8485}
8486
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008487/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008488/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008489static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008490 SourceLocation OpLoc, Expr *LHSExpr,
8491 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008492 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008493 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +00008494 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008495
8496 // Diagnose "arg1 & arg2 | arg3"
8497 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008498 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8499 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00008500 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008501
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008502 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8503 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008504 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +00008505 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8506 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008507 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008508}
8509
Reid Spencer5f016e22007-07-11 17:01:13 +00008510// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008511ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008512 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +00008513 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +00008514 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieubefece12011-09-07 02:02:10 +00008515 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8516 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008517
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008518 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +00008519 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008520
Richard Trieubefece12011-09-07 02:02:10 +00008521 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008522}
8523
John McCall3c3b7f92011-10-25 17:37:35 +00008524/// Build an overloaded binary operator expression in the given scope.
8525static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8526 BinaryOperatorKind Opc,
8527 Expr *LHS, Expr *RHS) {
8528 // Find all of the overloaded operators visible from this
8529 // point. We perform both an operator-name lookup from the local
8530 // scope and an argument-dependent lookup based on the types of
8531 // the arguments.
8532 UnresolvedSet<16> Functions;
8533 OverloadedOperatorKind OverOp
8534 = BinaryOperator::getOverloadedOperator(Opc);
8535 if (Sc && OverOp != OO_None)
8536 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8537 RHS->getType(), Functions);
8538
8539 // Build the (potentially-overloaded, potentially-dependent)
8540 // binary operation.
8541 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8542}
8543
John McCall60d7b3a2010-08-24 06:29:42 +00008544ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008545 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +00008546 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +00008547 // We want to end up calling one of checkPseudoObjectAssignment
8548 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8549 // both expressions are overloadable or either is type-dependent),
8550 // or CreateBuiltinBinOp (in any other case). We also want to get
8551 // any placeholder types out of the way.
8552
John McCall3c3b7f92011-10-25 17:37:35 +00008553 // Handle pseudo-objects in the LHS.
8554 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8555 // Assignments with a pseudo-object l-value need special analysis.
8556 if (pty->getKind() == BuiltinType::PseudoObject &&
8557 BinaryOperator::isAssignmentOp(Opc))
8558 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8559
8560 // Don't resolve overloads if the other type is overloadable.
8561 if (pty->getKind() == BuiltinType::Overload) {
8562 // We can't actually test that if we still have a placeholder,
8563 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +00008564 // code below are valid when the LHS is an overload set. Note
8565 // that an overload set can be dependently-typed, but it never
8566 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +00008567 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8568 if (resolvedRHS.isInvalid()) return ExprError();
8569 RHSExpr = resolvedRHS.take();
8570
John McCallac516502011-10-28 01:04:34 +00008571 if (RHSExpr->isTypeDependent() ||
8572 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008573 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8574 }
8575
8576 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8577 if (LHS.isInvalid()) return ExprError();
8578 LHSExpr = LHS.take();
8579 }
8580
8581 // Handle pseudo-objects in the RHS.
8582 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8583 // An overload in the RHS can potentially be resolved by the type
8584 // being assigned to.
John McCallac516502011-10-28 01:04:34 +00008585 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8586 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8587 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8588
Eli Friedman87884912012-01-17 21:27:43 +00008589 if (LHSExpr->getType()->isOverloadableType())
8590 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8591
John McCall3c3b7f92011-10-25 17:37:35 +00008592 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +00008593 }
John McCall3c3b7f92011-10-25 17:37:35 +00008594
8595 // Don't resolve overloads if the other type is overloadable.
8596 if (pty->getKind() == BuiltinType::Overload &&
8597 LHSExpr->getType()->isOverloadableType())
8598 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8599
8600 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8601 if (!resolvedRHS.isUsable()) return ExprError();
8602 RHSExpr = resolvedRHS.take();
8603 }
8604
David Blaikie4e4d0842012-03-11 07:00:24 +00008605 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +00008606 // If either expression is type-dependent, always build an
8607 // overloaded op.
8608 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8609 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008610
John McCallac516502011-10-28 01:04:34 +00008611 // Otherwise, build an overloaded op if either expression has an
8612 // overloadable type.
8613 if (LHSExpr->getType()->isOverloadableType() ||
8614 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +00008615 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008616 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008617
Douglas Gregoreaebc752008-11-06 23:29:22 +00008618 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +00008619 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00008620}
8621
John McCall60d7b3a2010-08-24 06:29:42 +00008622ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008623 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008624 Expr *InputExpr) {
8625 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008626 ExprValueKind VK = VK_RValue;
8627 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008628 QualType resultType;
8629 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008630 case UO_PreInc:
8631 case UO_PreDec:
8632 case UO_PostInc:
8633 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008634 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008635 Opc == UO_PreInc ||
8636 Opc == UO_PostInc,
8637 Opc == UO_PreInc ||
8638 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008639 break;
John McCall2de56d12010-08-25 11:45:40 +00008640 case UO_AddrOf:
John McCall3c3b7f92011-10-25 17:37:35 +00008641 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008642 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008643 case UO_Deref: {
John Wiegley429bb272011-04-08 18:41:53 +00008644 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8645 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008646 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008647 }
John McCall2de56d12010-08-25 11:45:40 +00008648 case UO_Plus:
8649 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008650 Input = UsualUnaryConversions(Input.take());
8651 if (Input.isInvalid()) return ExprError();
8652 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008653 if (resultType->isDependentType())
8654 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008655 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8656 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008657 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008658 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregor74253732008-11-19 15:42:04 +00008659 resultType->isEnumeralType())
8660 break;
David Blaikie4e4d0842012-03-11 07:00:24 +00008661 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008662 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008663 resultType->isPointerType())
8664 break;
8665
Sebastian Redl0eb23302009-01-19 00:08:26 +00008666 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008667 << resultType << Input.get()->getSourceRange());
8668
John McCall2de56d12010-08-25 11:45:40 +00008669 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008670 Input = UsualUnaryConversions(Input.take());
8671 if (Input.isInvalid()) return ExprError();
8672 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008673 if (resultType->isDependentType())
8674 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008675 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8676 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8677 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008678 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008679 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008680 else if (resultType->hasIntegerRepresentation())
8681 break;
John McCall3c3b7f92011-10-25 17:37:35 +00008682 else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008684 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008685 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008686 break;
John Wiegley429bb272011-04-08 18:41:53 +00008687
John McCall2de56d12010-08-25 11:45:40 +00008688 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008689 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008690 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8691 if (Input.isInvalid()) return ExprError();
8692 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00008693
8694 // Though we still have to promote half FP to float...
8695 if (resultType->isHalfType()) {
8696 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8697 resultType = Context.FloatTy;
8698 }
8699
Sebastian Redl28507842009-02-26 14:39:58 +00008700 if (resultType->isDependentType())
8701 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008702 if (resultType->isScalarType()) {
8703 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +00008704 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +00008705 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8706 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008707 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8708 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008709 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008710 } else if (resultType->isExtVectorType()) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008711 // Vector logical not returns the signed variant of the operand type.
8712 resultType = GetSignedVectorType(resultType);
8713 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008714 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008715 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008716 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008717 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008718
Reid Spencer5f016e22007-07-11 17:01:13 +00008719 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008720 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008721 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008722 break;
John McCall2de56d12010-08-25 11:45:40 +00008723 case UO_Real:
8724 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008725 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +00008726 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8727 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +00008728 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +00008729 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8730 if (Input.get()->getValueKind() != VK_RValue &&
8731 Input.get()->getObjectKind() == OK_Ordinary)
8732 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +00008733 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +00008734 // In C, a volatile scalar is read by __imag. In C++, it is not.
8735 Input = DefaultLvalueConversion(Input.take());
8736 }
Chris Lattnerdbb36972007-08-24 21:16:53 +00008737 break;
John McCall2de56d12010-08-25 11:45:40 +00008738 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008739 resultType = Input.get()->getType();
8740 VK = Input.get()->getValueKind();
8741 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008742 break;
8743 }
John Wiegley429bb272011-04-08 18:41:53 +00008744 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008745 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008746
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008747 // Check for array bounds violations in the operand of the UnaryOperator,
8748 // except for the '*' and '&' operators that have to be handled specially
8749 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8750 // that are explicitly defined as valid by the standard).
8751 if (Opc != UO_AddrOf && Opc != UO_Deref)
8752 CheckArrayAccess(Input.get());
8753
John Wiegley429bb272011-04-08 18:41:53 +00008754 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008755 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008756}
8757
Douglas Gregord3d08532011-12-14 21:23:13 +00008758/// \brief Determine whether the given expression is a qualified member
8759/// access expression, of a form that could be turned into a pointer to member
8760/// with the address-of operator.
8761static bool isQualifiedMemberAccess(Expr *E) {
8762 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8763 if (!DRE->getQualifier())
8764 return false;
8765
8766 ValueDecl *VD = DRE->getDecl();
8767 if (!VD->isCXXClassMember())
8768 return false;
8769
8770 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8771 return true;
8772 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8773 return Method->isInstance();
8774
8775 return false;
8776 }
8777
8778 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8779 if (!ULE->getQualifier())
8780 return false;
8781
8782 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8783 DEnd = ULE->decls_end();
8784 D != DEnd; ++D) {
8785 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8786 if (Method->isInstance())
8787 return true;
8788 } else {
8789 // Overload set does not contain methods.
8790 break;
8791 }
8792 }
8793
8794 return false;
8795 }
8796
8797 return false;
8798}
8799
John McCall60d7b3a2010-08-24 06:29:42 +00008800ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008801 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +00008802 // First things first: handle placeholders so that the
8803 // overloaded-operator check considers the right type.
8804 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8805 // Increment and decrement of pseudo-object references.
8806 if (pty->getKind() == BuiltinType::PseudoObject &&
8807 UnaryOperator::isIncrementDecrementOp(Opc))
8808 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8809
8810 // extension is always a builtin operator.
8811 if (Opc == UO_Extension)
8812 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8813
8814 // & gets special logic for several kinds of placeholder.
8815 // The builtin code knows what to do.
8816 if (Opc == UO_AddrOf &&
8817 (pty->getKind() == BuiltinType::Overload ||
8818 pty->getKind() == BuiltinType::UnknownAny ||
8819 pty->getKind() == BuiltinType::BoundMember))
8820 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8821
8822 // Anything else needs to be handled now.
8823 ExprResult Result = CheckPlaceholderExpr(Input);
8824 if (Result.isInvalid()) return ExprError();
8825 Input = Result.take();
8826 }
8827
David Blaikie4e4d0842012-03-11 07:00:24 +00008828 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +00008829 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8830 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008831 // Find all of the overloaded operators visible from this
8832 // point. We perform both an operator-name lookup from the local
8833 // scope and an argument-dependent lookup based on the types of
8834 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008835 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008836 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008837 if (S && OverOp != OO_None)
8838 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8839 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008840
John McCall9ae2f072010-08-23 23:25:46 +00008841 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008842 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008843
John McCall9ae2f072010-08-23 23:25:46 +00008844 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008845}
8846
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008847// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008848ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008849 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008850 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008851}
8852
Steve Naroff1b273c42007-09-16 14:56:35 +00008853/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008854ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008855 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008856 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008857 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008858 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008859 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008860}
8861
John McCallf85e1932011-06-15 23:02:42 +00008862/// Given the last statement in a statement-expression, check whether
8863/// the result is a producing expression (like a call to an
8864/// ns_returns_retained function) and, if so, rebuild it to hoist the
8865/// release out of the full-expression. Otherwise, return null.
8866/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +00008867static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +00008868 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +00008869 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCallf85e1932011-06-15 23:02:42 +00008870 if (!cleanups) return 0;
8871
8872 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +00008873 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCallf85e1932011-06-15 23:02:42 +00008874 return 0;
8875
8876 // Splice out the cast. This shouldn't modify any interesting
8877 // features of the statement.
8878 Expr *producer = cast->getSubExpr();
8879 assert(producer->getType() == cast->getType());
8880 assert(producer->getValueKind() == cast->getValueKind());
8881 cleanups->setSubExpr(producer);
8882 return cleanups;
8883}
8884
John McCall73f428c2012-04-04 01:27:53 +00008885void Sema::ActOnStartStmtExpr() {
8886 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8887}
8888
8889void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +00008890 // Note that function is also called by TreeTransform when leaving a
8891 // StmtExpr scope without rebuilding anything.
8892
John McCall73f428c2012-04-04 01:27:53 +00008893 DiscardCleanupsInEvaluationContext();
8894 PopExpressionEvaluationContext();
8895}
8896
John McCall60d7b3a2010-08-24 06:29:42 +00008897ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008898Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008899 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008900 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8901 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8902
John McCall73f428c2012-04-04 01:27:53 +00008903 if (hasAnyUnrecoverableErrorsInThisFunction())
8904 DiscardCleanupsInEvaluationContext();
8905 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8906 PopExpressionEvaluationContext();
8907
Douglas Gregordd8f5692010-03-10 04:54:39 +00008908 bool isFileScope
8909 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008910 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008911 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008912
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008913 // FIXME: there are a variety of strange constraints to enforce here, for
8914 // example, it is not possible to goto into a stmt expression apparently.
8915 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008916
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008917 // If there are sub stmts in the compound stmt, take the type of the last one
8918 // as the type of the stmtexpr.
8919 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008920 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008921 if (!Compound->body_empty()) {
8922 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008923 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008924 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008925 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8926 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008927 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008928 }
John McCallf85e1932011-06-15 23:02:42 +00008929
John Wiegley429bb272011-04-08 18:41:53 +00008930 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008931 // Do function/array conversion on the last expression, but not
8932 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008933 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8934 if (LastExpr.isInvalid())
8935 return ExprError();
8936 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008937
John Wiegley429bb272011-04-08 18:41:53 +00008938 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008939 // In ARC, if the final expression ends in a consume, splice
8940 // the consume out and bind it later. In the alternate case
8941 // (when dealing with a retainable type), the result
8942 // initialization will create a produce. In both cases the
8943 // result will be +1, and we'll need to balance that out with
8944 // a bind.
8945 if (Expr *rebuiltLastStmt
8946 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8947 LastExpr = rebuiltLastStmt;
8948 } else {
8949 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008950 InitializedEntity::InitializeResult(LPLoc,
8951 Ty,
8952 false),
8953 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008954 LastExpr);
8955 }
8956
John Wiegley429bb272011-04-08 18:41:53 +00008957 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008958 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008959 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008960 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008961 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008962 else
John Wiegley429bb272011-04-08 18:41:53 +00008963 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008964 StmtExprMayBindToTemp = true;
8965 }
8966 }
8967 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008968 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008969
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008970 // FIXME: Check that expression type is complete/non-abstract; statement
8971 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008972 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8973 if (StmtExprMayBindToTemp)
8974 return MaybeBindToTemporary(ResStmtExpr);
8975 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008976}
Steve Naroffd34e9152007-08-01 22:05:33 +00008977
John McCall60d7b3a2010-08-24 06:29:42 +00008978ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008979 TypeSourceInfo *TInfo,
8980 OffsetOfComponent *CompPtr,
8981 unsigned NumComponents,
8982 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008983 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008984 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008985 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008986
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008987 // We must have at least one component that refers to the type, and the first
8988 // one is known to be a field designator. Verify that the ArgTy represents
8989 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008990 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008991 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8992 << ArgTy << TypeRange);
8993
8994 // Type must be complete per C99 7.17p3 because a declaring a variable
8995 // with an incomplete type would be ill-formed.
8996 if (!Dependent
8997 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +00008998 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008999 return ExprError();
9000
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009001 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9002 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009003 // FIXME: This diagnostic isn't actually visible because the location is in
9004 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009005 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009006 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9007 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009008
9009 bool DidWarnAboutNonPOD = false;
9010 QualType CurrentType = ArgTy;
9011 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009012 SmallVector<OffsetOfNode, 4> Comps;
9013 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009014 for (unsigned i = 0; i != NumComponents; ++i) {
9015 const OffsetOfComponent &OC = CompPtr[i];
9016 if (OC.isBrackets) {
9017 // Offset of an array sub-field. TODO: Should we allow vector elements?
9018 if (!CurrentType->isDependentType()) {
9019 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9020 if(!AT)
9021 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9022 << CurrentType);
9023 CurrentType = AT->getElementType();
9024 } else
9025 CurrentType = Context.DependentTy;
9026
Richard Smithea011432011-10-17 23:29:39 +00009027 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9028 if (IdxRval.isInvalid())
9029 return ExprError();
9030 Expr *Idx = IdxRval.take();
9031
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009032 // The expression must be an integral expression.
9033 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009034 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9035 !Idx->getType()->isIntegerType())
9036 return ExprError(Diag(Idx->getLocStart(),
9037 diag::err_typecheck_subscript_not_integer)
9038 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +00009039
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009040 // Record this array index.
9041 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +00009042 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009043 continue;
9044 }
9045
9046 // Offset of a field.
9047 if (CurrentType->isDependentType()) {
9048 // We have the offset of a field, but we can't look into the dependent
9049 // type. Just record the identifier of the field.
9050 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9051 CurrentType = Context.DependentTy;
9052 continue;
9053 }
9054
9055 // We need to have a complete type to look into.
9056 if (RequireCompleteType(OC.LocStart, CurrentType,
9057 diag::err_offsetof_incomplete_type))
9058 return ExprError();
9059
9060 // Look for the designated field.
9061 const RecordType *RC = CurrentType->getAs<RecordType>();
9062 if (!RC)
9063 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9064 << CurrentType);
9065 RecordDecl *RD = RC->getDecl();
9066
9067 // C++ [lib.support.types]p5:
9068 // The macro offsetof accepts a restricted set of type arguments in this
9069 // International Standard. type shall be a POD structure or a POD union
9070 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009071 // C++11 [support.types]p4:
9072 // If type is not a standard-layout class (Clause 9), the results are
9073 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009074 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009075 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9076 unsigned DiagID =
9077 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9078 : diag::warn_offsetof_non_pod_type;
9079
9080 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009081 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +00009082 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009083 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9084 << CurrentType))
9085 DidWarnAboutNonPOD = true;
9086 }
9087
9088 // Look for the field.
9089 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9090 LookupQualifiedName(R, RD);
9091 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009092 IndirectFieldDecl *IndirectMemberDecl = 0;
9093 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009094 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009095 MemberDecl = IndirectMemberDecl->getAnonField();
9096 }
9097
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009098 if (!MemberDecl)
9099 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9100 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9101 OC.LocEnd));
9102
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009103 // C99 7.17p3:
9104 // (If the specified member is a bit-field, the behavior is undefined.)
9105 //
9106 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009107 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009108 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9109 << MemberDecl->getDeclName()
9110 << SourceRange(BuiltinLoc, RParenLoc);
9111 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9112 return ExprError();
9113 }
Eli Friedman19410a72010-08-05 10:11:36 +00009114
9115 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009116 if (IndirectMemberDecl)
9117 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009118
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009119 // If the member was found in a base class, introduce OffsetOfNodes for
9120 // the base class indirections.
9121 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9122 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009123 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009124 CXXBasePath &Path = Paths.front();
9125 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9126 B != BEnd; ++B)
9127 Comps.push_back(OffsetOfNode(B->Base));
9128 }
Eli Friedman19410a72010-08-05 10:11:36 +00009129
Francois Pichet87c2e122010-11-21 06:08:52 +00009130 if (IndirectMemberDecl) {
9131 for (IndirectFieldDecl::chain_iterator FI =
9132 IndirectMemberDecl->chain_begin(),
9133 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9134 assert(isa<FieldDecl>(*FI));
9135 Comps.push_back(OffsetOfNode(OC.LocStart,
9136 cast<FieldDecl>(*FI), OC.LocEnd));
9137 }
9138 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009139 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009140
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009141 CurrentType = MemberDecl->getType().getNonReferenceType();
9142 }
9143
9144 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9145 TInfo, Comps.data(), Comps.size(),
9146 Exprs.data(), Exprs.size(), RParenLoc));
9147}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009148
John McCall60d7b3a2010-08-24 06:29:42 +00009149ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009150 SourceLocation BuiltinLoc,
9151 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009152 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +00009153 OffsetOfComponent *CompPtr,
9154 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009155 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +00009156
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009157 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009158 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009159 if (ArgTy.isNull())
9160 return ExprError();
9161
Eli Friedman5a15dc12010-08-05 10:15:45 +00009162 if (!ArgTInfo)
9163 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9164
9165 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +00009166 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009167}
9168
9169
John McCall60d7b3a2010-08-24 06:29:42 +00009170ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009171 Expr *CondExpr,
9172 Expr *LHSExpr, Expr *RHSExpr,
9173 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009174 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9175
John McCallf89e55a2010-11-18 06:31:45 +00009176 ExprValueKind VK = VK_RValue;
9177 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009178 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009179 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009180 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009181 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009182 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009183 } else {
9184 // The conditional expression is required to be a constant expression.
9185 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +00009186 ExprResult CondICE
9187 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9188 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009189 if (CondICE.isInvalid())
9190 return ExprError();
9191 CondExpr = CondICE.take();
Steve Naroffd04fdd52007-08-03 21:21:27 +00009192
Sebastian Redl28507842009-02-26 14:39:58 +00009193 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009194 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9195
9196 resType = ActiveExpr->getType();
9197 ValueDependent = ActiveExpr->isValueDependent();
9198 VK = ActiveExpr->getValueKind();
9199 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009200 }
9201
Sebastian Redlf53597f2009-03-15 17:47:39 +00009202 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009203 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009204 resType->isDependentType(),
9205 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009206}
9207
Steve Naroff4eb206b2008-09-03 18:15:37 +00009208//===----------------------------------------------------------------------===//
9209// Clang Extensions.
9210//===----------------------------------------------------------------------===//
9211
9212/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +00009213void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009214 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuccd891a2011-09-09 01:45:06 +00009215 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009216 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +00009217 if (CurScope)
9218 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009219 else
9220 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +00009221
Eli Friedman84b007f2012-01-26 03:00:14 +00009222 getCurBlock()->HasImplicitReturnType = true;
9223
John McCall538773c2011-11-11 03:19:12 +00009224 // Enter a new evaluation context to insulate the block from any
9225 // cleanups from the enclosing full-expression.
9226 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +00009227}
9228
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009229void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9230 Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009231 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009232 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009233 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009234
John McCallbf1a0282010-06-04 23:28:52 +00009235 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009236 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009237
Douglas Gregor03f1eb02012-06-15 16:59:29 +00009238 // FIXME: We should allow unexpanded parameter packs here, but that would,
9239 // in turn, make the block expression contain unexpanded parameter packs.
9240 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9241 // Drop the parameters.
9242 FunctionProtoType::ExtProtoInfo EPI;
9243 EPI.HasTrailingReturn = false;
9244 EPI.TypeQuals |= DeclSpec::TQ_const;
9245 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9246 EPI);
9247 Sig = Context.getTrivialTypeSourceInfo(T);
9248 }
9249
John McCall711c52b2011-01-05 12:14:39 +00009250 // GetTypeForDeclarator always produces a function type for a block
9251 // literal signature. Furthermore, it is always a FunctionProtoType
9252 // unless the function was written with a typedef.
9253 assert(T->isFunctionType() &&
9254 "GetTypeForDeclarator made a non-function block signature");
9255
9256 // Look for an explicit signature in that function type.
9257 FunctionProtoTypeLoc ExplicitSignature;
9258
9259 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9260 if (isa<FunctionProtoTypeLoc>(tmp)) {
9261 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9262
9263 // Check whether that explicit signature was synthesized by
9264 // GetTypeForDeclarator. If so, don't save that as part of the
9265 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009266 if (ExplicitSignature.getLocalRangeBegin() ==
9267 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009268 // This would be much cheaper if we stored TypeLocs instead of
9269 // TypeSourceInfos.
9270 TypeLoc Result = ExplicitSignature.getResultLoc();
9271 unsigned Size = Result.getFullDataSize();
9272 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9273 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9274
9275 ExplicitSignature = FunctionProtoTypeLoc();
9276 }
John McCall82dc0092010-06-04 11:21:44 +00009277 }
Mike Stump1eb44332009-09-09 15:08:12 +00009278
John McCall711c52b2011-01-05 12:14:39 +00009279 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9280 CurBlock->FunctionType = T;
9281
9282 const FunctionType *Fn = T->getAs<FunctionType>();
9283 QualType RetTy = Fn->getResultType();
9284 bool isVariadic =
9285 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9286
John McCallc71a4912010-06-04 19:02:56 +00009287 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009288
John McCall82dc0092010-06-04 11:21:44 +00009289 // Don't allow returning a objc interface by value.
9290 if (RetTy->isObjCObjectType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009291 Diag(ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009292 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9293 return;
9294 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009295
John McCall82dc0092010-06-04 11:21:44 +00009296 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009297 // return type. TODO: what should we do with declarators like:
9298 // ^ * { ... }
9299 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +00009300 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +00009301 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009302 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +00009303 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +00009304 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009305
John McCall82dc0092010-06-04 11:21:44 +00009306 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009307 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009308 if (ExplicitSignature) {
9309 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9310 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009311 if (Param->getIdentifier() == 0 &&
9312 !Param->isImplicit() &&
9313 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00009314 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009315 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009316 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009317 }
John McCall82dc0092010-06-04 11:21:44 +00009318
9319 // Fake up parameter variables if we have a typedef, like
9320 // ^ fntype { ... }
9321 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9322 for (FunctionProtoType::arg_type_iterator
9323 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9324 ParmVarDecl *Param =
9325 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009326 ParamInfo.getLocStart(),
John McCall82dc0092010-06-04 11:21:44 +00009327 *I);
John McCallc71a4912010-06-04 19:02:56 +00009328 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009329 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009330 }
John McCall82dc0092010-06-04 11:21:44 +00009331
John McCallc71a4912010-06-04 19:02:56 +00009332 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009333 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +00009334 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +00009335 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9336 CurBlock->TheDecl->param_end(),
9337 /*CheckParameterNames=*/false);
9338 }
9339
John McCall82dc0092010-06-04 11:21:44 +00009340 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009341 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009342
John McCall82dc0092010-06-04 11:21:44 +00009343 // Put the parameter variables in scope. We can bail out immediately
9344 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009345 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009346 return;
9347
Steve Naroff090276f2008-10-10 01:28:17 +00009348 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009349 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9350 (*AI)->setOwningFunction(CurBlock->TheDecl);
9351
Steve Naroff090276f2008-10-10 01:28:17 +00009352 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009353 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009354 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009355
Steve Naroff090276f2008-10-10 01:28:17 +00009356 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009357 }
John McCall7a9813c2010-01-22 00:28:27 +00009358 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009359}
9360
9361/// ActOnBlockError - If there is an error parsing a block, this callback
9362/// is invoked to pop the information about the block from the action impl.
9363void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +00009364 // Leave the expression-evaluation context.
9365 DiscardCleanupsInEvaluationContext();
9366 PopExpressionEvaluationContext();
9367
Steve Naroff4eb206b2008-09-03 18:15:37 +00009368 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009369 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009370 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009371}
9372
9373/// ActOnBlockStmtExpr - This is called when the body of a block statement
9374/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009375ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009376 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009377 // If blocks are disabled, emit an error.
9378 if (!LangOpts.Blocks)
9379 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009380
John McCall538773c2011-11-11 03:19:12 +00009381 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +00009382 if (hasAnyUnrecoverableErrorsInThisFunction())
9383 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +00009384 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9385 PopExpressionEvaluationContext();
9386
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009387 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +00009388
9389 if (BSI->HasImplicitReturnType)
9390 deduceClosureReturnType(*BSI);
9391
Steve Naroff090276f2008-10-10 01:28:17 +00009392 PopDeclContext();
9393
Steve Naroff4eb206b2008-09-03 18:15:37 +00009394 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009395 if (!BSI->ReturnType.isNull())
9396 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009397
Mike Stump56925862009-07-28 22:04:01 +00009398 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009399 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009400
John McCall469a1eb2011-02-02 13:00:07 +00009401 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009402 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9403 SmallVector<BlockDecl::Capture, 4> Captures;
9404 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9405 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9406 if (Cap.isThisCapture())
9407 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +00009408 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedmanb69b42c2012-01-11 02:36:31 +00009409 Cap.isNested(), Cap.getCopyExpr());
9410 Captures.push_back(NewCap);
9411 }
9412 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9413 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +00009414
John McCallc71a4912010-06-04 19:02:56 +00009415 // If the user wrote a function type in some form, try to use that.
9416 if (!BSI->FunctionType.isNull()) {
9417 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9418
9419 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9420 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9421
9422 // Turn protoless block types into nullary block types.
9423 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009424 FunctionProtoType::ExtProtoInfo EPI;
9425 EPI.ExtInfo = Ext;
9426 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009427
9428 // Otherwise, if we don't need to change anything about the function type,
9429 // preserve its sugar structure.
9430 } else if (FTy->getResultType() == RetTy &&
9431 (!NoReturn || FTy->getNoReturnAttr())) {
9432 BlockTy = BSI->FunctionType;
9433
9434 // Otherwise, make the minimal modifications to the function type.
9435 } else {
9436 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009437 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9438 EPI.TypeQuals = 0; // FIXME: silently?
9439 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009440 BlockTy = Context.getFunctionType(RetTy,
9441 FPT->arg_type_begin(),
9442 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009443 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009444 }
9445
9446 // If we don't have a function type, just build one from nothing.
9447 } else {
John McCalle23cf432010-12-14 08:05:40 +00009448 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009449 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009450 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009451 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009452
John McCallc71a4912010-06-04 19:02:56 +00009453 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9454 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009455 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009456
Chris Lattner17a78302009-04-19 05:28:12 +00009457 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009458 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +00009459 !hasAnyUnrecoverableErrorsInThisFunction() &&
9460 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +00009461 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009462
Chris Lattnere476bdc2011-02-17 23:58:47 +00009463 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009464
Jordan Rose7dd900e2012-07-02 21:19:23 +00009465 // Try to apply the named return value optimization. We have to check again
9466 // if we can do this, though, because blocks keep return statements around
9467 // to deduce an implicit return type.
9468 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9469 !BSI->TheDecl->isDependentContext())
9470 computeNRVO(Body, getCurBlock());
Douglas Gregorf8b7f712011-09-06 20:46:03 +00009471
Benjamin Kramerd2486192011-07-12 14:11:05 +00009472 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9473 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +00009474 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +00009475
John McCall80ee6e82011-11-10 05:35:25 +00009476 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +00009477 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +00009478 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +00009479 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +00009480 ExprCleanupObjects.push_back(Result->getBlockDecl());
9481 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +00009482
9483 // It also gets a branch-protected scope if any of the captured
9484 // variables needs destruction.
9485 for (BlockDecl::capture_const_iterator
9486 ci = Result->getBlockDecl()->capture_begin(),
9487 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9488 const VarDecl *var = ci->getVariable();
9489 if (var->getType().isDestructedType() != QualType::DK_none) {
9490 getCurFunction()->setHasBranchProtectedScope();
9491 break;
9492 }
9493 }
John McCall80ee6e82011-11-10 05:35:25 +00009494 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +00009495
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009496 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009497}
9498
John McCall60d7b3a2010-08-24 06:29:42 +00009499ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009500 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009501 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009502 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +00009503 GetTypeFromParser(Ty, &TInfo);
9504 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009505}
9506
John McCall60d7b3a2010-08-24 06:29:42 +00009507ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009508 Expr *E, TypeSourceInfo *TInfo,
9509 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009510 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009511
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009512 // Get the va_list type
9513 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009514 if (VaListType->isArrayType()) {
9515 // Deal with implicit array decay; for example, on x86-64,
9516 // va_list is an array, but it's supposed to decay to
9517 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009518 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009519 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009520 ExprResult Result = UsualUnaryConversions(E);
9521 if (Result.isInvalid())
9522 return ExprError();
9523 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009524 } else {
9525 // Otherwise, the va_list argument must be an l-value because
9526 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009527 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009528 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009529 return ExprError();
9530 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009531
Douglas Gregordd027302009-05-19 23:10:31 +00009532 if (!E->isTypeDependent() &&
9533 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009534 return ExprError(Diag(E->getLocStart(),
9535 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009536 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009537 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009538
David Majnemer0adde122011-06-14 05:17:32 +00009539 if (!TInfo->getType()->isDependentType()) {
9540 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009541 diag::err_second_parameter_to_va_arg_incomplete,
9542 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009543 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00009544
David Majnemer0adde122011-06-14 05:17:32 +00009545 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00009546 TInfo->getType(),
9547 diag::err_second_parameter_to_va_arg_abstract,
9548 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +00009549 return ExprError();
9550
Douglas Gregor4eb75222011-07-30 06:45:27 +00009551 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00009552 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00009553 TInfo->getType()->isObjCLifetimeType()
9554 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9555 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00009556 << TInfo->getType()
9557 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00009558 }
Eli Friedman46d37c12011-07-11 21:45:59 +00009559
9560 // Check for va_arg where arguments of the given type will be promoted
9561 // (i.e. this va_arg is guaranteed to have undefined behavior).
9562 QualType PromoteType;
9563 if (TInfo->getType()->isPromotableIntegerType()) {
9564 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9565 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9566 PromoteType = QualType();
9567 }
9568 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9569 PromoteType = Context.DoubleTy;
9570 if (!PromoteType.isNull())
9571 Diag(TInfo->getTypeLoc().getBeginLoc(),
9572 diag::warn_second_parameter_to_va_arg_never_compatible)
9573 << TInfo->getType()
9574 << PromoteType
9575 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00009576 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009577
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009578 QualType T = TInfo->getType().getNonLValueExprType(Context);
9579 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009580}
9581
John McCall60d7b3a2010-08-24 06:29:42 +00009582ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009583 // The type of __null will be int or long, depending on the size of
9584 // pointers on the target.
9585 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009586 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9587 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009588 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009589 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009590 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00009591 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009592 Ty = Context.LongLongTy;
9593 else {
David Blaikieb219cfc2011-09-23 05:06:16 +00009594 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009595 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009596
Sebastian Redlf53597f2009-03-15 17:47:39 +00009597 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009598}
9599
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009600static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009601 Expr *SrcExpr, FixItHint &Hint) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009602 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009603 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009604
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009605 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9606 if (!PT)
9607 return;
9608
9609 // Check if the destination is of type 'id'.
9610 if (!PT->isObjCIdType()) {
9611 // Check if the destination is the 'NSString' interface.
9612 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9613 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9614 return;
9615 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009616
John McCall4b9c2d22011-11-06 09:01:30 +00009617 // Ignore any parens, implicit casts (should only be
9618 // array-to-pointer decays), and not-so-opaque values. The last is
9619 // important for making this trigger for property assignments.
9620 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9621 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9622 if (OV->getSourceExpr())
9623 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9624
9625 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +00009626 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009627 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009628
Douglas Gregor849b2432010-03-31 17:46:05 +00009629 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009630}
9631
Chris Lattner5cf216b2008-01-04 18:04:52 +00009632bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9633 SourceLocation Loc,
9634 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009635 Expr *SrcExpr, AssignmentAction Action,
9636 bool *Complained) {
9637 if (Complained)
9638 *Complained = false;
9639
Chris Lattner5cf216b2008-01-04 18:04:52 +00009640 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00009641 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009642 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +00009643 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +00009644 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00009645 ConversionFixItGenerator ConvHints;
9646 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009647 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009648
Chris Lattner5cf216b2008-01-04 18:04:52 +00009649 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +00009650 case Compatible:
9651 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9652 return false;
9653
Chris Lattnerb7b61152008-01-04 18:22:42 +00009654 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009655 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00009656 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9657 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009658 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009659 case IntToPointer:
9660 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00009661 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9662 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009663 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009664 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009665 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009666 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00009667 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9668 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00009669 if (Hint.isNull() && !CheckInferredResultType) {
9670 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9671 }
9672 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009673 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009674 case IncompatiblePointerSign:
9675 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9676 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009677 case FunctionVoidPointer:
9678 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9679 break;
John McCall86c05f32011-02-01 00:10:29 +00009680 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009681 // Perform array-to-pointer decay if necessary.
9682 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9683
John McCall86c05f32011-02-01 00:10:29 +00009684 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9685 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9686 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9687 DiagKind = diag::err_typecheck_incompatible_address_space;
9688 break;
John McCallf85e1932011-06-15 23:02:42 +00009689
9690
9691 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00009692 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00009693 break;
John McCall86c05f32011-02-01 00:10:29 +00009694 }
9695
9696 llvm_unreachable("unknown error case for discarding qualifiers!");
9697 // fallthrough
9698 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009699 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009700 // If the qualifiers lost were because we were applying the
9701 // (deprecated) C++ conversion from a string literal to a char*
9702 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9703 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009704 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009705 // bit of refactoring (so that the second argument is an
9706 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009707 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009708 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009709 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +00009710 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9711 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009712 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9713 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009714 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009715 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009716 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009717 case IntToBlockPointer:
9718 DiagKind = diag::err_int_to_block_pointer;
9719 break;
9720 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009721 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009722 break;
Steve Naroff39579072008-10-14 22:18:38 +00009723 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009724 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009725 // it can give a more specific diagnostic.
9726 DiagKind = diag::warn_incompatible_qualified_id;
9727 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009728 case IncompatibleVectors:
9729 DiagKind = diag::warn_incompatible_vectors;
9730 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00009731 case IncompatibleObjCWeakRef:
9732 DiagKind = diag::err_arc_weak_unavailable_assign;
9733 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009734 case Incompatible:
9735 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00009736 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9737 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009738 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +00009739 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009740 break;
9741 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009742
Douglas Gregord4eea832010-04-09 00:35:39 +00009743 QualType FirstType, SecondType;
9744 switch (Action) {
9745 case AA_Assigning:
9746 case AA_Initializing:
9747 // The destination type comes first.
9748 FirstType = DstType;
9749 SecondType = SrcType;
9750 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009751
Douglas Gregord4eea832010-04-09 00:35:39 +00009752 case AA_Returning:
9753 case AA_Passing:
9754 case AA_Converting:
9755 case AA_Sending:
9756 case AA_Casting:
9757 // The source type comes first.
9758 FirstType = SrcType;
9759 SecondType = DstType;
9760 break;
9761 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009762
Anna Zaks67221552011-07-28 19:51:27 +00009763 PartialDiagnostic FDiag = PDiag(DiagKind);
9764 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9765
9766 // If we can fix the conversion, suggest the FixIts.
9767 assert(ConvHints.isNull() || Hint.isNull());
9768 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +00009769 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9770 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +00009771 FDiag << *HI;
9772 } else {
9773 FDiag << Hint;
9774 }
9775 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9776
Richard Trieu6efd4c52011-11-23 22:32:32 +00009777 if (MayHaveFunctionDiff)
9778 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9779
Anna Zaks67221552011-07-28 19:51:27 +00009780 Diag(Loc, FDiag);
9781
Richard Trieu6efd4c52011-11-23 22:32:32 +00009782 if (SecondType == Context.OverloadTy)
9783 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9784 FirstType);
9785
Douglas Gregor926df6c2011-06-11 01:09:30 +00009786 if (CheckInferredResultType)
9787 EmitRelatedResultTypeNote(SrcExpr);
9788
Douglas Gregora41a8c52010-04-22 00:20:18 +00009789 if (Complained)
9790 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009791 return isInvalid;
9792}
Anders Carlssone21555e2008-11-30 19:50:32 +00009793
Richard Smith282e7e62012-02-04 09:53:13 +00009794ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9795 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009796 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9797 public:
9798 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9799 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9800 }
9801 } Diagnoser;
9802
9803 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9804}
9805
9806ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9807 llvm::APSInt *Result,
9808 unsigned DiagID,
9809 bool AllowFold) {
9810 class IDDiagnoser : public VerifyICEDiagnoser {
9811 unsigned DiagID;
9812
9813 public:
9814 IDDiagnoser(unsigned DiagID)
9815 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9816
9817 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9818 S.Diag(Loc, DiagID) << SR;
9819 }
9820 } Diagnoser(DiagID);
9821
9822 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9823}
9824
9825void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9826 SourceRange SR) {
9827 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +00009828}
9829
Benjamin Kramerd448ce02012-04-18 14:22:41 +00009830ExprResult
9831Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009832 VerifyICEDiagnoser &Diagnoser,
9833 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009834 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +00009835
David Blaikie4e4d0842012-03-11 07:00:24 +00009836 if (getLangOpts().CPlusPlus0x) {
Richard Smith282e7e62012-02-04 09:53:13 +00009837 // C++11 [expr.const]p5:
9838 // If an expression of literal class type is used in a context where an
9839 // integral constant expression is required, then that class type shall
9840 // have a single non-explicit conversion function to an integral or
9841 // unscoped enumeration type
9842 ExprResult Converted;
Douglas Gregorab41fe92012-05-04 22:38:52 +00009843 if (!Diagnoser.Suppress) {
9844 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9845 public:
9846 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9847
9848 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9849 QualType T) {
9850 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9851 }
9852
9853 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9854 SourceLocation Loc,
9855 QualType T) {
9856 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9857 }
9858
9859 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9860 SourceLocation Loc,
9861 QualType T,
9862 QualType ConvTy) {
9863 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9864 }
9865
9866 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9867 CXXConversionDecl *Conv,
9868 QualType ConvTy) {
9869 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9870 << ConvTy->isEnumeralType() << ConvTy;
9871 }
9872
9873 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9874 QualType T) {
9875 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9876 }
9877
9878 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9879 CXXConversionDecl *Conv,
9880 QualType ConvTy) {
9881 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9882 << ConvTy->isEnumeralType() << ConvTy;
9883 }
9884
9885 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9886 SourceLocation Loc,
9887 QualType T,
9888 QualType ConvTy) {
9889 return DiagnosticBuilder::getEmpty();
9890 }
9891 } ConvertDiagnoser;
9892
9893 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9894 ConvertDiagnoser,
9895 /*AllowScopedEnumerations*/ false);
Richard Smith282e7e62012-02-04 09:53:13 +00009896 } else {
9897 // The caller wants to silently enquire whether this is an ICE. Don't
9898 // produce any diagnostics if it isn't.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009899 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9900 public:
9901 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9902
9903 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9904 QualType T) {
9905 return DiagnosticBuilder::getEmpty();
9906 }
9907
9908 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9909 SourceLocation Loc,
9910 QualType T) {
9911 return DiagnosticBuilder::getEmpty();
9912 }
9913
9914 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9915 SourceLocation Loc,
9916 QualType T,
9917 QualType ConvTy) {
9918 return DiagnosticBuilder::getEmpty();
9919 }
9920
9921 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9922 CXXConversionDecl *Conv,
9923 QualType ConvTy) {
9924 return DiagnosticBuilder::getEmpty();
9925 }
9926
9927 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9928 QualType T) {
9929 return DiagnosticBuilder::getEmpty();
9930 }
9931
9932 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9933 CXXConversionDecl *Conv,
9934 QualType ConvTy) {
9935 return DiagnosticBuilder::getEmpty();
9936 }
9937
9938 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9939 SourceLocation Loc,
9940 QualType T,
9941 QualType ConvTy) {
9942 return DiagnosticBuilder::getEmpty();
9943 }
9944 } ConvertDiagnoser;
9945
9946 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9947 ConvertDiagnoser, false);
Richard Smith282e7e62012-02-04 09:53:13 +00009948 }
9949 if (Converted.isInvalid())
9950 return Converted;
9951 E = Converted.take();
9952 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9953 return ExprError();
9954 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9955 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +00009956 if (!Diagnoser.Suppress)
9957 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +00009958 return ExprError();
9959 }
9960
Richard Smithdaaefc52011-12-14 23:32:26 +00009961 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9962 // in the non-ICE case.
David Blaikie4e4d0842012-03-11 07:00:24 +00009963 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +00009964 if (Result)
9965 *Result = E->EvaluateKnownConstInt(Context);
9966 return Owned(E);
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009967 }
9968
Anders Carlssone21555e2008-11-30 19:50:32 +00009969 Expr::EvalResult EvalResult;
Richard Smithdd1f29b2011-12-12 09:28:41 +00009970 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9971 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +00009972
Richard Smithdaaefc52011-12-14 23:32:26 +00009973 // Try to evaluate the expression, and produce diagnostics explaining why it's
9974 // not a constant expression as a side-effect.
9975 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9976 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9977
9978 // In C++11, we can rely on diagnostics being produced for any expression
9979 // which is not a constant expression. If no diagnostics were produced, then
9980 // this is a constant expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00009981 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009982 if (Result)
9983 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +00009984 return Owned(E);
9985 }
9986
9987 // If our only note is the usual "invalid subexpression" note, just point
9988 // the caret at its location rather than producing an essentially
9989 // redundant note.
9990 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9991 diag::note_invalid_subexpr_in_const_expr) {
9992 DiagLoc = Notes[0].first;
9993 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +00009994 }
9995
9996 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00009997 if (!Diagnoser.Suppress) {
9998 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +00009999 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10000 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000010001 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010002
Richard Smith282e7e62012-02-04 09:53:13 +000010003 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000010004 }
10005
Douglas Gregorab41fe92012-05-04 22:38:52 +000010006 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000010007 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10008 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010009
Anders Carlssone21555e2008-11-30 19:50:32 +000010010 if (Result)
10011 *Result = EvalResult.Val.getInt();
Richard Smith282e7e62012-02-04 09:53:13 +000010012 return Owned(E);
Anders Carlssone21555e2008-11-30 19:50:32 +000010013}
Douglas Gregore0762c92009-06-19 23:52:42 +000010014
Eli Friedmanef331b72012-01-20 01:26:23 +000010015namespace {
10016 // Handle the case where we conclude a expression which we speculatively
10017 // considered to be unevaluated is actually evaluated.
10018 class TransformToPE : public TreeTransform<TransformToPE> {
10019 typedef TreeTransform<TransformToPE> BaseTransform;
10020
10021 public:
10022 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10023
10024 // Make sure we redo semantic analysis
10025 bool AlwaysRebuild() { return true; }
10026
Eli Friedman56ff2832012-02-06 23:29:57 +000010027 // Make sure we handle LabelStmts correctly.
10028 // FIXME: This does the right thing, but maybe we need a more general
10029 // fix to TreeTransform?
10030 StmtResult TransformLabelStmt(LabelStmt *S) {
10031 S->getDecl()->setStmt(0);
10032 return BaseTransform::TransformLabelStmt(S);
10033 }
10034
Eli Friedmanef331b72012-01-20 01:26:23 +000010035 // We need to special-case DeclRefExprs referring to FieldDecls which
10036 // are not part of a member pointer formation; normal TreeTransforming
10037 // doesn't catch this case because of the way we represent them in the AST.
10038 // FIXME: This is a bit ugly; is it really the best way to handle this
10039 // case?
10040 //
10041 // Error on DeclRefExprs referring to FieldDecls.
10042 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10043 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000010044 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000010045 return SemaRef.Diag(E->getLocation(),
10046 diag::err_invalid_non_static_member_use)
10047 << E->getDecl() << E->getSourceRange();
10048
10049 return BaseTransform::TransformDeclRefExpr(E);
10050 }
10051
10052 // Exception: filter out member pointer formation
10053 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10054 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10055 return E;
10056
10057 return BaseTransform::TransformUnaryOperator(E);
10058 }
10059
Douglas Gregore2c59132012-02-09 08:14:43 +000010060 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10061 // Lambdas never need to be transformed.
10062 return E;
10063 }
Eli Friedmanef331b72012-01-20 01:26:23 +000010064 };
Eli Friedman93c878e2012-01-18 01:05:54 +000010065}
10066
Eli Friedmanef331b72012-01-20 01:26:23 +000010067ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedman72b8b1e2012-02-29 04:03:55 +000010068 assert(ExprEvalContexts.back().Context == Unevaluated &&
10069 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000010070 ExprEvalContexts.back().Context =
10071 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10072 if (ExprEvalContexts.back().Context == Unevaluated)
10073 return E;
10074 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000010075}
10076
Douglas Gregor2afce722009-11-26 00:44:06 +000010077void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010078Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000010079 Decl *LambdaContextDecl,
10080 bool IsDecltype) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010081 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010082 ExpressionEvaluationContextRecord(NewContext,
John McCall80ee6e82011-11-10 05:35:25 +000010083 ExprCleanupObjects.size(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000010084 ExprNeedsCleanups,
Richard Smith76f3f692012-02-22 02:04:18 +000010085 LambdaContextDecl,
10086 IsDecltype));
John McCallf85e1932011-06-15 23:02:42 +000010087 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010088 if (!MaybeODRUseExprs.empty())
10089 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010090}
10091
Richard Trieu67e29332011-08-02 04:35:43 +000010092void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010093 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010094
Douglas Gregore2c59132012-02-09 08:14:43 +000010095 if (!Rec.Lambdas.empty()) {
10096 if (Rec.Context == Unevaluated) {
10097 // C++11 [expr.prim.lambda]p2:
10098 // A lambda-expression shall not appear in an unevaluated operand
10099 // (Clause 5).
10100 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10101 Diag(Rec.Lambdas[I]->getLocStart(),
10102 diag::err_lambda_unevaluated_operand);
10103 } else {
10104 // Mark the capture expressions odr-used. This was deferred
10105 // during lambda expression creation.
10106 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10107 LambdaExpr *Lambda = Rec.Lambdas[I];
10108 for (LambdaExpr::capture_init_iterator
10109 C = Lambda->capture_init_begin(),
10110 CEnd = Lambda->capture_init_end();
10111 C != CEnd; ++C) {
10112 MarkDeclarationsReferencedInExpr(*C);
10113 }
10114 }
10115 }
10116 }
10117
Douglas Gregor2afce722009-11-26 00:44:06 +000010118 // When are coming out of an unevaluated context, clear out any
10119 // temporaries that we may have created as part of the evaluation of
10120 // the expression in that context: they aren't relevant because they
10121 // will never be constructed.
Richard Smithf6702a32011-12-20 02:08:33 +000010122 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000010123 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10124 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010125 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010126 CleanupVarDeclMarking();
10127 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000010128 // Otherwise, merge the contexts together.
10129 } else {
10130 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000010131 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10132 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000010133 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010134
10135 // Pop the current expression evaluation context off the stack.
10136 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010137}
Douglas Gregore0762c92009-06-19 23:52:42 +000010138
John McCallf85e1932011-06-15 23:02:42 +000010139void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000010140 ExprCleanupObjects.erase(
10141 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10142 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000010143 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000010144 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000010145}
10146
Eli Friedman71b8fb52012-01-21 01:01:51 +000010147ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10148 if (!E->getType()->isVariablyModifiedType())
10149 return E;
10150 return TranformToPotentiallyEvaluated(E);
10151}
10152
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000010153static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000010154 // Do not mark anything as "used" within a dependent context; wait for
10155 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010156 if (SemaRef.CurContext->isDependentContext())
10157 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010158
Eli Friedman5f2987c2012-02-02 03:46:19 +000010159 switch (SemaRef.ExprEvalContexts.back().Context) {
10160 case Sema::Unevaluated:
Douglas Gregorac7610d2009-06-22 20:57:11 +000010161 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000010162 // (Depending on how you read the standard, we actually do need to do
10163 // something here for null pointer constants, but the standard's
10164 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000010165 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010166
Eli Friedman5f2987c2012-02-02 03:46:19 +000010167 case Sema::ConstantEvaluated:
10168 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000010169 // We are in a potentially evaluated expression (or a constant-expression
10170 // in C++03); we need to do implicit template instantiation, implicitly
10171 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010172 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000010173
Eli Friedman5f2987c2012-02-02 03:46:19 +000010174 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010175 // Referenced declarations will only be used if the construct in the
10176 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010177 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010178 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000010179 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000010180}
10181
10182/// \brief Mark a function referenced, and check whether it is odr-used
10183/// (C++ [basic.def.odr]p2, C99 6.9p3)
10184void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10185 assert(Func && "No function?");
10186
10187 Func->setReferenced();
10188
Richard Smith57b9c4e2012-02-14 22:25:15 +000010189 // Don't mark this function as used multiple times, unless it's a constexpr
10190 // function which we need to instantiate.
10191 if (Func->isUsed(false) &&
10192 !(Func->isConstexpr() && !Func->getBody() &&
10193 Func->isImplicitlyInstantiable()))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010194 return;
10195
10196 if (!IsPotentiallyEvaluatedContext(*this))
10197 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010198
Douglas Gregore0762c92009-06-19 23:52:42 +000010199 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000010200 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010201 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010202 if (Constructor->isDefaultConstructor()) {
10203 if (Constructor->isTrivial())
10204 return;
10205 if (!Constructor->isUsed(false))
10206 DefineImplicitDefaultConstructor(Loc, Constructor);
10207 } else if (Constructor->isCopyConstructor()) {
10208 if (!Constructor->isUsed(false))
10209 DefineImplicitCopyConstructor(Loc, Constructor);
10210 } else if (Constructor->isMoveConstructor()) {
10211 if (!Constructor->isUsed(false))
10212 DefineImplicitMoveConstructor(Loc, Constructor);
10213 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010214 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010215
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010216 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010217 } else if (CXXDestructorDecl *Destructor =
10218 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010219 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10220 !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010221 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010222 if (Destructor->isVirtual())
10223 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000010224 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith03f68782012-02-26 07:51:39 +000010225 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10226 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010227 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010228 if (!MethodDecl->isUsed(false)) {
10229 if (MethodDecl->isCopyAssignmentOperator())
10230 DefineImplicitCopyAssignment(Loc, MethodDecl);
10231 else
10232 DefineImplicitMoveAssignment(Loc, MethodDecl);
10233 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010234 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10235 MethodDecl->getParent()->isLambda()) {
10236 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10237 if (Conversion->isLambdaToBlockPointerConversion())
10238 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10239 else
10240 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010241 } else if (MethodDecl->isVirtual())
10242 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010243 }
John McCall15e310a2011-02-19 02:53:41 +000010244
Eli Friedman5f2987c2012-02-02 03:46:19 +000010245 // Recursive functions should be marked when used from another function.
10246 // FIXME: Is this really right?
10247 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010248
Richard Smithb9d0b762012-07-27 04:22:15 +000010249 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000010250 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000010251 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000010252 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10253 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000010254
Eli Friedman5f2987c2012-02-02 03:46:19 +000010255 // Implicit instantiation of function templates and member functions of
10256 // class templates.
10257 if (Func->isImplicitlyInstantiable()) {
10258 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010259 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000010260 if (FunctionTemplateSpecializationInfo *SpecInfo
10261 = Func->getTemplateSpecializationInfo()) {
10262 if (SpecInfo->getPointOfInstantiation().isInvalid())
10263 SpecInfo->setPointOfInstantiation(Loc);
10264 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010265 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010266 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010267 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10268 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010269 } else if (MemberSpecializationInfo *MSInfo
10270 = Func->getMemberSpecializationInfo()) {
10271 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010272 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010273 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000010274 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010275 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000010276 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10277 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010278 }
Mike Stump1eb44332009-09-09 15:08:12 +000010279
Richard Smith57b9c4e2012-02-14 22:25:15 +000010280 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010281 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10282 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith57b9c4e2012-02-14 22:25:15 +000010283 PendingLocalImplicitInstantiations.push_back(
10284 std::make_pair(Func, PointOfInstantiation));
10285 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010286 // Do not defer instantiations of constexpr functions, to avoid the
10287 // expression evaluator needing to call back into Sema if it sees a
10288 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000010289 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010290 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000010291 PendingInstantiations.push_back(std::make_pair(Func,
10292 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000010293 // Notify the consumer that a function was implicitly instantiated.
10294 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10295 }
John McCall15e310a2011-02-19 02:53:41 +000010296 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010297 } else {
10298 // Walk redefinitions, as some of them may be instantiable.
10299 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10300 e(Func->redecls_end()); i != e; ++i) {
10301 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10302 MarkFunctionReferenced(Loc, *i);
10303 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010304 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000010305
10306 // Keep track of used but undefined functions.
10307 if (!Func->isPure() && !Func->hasBody() &&
10308 Func->getLinkage() != ExternalLinkage) {
10309 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10310 if (old.isInvalid()) old = Loc;
10311 }
10312
10313 Func->setUsed(true);
10314}
10315
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010316static void
10317diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10318 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000010319 DeclContext *VarDC = var->getDeclContext();
10320
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010321 // If the parameter still belongs to the translation unit, then
10322 // we're actually just using one parameter in the declaration of
10323 // the next.
10324 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000010325 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010326 return;
10327
Eli Friedman0a294222012-02-07 00:15:00 +000010328 // For C code, don't diagnose about capture if we're not actually in code
10329 // right now; it's impossible to write a non-constant expression outside of
10330 // function context, so we'll get other (more useful) diagnostics later.
10331 //
10332 // For C++, things get a bit more nasty... it would be nice to suppress this
10333 // diagnostic for certain cases like using a local variable in an array bound
10334 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000010335 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010336 return;
10337
Eli Friedman0a294222012-02-07 00:15:00 +000010338 if (isa<CXXMethodDecl>(VarDC) &&
10339 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10340 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10341 << var->getIdentifier();
10342 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10343 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10344 << var->getIdentifier() << fn->getDeclName();
10345 } else if (isa<BlockDecl>(VarDC)) {
10346 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10347 << var->getIdentifier();
10348 } else {
10349 // FIXME: Is there any other context where a local variable can be
10350 // declared?
10351 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10352 << var->getIdentifier();
10353 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010354
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010355 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10356 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000010357
10358 // FIXME: Add additional diagnostic info about class etc. which prevents
10359 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010360}
10361
Douglas Gregorf8af9822012-02-12 18:42:33 +000010362/// \brief Capture the given variable in the given lambda expression.
10363static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000010364 VarDecl *Var, QualType FieldType,
10365 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010366 SourceLocation Loc,
10367 bool RefersToEnclosingLocal) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010368 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010369
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010370 // Build the non-static data member.
10371 FieldDecl *Field
10372 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10373 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smithca523302012-06-10 03:12:00 +000010374 0, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010375 Field->setImplicit(true);
10376 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000010377 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010378
10379 // C++11 [expr.prim.lambda]p21:
10380 // When the lambda-expression is evaluated, the entities that
10381 // are captured by copy are used to direct-initialize each
10382 // corresponding non-static data member of the resulting closure
10383 // object. (For array members, the array elements are
10384 // direct-initialized in increasing subscript order.) These
10385 // initializations are performed in the (unspecified) order in
10386 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010387
Douglas Gregore2c59132012-02-09 08:14:43 +000010388 // Introduce a new evaluation context for the initialization, so
10389 // that temporaries introduced as part of the capture are retained
10390 // to be re-"exported" from the lambda expression itself.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010391 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10392
Douglas Gregor73d90922012-02-10 09:26:04 +000010393 // C++ [expr.prim.labda]p12:
10394 // An entity captured by a lambda-expression is odr-used (3.2) in
10395 // the scope containing the lambda-expression.
Douglas Gregord57f52c2012-05-16 17:01:33 +000010396 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10397 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000010398 Var->setReferenced(true);
Douglas Gregor73d90922012-02-10 09:26:04 +000010399 Var->setUsed(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010400
10401 // When the field has array type, create index variables for each
10402 // dimension of the array. We use these index variables to subscript
10403 // the source array, and other clients (e.g., CodeGen) will perform
10404 // the necessary iteration with these index variables.
10405 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010406 QualType BaseType = FieldType;
10407 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010408 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000010409 while (const ConstantArrayType *Array
10410 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000010411 // Create the iteration variable for this array index.
10412 IdentifierInfo *IterationVarName = 0;
10413 {
10414 SmallString<8> Str;
10415 llvm::raw_svector_ostream OS(Str);
10416 OS << "__i" << IndexVariables.size();
10417 IterationVarName = &S.Context.Idents.get(OS.str());
10418 }
10419 VarDecl *IterationVar
10420 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10421 IterationVarName, SizeType,
10422 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10423 SC_None, SC_None);
10424 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000010425 LSI->ArrayIndexVars.push_back(IterationVar);
10426
Douglas Gregor18fe0842012-02-09 02:45:47 +000010427 // Create a reference to the iteration variable.
10428 ExprResult IterationVarRef
10429 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10430 assert(!IterationVarRef.isInvalid() &&
10431 "Reference to invented variable cannot fail!");
10432 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10433 assert(!IterationVarRef.isInvalid() &&
10434 "Conversion of invented variable cannot fail!");
10435
10436 // Subscript the array with this iteration variable.
10437 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10438 Ref, Loc, IterationVarRef.take(), Loc);
10439 if (Subscript.isInvalid()) {
10440 S.CleanupVarDeclMarking();
10441 S.DiscardCleanupsInEvaluationContext();
10442 S.PopExpressionEvaluationContext();
10443 return ExprError();
10444 }
10445
10446 Ref = Subscript.take();
10447 BaseType = Array->getElementType();
10448 }
10449
10450 // Construct the entity that we will be initializing. For an array, this
10451 // will be first element in the array, which may require several levels
10452 // of array-subscript entities.
10453 SmallVector<InitializedEntity, 4> Entities;
10454 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000010455 Entities.push_back(
10456 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000010457 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10458 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10459 0,
10460 Entities.back()));
10461
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010462 InitializationKind InitKind
10463 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010464 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010465 ExprResult Result(true);
Douglas Gregor18fe0842012-02-09 02:45:47 +000010466 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
Benjamin Kramer5354e772012-08-23 23:38:35 +000010467 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010468
10469 // If this initialization requires any cleanups (e.g., due to a
10470 // default argument to a copy constructor), note that for the
10471 // lambda.
10472 if (S.ExprNeedsCleanups)
10473 LSI->ExprNeedsCleanups = true;
10474
10475 // Exit the expression evaluation context used for the capture.
10476 S.CleanupVarDeclMarking();
10477 S.DiscardCleanupsInEvaluationContext();
10478 S.PopExpressionEvaluationContext();
10479 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000010480}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000010481
Douglas Gregor999713e2012-02-18 09:37:24 +000010482bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10483 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10484 bool BuildAndDiagnose,
10485 QualType &CaptureType,
10486 QualType &DeclRefType) {
10487 bool Nested = false;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010488
Eli Friedmanb942cb22012-02-03 22:47:37 +000010489 DeclContext *DC = CurContext;
Douglas Gregor999713e2012-02-18 09:37:24 +000010490 if (Var->getDeclContext() == DC) return true;
10491 if (!Var->hasLocalStorage()) return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010492
Douglas Gregorf8af9822012-02-12 18:42:33 +000010493 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010494
Douglas Gregor999713e2012-02-18 09:37:24 +000010495 // Walk up the stack to determine whether we can capture the variable,
10496 // performing the "simple" checks that don't depend on type. We stop when
10497 // we've either hit the declared scope of the variable or find an existing
10498 // capture of that variable.
10499 CaptureType = Var->getType();
10500 DeclRefType = CaptureType.getNonReferenceType();
10501 bool Explicit = (Kind != TryCapture_Implicit);
10502 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010503 do {
Eli Friedmanb942cb22012-02-03 22:47:37 +000010504 // Only block literals and lambda expressions can capture; other
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010505 // scopes don't work.
Eli Friedmanb942cb22012-02-03 22:47:37 +000010506 DeclContext *ParentDC;
10507 if (isa<BlockDecl>(DC))
10508 ParentDC = DC->getParent();
10509 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregorf8af9822012-02-12 18:42:33 +000010510 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedmanb942cb22012-02-03 22:47:37 +000010511 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10512 ParentDC = DC->getParent()->getParent();
Douglas Gregorf8af9822012-02-12 18:42:33 +000010513 else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010514 if (BuildAndDiagnose)
Douglas Gregorf8af9822012-02-12 18:42:33 +000010515 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregor999713e2012-02-18 09:37:24 +000010516 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010517 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010518
Eli Friedmanb942cb22012-02-03 22:47:37 +000010519 CapturingScopeInfo *CSI =
Douglas Gregorf8af9822012-02-12 18:42:33 +000010520 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010521
Eli Friedmanb942cb22012-02-03 22:47:37 +000010522 // Check whether we've already captured it.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010523 if (CSI->CaptureMap.count(Var)) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010524 // If we found a capture, any subcaptures are nested.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010525 Nested = true;
Douglas Gregor999713e2012-02-18 09:37:24 +000010526
10527 // Retrieve the capture type for this variable.
10528 CaptureType = CSI->getCapture(Var).getCaptureType();
10529
10530 // Compute the type of an expression that refers to this variable.
10531 DeclRefType = CaptureType.getNonReferenceType();
10532
10533 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10534 if (Cap.isCopyCapture() &&
10535 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10536 DeclRefType.addConst();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010537 break;
10538 }
10539
Douglas Gregorf8af9822012-02-12 18:42:33 +000010540 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregor999713e2012-02-18 09:37:24 +000010541 bool IsLambda = !IsBlock;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010542
10543 // Lambdas are not allowed to capture unnamed variables
10544 // (e.g. anonymous unions).
10545 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10546 // assuming that's the intent.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010547 if (IsLambda && !Var->getDeclName()) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010548 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010549 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10550 Diag(Var->getLocation(), diag::note_declared_at);
10551 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010552 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010553 }
10554
10555 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregor999713e2012-02-18 09:37:24 +000010556 if (Var->getType()->isVariablyModifiedType()) {
10557 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010558 if (IsBlock)
10559 Diag(Loc, diag::err_ref_vm_type);
10560 else
10561 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10562 Diag(Var->getLocation(), diag::note_previous_decl)
10563 << Var->getDeclName();
10564 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010565 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010566 }
10567
Eli Friedmanb942cb22012-02-03 22:47:37 +000010568 // Lambdas are not allowed to capture __block variables; they don't
10569 // support the expected semantics.
Douglas Gregorf8af9822012-02-12 18:42:33 +000010570 if (IsLambda && HasBlocksAttr) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010571 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010572 Diag(Loc, diag::err_lambda_capture_block)
10573 << Var->getDeclName();
10574 Diag(Var->getLocation(), diag::note_previous_decl)
10575 << Var->getDeclName();
10576 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010577 return true;
Eli Friedmanb942cb22012-02-03 22:47:37 +000010578 }
10579
Douglas Gregorf8af9822012-02-12 18:42:33 +000010580 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10581 // No capture-default
Douglas Gregor999713e2012-02-18 09:37:24 +000010582 if (BuildAndDiagnose) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000010583 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10584 Diag(Var->getLocation(), diag::note_previous_decl)
10585 << Var->getDeclName();
10586 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10587 diag::note_lambda_decl);
10588 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010589 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000010590 }
10591
10592 FunctionScopesIndex--;
10593 DC = ParentDC;
10594 Explicit = false;
10595 } while (!Var->getDeclContext()->Equals(DC));
10596
Douglas Gregor999713e2012-02-18 09:37:24 +000010597 // Walk back down the scope stack, computing the type of the capture at
10598 // each step, checking type-specific requirements, and adding captures if
10599 // requested.
10600 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10601 ++I) {
10602 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000010603
Douglas Gregor999713e2012-02-18 09:37:24 +000010604 // Compute the type of the capture and of a reference to the capture within
10605 // this scope.
10606 if (isa<BlockScopeInfo>(CSI)) {
10607 Expr *CopyExpr = 0;
10608 bool ByRef = false;
10609
10610 // Blocks are not allowed to capture arrays.
10611 if (CaptureType->isArrayType()) {
10612 if (BuildAndDiagnose) {
10613 Diag(Loc, diag::err_ref_array_type);
10614 Diag(Var->getLocation(), diag::note_previous_decl)
10615 << Var->getDeclName();
10616 }
10617 return true;
10618 }
10619
John McCall100c6492012-03-30 05:23:48 +000010620 // Forbid the block-capture of autoreleasing variables.
10621 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10622 if (BuildAndDiagnose) {
10623 Diag(Loc, diag::err_arc_autoreleasing_capture)
10624 << /*block*/ 0;
10625 Diag(Var->getLocation(), diag::note_previous_decl)
10626 << Var->getDeclName();
10627 }
10628 return true;
10629 }
10630
Douglas Gregor999713e2012-02-18 09:37:24 +000010631 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10632 // Block capture by reference does not change the capture or
10633 // declaration reference types.
10634 ByRef = true;
10635 } else {
10636 // Block capture by copy introduces 'const'.
10637 CaptureType = CaptureType.getNonReferenceType().withConst();
10638 DeclRefType = CaptureType;
10639
David Blaikie4e4d0842012-03-11 07:00:24 +000010640 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregor999713e2012-02-18 09:37:24 +000010641 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10642 // The capture logic needs the destructor, so make sure we mark it.
10643 // Usually this is unnecessary because most local variables have
10644 // their destructors marked at declaration time, but parameters are
10645 // an exception because it's technically only the call site that
10646 // actually requires the destructor.
10647 if (isa<ParmVarDecl>(Var))
10648 FinalizeVarWithDestructor(Var, Record);
10649
10650 // According to the blocks spec, the capture of a variable from
10651 // the stack requires a const copy constructor. This is not true
10652 // of the copy/move done to move a __block variable to the heap.
John McCallf4b88a42012-03-10 09:33:50 +000010653 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregor999713e2012-02-18 09:37:24 +000010654 DeclRefType.withConst(),
10655 VK_LValue, Loc);
10656 ExprResult Result
10657 = PerformCopyInitialization(
10658 InitializedEntity::InitializeBlock(Var->getLocation(),
10659 CaptureType, false),
10660 Loc, Owned(DeclRef));
10661
10662 // Build a full-expression copy expression if initialization
10663 // succeeded and used a non-trivial constructor. Recover from
10664 // errors by pretending that the copy isn't necessary.
10665 if (!Result.isInvalid() &&
10666 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10667 ->isTrivial()) {
10668 Result = MaybeCreateExprWithCleanups(Result);
10669 CopyExpr = Result.take();
10670 }
10671 }
10672 }
10673 }
10674
10675 // Actually capture the variable.
10676 if (BuildAndDiagnose)
10677 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10678 SourceLocation(), CaptureType, CopyExpr);
10679 Nested = true;
10680 continue;
10681 }
Douglas Gregor68932842012-02-18 05:51:20 +000010682
Douglas Gregor999713e2012-02-18 09:37:24 +000010683 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10684
10685 // Determine whether we are capturing by reference or by value.
10686 bool ByRef = false;
10687 if (I == N - 1 && Kind != TryCapture_Implicit) {
10688 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010689 } else {
Douglas Gregor999713e2012-02-18 09:37:24 +000010690 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedmanb942cb22012-02-03 22:47:37 +000010691 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010692
10693 // Compute the type of the field that will capture this variable.
10694 if (ByRef) {
10695 // C++11 [expr.prim.lambda]p15:
10696 // An entity is captured by reference if it is implicitly or
10697 // explicitly captured but not captured by copy. It is
10698 // unspecified whether additional unnamed non-static data
10699 // members are declared in the closure type for entities
10700 // captured by reference.
10701 //
10702 // FIXME: It is not clear whether we want to build an lvalue reference
10703 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10704 // to do the former, while EDG does the latter. Core issue 1249 will
10705 // clarify, but for now we follow GCC because it's a more permissive and
10706 // easily defensible position.
10707 CaptureType = Context.getLValueReferenceType(DeclRefType);
10708 } else {
10709 // C++11 [expr.prim.lambda]p14:
10710 // For each entity captured by copy, an unnamed non-static
10711 // data member is declared in the closure type. The
10712 // declaration order of these members is unspecified. The type
10713 // of such a data member is the type of the corresponding
10714 // captured entity if the entity is not a reference to an
10715 // object, or the referenced type otherwise. [Note: If the
10716 // captured entity is a reference to a function, the
10717 // corresponding data member is also a reference to a
10718 // function. - end note ]
10719 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10720 if (!RefType->getPointeeType()->isFunctionType())
10721 CaptureType = RefType->getPointeeType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010722 }
John McCall100c6492012-03-30 05:23:48 +000010723
10724 // Forbid the lambda copy-capture of autoreleasing variables.
10725 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10726 if (BuildAndDiagnose) {
10727 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10728 Diag(Var->getLocation(), diag::note_previous_decl)
10729 << Var->getDeclName();
10730 }
10731 return true;
10732 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010733 }
10734
Douglas Gregor999713e2012-02-18 09:37:24 +000010735 // Capture this variable in the lambda.
10736 Expr *CopyExpr = 0;
10737 if (BuildAndDiagnose) {
10738 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000010739 DeclRefType, Loc,
10740 I == N-1);
Douglas Gregor999713e2012-02-18 09:37:24 +000010741 if (!Result.isInvalid())
10742 CopyExpr = Result.take();
10743 }
10744
10745 // Compute the type of a reference to this captured variable.
10746 if (ByRef)
10747 DeclRefType = CaptureType.getNonReferenceType();
10748 else {
10749 // C++ [expr.prim.lambda]p5:
10750 // The closure type for a lambda-expression has a public inline
10751 // function call operator [...]. This function call operator is
10752 // declared const (9.3.1) if and only if the lambda-expression’s
10753 // parameter-declaration-clause is not followed by mutable.
10754 DeclRefType = CaptureType.getNonReferenceType();
10755 if (!LSI->Mutable && !CaptureType->isReferenceType())
10756 DeclRefType.addConst();
10757 }
10758
10759 // Add the capture.
10760 if (BuildAndDiagnose)
10761 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10762 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010763 Nested = true;
10764 }
Douglas Gregor999713e2012-02-18 09:37:24 +000010765
10766 return false;
10767}
10768
10769bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10770 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10771 QualType CaptureType;
10772 QualType DeclRefType;
10773 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10774 /*BuildAndDiagnose=*/true, CaptureType,
10775 DeclRefType);
10776}
10777
10778QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10779 QualType CaptureType;
10780 QualType DeclRefType;
10781
10782 // Determine whether we can capture this variable.
10783 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10784 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10785 return QualType();
10786
10787 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010788}
10789
Eli Friedmand2cce132012-02-02 23:15:15 +000010790static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10791 SourceLocation Loc) {
10792 // Keep track of used but undefined variables.
Eli Friedman0cc5d402012-02-04 00:54:05 +000010793 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010794 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman0cc5d402012-02-04 00:54:05 +000010795 Var->getLinkage() != ExternalLinkage &&
10796 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010797 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10798 if (old.isInvalid()) old = Loc;
10799 }
10800
Douglas Gregor999713e2012-02-18 09:37:24 +000010801 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000010802
Eli Friedmand2cce132012-02-02 23:15:15 +000010803 Var->setUsed(true);
10804}
10805
10806void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10807 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10808 // an object that satisfies the requirements for appearing in a
10809 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10810 // is immediately applied." This function handles the lvalue-to-rvalue
10811 // conversion part.
10812 MaybeODRUseExprs.erase(E->IgnoreParens());
10813}
10814
Eli Friedmanac626012012-02-29 03:16:56 +000010815ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10816 if (!Res.isUsable())
10817 return Res;
10818
10819 // If a constant-expression is a reference to a variable where we delay
10820 // deciding whether it is an odr-use, just assume we will apply the
10821 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10822 // (a non-type template argument), we have special handling anyway.
10823 UpdateMarkingForLValueToRValue(Res.get());
10824 return Res;
10825}
10826
Eli Friedmand2cce132012-02-02 23:15:15 +000010827void Sema::CleanupVarDeclMarking() {
10828 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10829 e = MaybeODRUseExprs.end();
10830 i != e; ++i) {
10831 VarDecl *Var;
10832 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000010833 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010834 Var = cast<VarDecl>(DRE->getDecl());
10835 Loc = DRE->getLocation();
10836 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10837 Var = cast<VarDecl>(ME->getMemberDecl());
10838 Loc = ME->getMemberLoc();
10839 } else {
10840 llvm_unreachable("Unexpcted expression");
10841 }
10842
10843 MarkVarDeclODRUsed(*this, Var, Loc);
10844 }
10845
10846 MaybeODRUseExprs.clear();
10847}
10848
10849// Mark a VarDecl referenced, and perform the necessary handling to compute
10850// odr-uses.
10851static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10852 VarDecl *Var, Expr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010853 Var->setReferenced();
10854
Eli Friedmand2cce132012-02-02 23:15:15 +000010855 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010856 return;
10857
10858 // Implicit instantiation of static data members of class templates.
Richard Smith37ce0102012-02-15 02:42:50 +000010859 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010860 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10861 assert(MSInfo && "Missing member specialization information?");
Richard Smith37ce0102012-02-15 02:42:50 +000010862 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10863 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010864 (!AlreadyInstantiated ||
10865 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smith37ce0102012-02-15 02:42:50 +000010866 if (!AlreadyInstantiated) {
10867 // This is a modification of an existing AST node. Notify listeners.
10868 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10869 L->StaticDataMemberInstantiated(Var);
10870 MSInfo->setPointOfInstantiation(Loc);
10871 }
10872 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010873 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedman5f2987c2012-02-02 03:46:19 +000010874 // Do not defer instantiations of variables which could be used in a
10875 // constant expression.
Richard Smith37ce0102012-02-15 02:42:50 +000010876 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010877 else
Richard Smith37ce0102012-02-15 02:42:50 +000010878 SemaRef.PendingInstantiations.push_back(
10879 std::make_pair(Var, PointOfInstantiation));
Eli Friedman5f2987c2012-02-02 03:46:19 +000010880 }
10881 }
10882
Eli Friedmand2cce132012-02-02 23:15:15 +000010883 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10884 // an object that satisfies the requirements for appearing in a
10885 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10886 // is immediately applied." We check the first part here, and
10887 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10888 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith16581332012-03-02 04:14:40 +000010889 // C++03 depends on whether we get the C++03 version correct. This does not
10890 // apply to references, since they are not objects.
Eli Friedmand2cce132012-02-02 23:15:15 +000010891 const VarDecl *DefVD;
Richard Smith16581332012-03-02 04:14:40 +000010892 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +000010893 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedmand2cce132012-02-02 23:15:15 +000010894 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10895 SemaRef.MaybeODRUseExprs.insert(E);
10896 else
10897 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10898}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010899
Eli Friedmand2cce132012-02-02 23:15:15 +000010900/// \brief Mark a variable referenced, and check whether it is odr-used
10901/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10902/// used directly for normal expressions referring to VarDecl.
10903void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10904 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010905}
10906
10907static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10908 Decl *D, Expr *E) {
Eli Friedmand2cce132012-02-02 23:15:15 +000010909 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10910 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10911 return;
10912 }
10913
Eli Friedman5f2987c2012-02-02 03:46:19 +000010914 SemaRef.MarkAnyDeclReferenced(Loc, D);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010915
10916 // If this is a call to a method via a cast, also mark the method in the
10917 // derived class used in case codegen can devirtualize the call.
10918 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10919 if (!ME)
10920 return;
10921 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10922 if (!MD)
10923 return;
10924 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000010925 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010926 if (!MostDerivedClassDecl)
10927 return;
10928 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Rafael Espindola0713d992012-06-27 17:44:39 +000010929 if (!DM)
10930 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000010931 SemaRef.MarkAnyDeclReferenced(Loc, DM);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010932}
Eli Friedman5f2987c2012-02-02 03:46:19 +000010933
Eli Friedman5f2987c2012-02-02 03:46:19 +000010934/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10935void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10936 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10937}
10938
10939/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10940void Sema::MarkMemberReferenced(MemberExpr *E) {
10941 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10942}
10943
Douglas Gregor73d90922012-02-10 09:26:04 +000010944/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedman5f2987c2012-02-02 03:46:19 +000010945/// marks the declaration referenced, and performs odr-use checking for functions
10946/// and variables. This method should not be used when building an normal
10947/// expression which refers to a variable.
10948void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10949 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10950 MarkVariableReferenced(Loc, VD);
10951 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10952 MarkFunctionReferenced(Loc, FD);
10953 else
10954 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000010955}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010956
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010957namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010958 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010959 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010960 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010961 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10962 Sema &S;
10963 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010964
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010965 public:
10966 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010967
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010968 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010969
10970 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10971 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010972 };
10973}
10974
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010975bool MarkReferencedDecls::TraverseTemplateArgument(
10976 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010977 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000010978 if (Decl *D = Arg.getAsDecl())
10979 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010980 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010981
10982 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010983}
10984
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010985bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010986 if (ClassTemplateSpecializationDecl *Spec
10987 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10988 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010989 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010990 }
10991
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010992 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010993}
10994
10995void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10996 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010997 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010998}
10999
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011000namespace {
11001 /// \brief Helper class that marks all of the declarations referenced by
11002 /// potentially-evaluated subexpressions as "referenced".
11003 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11004 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011005 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011006
11007 public:
11008 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11009
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011010 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11011 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011012
11013 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011014 // If we were asked not to visit local variables, don't.
11015 if (SkipLocalVariables) {
11016 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11017 if (VD->hasLocalStorage())
11018 return;
11019 }
11020
Eli Friedman5f2987c2012-02-02 03:46:19 +000011021 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011022 }
11023
11024 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011025 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011026 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011027 }
11028
John McCall80ee6e82011-11-10 05:35:25 +000011029 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011030 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000011031 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11032 Visit(E->getSubExpr());
11033 }
11034
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011035 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011036 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011037 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011038 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011039 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011040 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011041 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000011042
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011043 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11044 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000011045 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011046 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11047 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11048 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000011049 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000011050 S.LookupDestructor(Record));
11051 }
11052
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011053 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011054 }
11055
11056 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011057 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000011058 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011059 }
11060
Douglas Gregor102ff972010-10-19 17:17:35 +000011061 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11062 Visit(E->getExpr());
11063 }
Eli Friedmand2cce132012-02-02 23:15:15 +000011064
11065 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11066 Inherited::VisitImplicitCastExpr(E);
11067
11068 if (E->getCastKind() == CK_LValueToRValue)
11069 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11070 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011071 };
11072}
11073
11074/// \brief Mark any declarations that appear within this expression or any
11075/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000011076///
11077/// \param SkipLocalVariables If true, don't mark local variables as
11078/// 'referenced'.
11079void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11080 bool SkipLocalVariables) {
11081 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011082}
11083
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011084/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11085/// of the program being compiled.
11086///
11087/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011088/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011089/// possibility that the code will actually be executable. Code in sizeof()
11090/// expressions, code used only during overload resolution, etc., are not
11091/// potentially evaluated. This routine will suppress such diagnostics or,
11092/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011093/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011094/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011095///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011096/// This routine should be used for all diagnostics that describe the run-time
11097/// behavior of a program, such as passing a non-POD value through an ellipsis.
11098/// Failure to do so will likely result in spurious diagnostics or failures
11099/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000011100bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011101 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000011102 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011103 case Unevaluated:
11104 // The argument will never be evaluated, so don't complain.
11105 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011106
Richard Smithf6702a32011-12-20 02:08:33 +000011107 case ConstantEvaluated:
11108 // Relevant diagnostics should be produced by constant evaluation.
11109 break;
11110
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011111 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000011112 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000011113 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000011114 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000011115 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000011116 }
11117 else
11118 Diag(Loc, PD);
11119
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011120 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000011121 }
11122
11123 return false;
11124}
11125
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011126bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11127 CallExpr *CE, FunctionDecl *FD) {
11128 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11129 return false;
11130
Richard Smith76f3f692012-02-22 02:04:18 +000011131 // If we're inside a decltype's expression, don't check for a valid return
11132 // type or construct temporaries until we know whether this is the last call.
11133 if (ExprEvalContexts.back().IsDecltype) {
11134 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11135 return false;
11136 }
11137
Douglas Gregorf502d8e2012-05-04 16:48:41 +000011138 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000011139 FunctionDecl *FD;
11140 CallExpr *CE;
11141
11142 public:
11143 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11144 : FD(FD), CE(CE) { }
11145
11146 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11147 if (!FD) {
11148 S.Diag(Loc, diag::err_call_incomplete_return)
11149 << T << CE->getSourceRange();
11150 return;
11151 }
11152
11153 S.Diag(Loc, diag::err_call_function_incomplete_return)
11154 << CE->getSourceRange() << FD->getDeclName() << T;
11155 S.Diag(FD->getLocation(),
11156 diag::note_function_with_incomplete_return_type_declared_here)
11157 << FD->getDeclName();
11158 }
11159 } Diagnoser(FD, CE);
11160
11161 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000011162 return true;
11163
11164 return false;
11165}
11166
Douglas Gregor92c3a042011-01-19 16:50:08 +000011167// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000011168// will prevent this condition from triggering, which is what we want.
11169void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11170 SourceLocation Loc;
11171
John McCalla52ef082009-11-11 02:41:58 +000011172 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000011173 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000011174
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011175 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011176 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000011177 return;
11178
Douglas Gregor92c3a042011-01-19 16:50:08 +000011179 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11180
John McCallc8d8ac52009-11-12 00:06:05 +000011181 // Greylist some idioms by putting them into a warning subcategory.
11182 if (ObjCMessageExpr *ME
11183 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11184 Selector Sel = ME->getSelector();
11185
John McCallc8d8ac52009-11-12 00:06:05 +000011186 // self = [<foo> init...]
Douglas Gregorc737acb2011-09-27 16:10:05 +000011187 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000011188 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11189
11190 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000011191 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000011192 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11193 }
John McCalla52ef082009-11-11 02:41:58 +000011194
John McCall5a881bb2009-10-12 21:59:07 +000011195 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000011196 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000011197 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000011198 return;
11199
Douglas Gregor92c3a042011-01-19 16:50:08 +000011200 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000011201 Loc = Op->getOperatorLoc();
11202 } else {
11203 // Not an assignment.
11204 return;
11205 }
11206
Douglas Gregor55b38842010-04-14 16:09:52 +000011207 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000011208
Daniel Dunbar96a00142012-03-09 18:35:03 +000011209 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011210 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11211 Diag(Loc, diag::note_condition_assign_silence)
11212 << FixItHint::CreateInsertion(Open, "(")
11213 << FixItHint::CreateInsertion(Close, ")");
11214
Douglas Gregor92c3a042011-01-19 16:50:08 +000011215 if (IsOrAssign)
11216 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11217 << FixItHint::CreateReplacement(Loc, "!=");
11218 else
11219 Diag(Loc, diag::note_condition_assign_to_comparison)
11220 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000011221}
11222
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011223/// \brief Redundant parentheses over an equality comparison can indicate
11224/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000011225void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011226 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000011227 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011228 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11229 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011230 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000011231 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000011232 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000011233
Richard Trieuccd891a2011-09-09 01:45:06 +000011234 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011235
11236 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000011237 if (opE->getOpcode() == BO_EQ &&
11238 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11239 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011240 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000011241
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011242 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000011243 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000011244 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000011245 << FixItHint::CreateRemoval(ParenERange.getBegin())
11246 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000011247 Diag(Loc, diag::note_equality_comparison_to_assign)
11248 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011249 }
11250}
11251
John Wiegley429bb272011-04-08 18:41:53 +000011252ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000011253 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000011254 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11255 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000011256
John McCall864c0412011-04-26 20:42:42 +000011257 ExprResult result = CheckPlaceholderExpr(E);
11258 if (result.isInvalid()) return ExprError();
11259 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000011260
John McCall864c0412011-04-26 20:42:42 +000011261 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011262 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000011263 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11264
John Wiegley429bb272011-04-08 18:41:53 +000011265 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11266 if (ERes.isInvalid())
11267 return ExprError();
11268 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000011269
11270 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000011271 if (!T->isScalarType()) { // C99 6.8.4.1p1
11272 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11273 << T << E->getSourceRange();
11274 return ExprError();
11275 }
John McCall5a881bb2009-10-12 21:59:07 +000011276 }
11277
John Wiegley429bb272011-04-08 18:41:53 +000011278 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000011279}
Douglas Gregor586596f2010-05-06 17:25:47 +000011280
John McCall60d7b3a2010-08-24 06:29:42 +000011281ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011282 Expr *SubExpr) {
11283 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000011284 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011285
Richard Trieuccd891a2011-09-09 01:45:06 +000011286 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000011287}
John McCall2a984ca2010-10-12 00:20:44 +000011288
John McCall1de4d4e2011-04-07 08:22:57 +000011289namespace {
John McCall755d8492011-04-12 00:42:48 +000011290 /// A visitor for rebuilding a call to an __unknown_any expression
11291 /// to have an appropriate type.
11292 struct RebuildUnknownAnyFunction
11293 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11294
11295 Sema &S;
11296
11297 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11298
11299 ExprResult VisitStmt(Stmt *S) {
11300 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000011301 }
11302
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011303 ExprResult VisitExpr(Expr *E) {
11304 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11305 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011306 return ExprError();
11307 }
11308
11309 /// Rebuild an expression which simply semantically wraps another
11310 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011311 template <class T> ExprResult rebuildSugarExpr(T *E) {
11312 ExprResult SubResult = Visit(E->getSubExpr());
11313 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011314
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011315 Expr *SubExpr = SubResult.take();
11316 E->setSubExpr(SubExpr);
11317 E->setType(SubExpr->getType());
11318 E->setValueKind(SubExpr->getValueKind());
11319 assert(E->getObjectKind() == OK_Ordinary);
11320 return E;
John McCall755d8492011-04-12 00:42:48 +000011321 }
11322
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011323 ExprResult VisitParenExpr(ParenExpr *E) {
11324 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011325 }
11326
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011327 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11328 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011329 }
11330
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011331 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11332 ExprResult SubResult = Visit(E->getSubExpr());
11333 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000011334
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011335 Expr *SubExpr = SubResult.take();
11336 E->setSubExpr(SubExpr);
11337 E->setType(S.Context.getPointerType(SubExpr->getType()));
11338 assert(E->getValueKind() == VK_RValue);
11339 assert(E->getObjectKind() == OK_Ordinary);
11340 return E;
John McCall755d8492011-04-12 00:42:48 +000011341 }
11342
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011343 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11344 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000011345
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011346 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000011347
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011348 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000011349 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011350 !(isa<CXXMethodDecl>(VD) &&
11351 cast<CXXMethodDecl>(VD)->isInstance()))
11352 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000011353
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011354 return E;
John McCall755d8492011-04-12 00:42:48 +000011355 }
11356
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011357 ExprResult VisitMemberExpr(MemberExpr *E) {
11358 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011359 }
11360
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011361 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11362 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000011363 }
11364 };
11365}
11366
11367/// Given a function expression of unknown-any type, try to rebuild it
11368/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011369static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11370 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11371 if (Result.isInvalid()) return ExprError();
11372 return S.DefaultFunctionArrayConversion(Result.take());
John McCall755d8492011-04-12 00:42:48 +000011373}
11374
11375namespace {
John McCall379b5152011-04-11 07:02:50 +000011376 /// A visitor for rebuilding an expression of type __unknown_anytype
11377 /// into one which resolves the type directly on the referring
11378 /// expression. Strict preservation of the original source
11379 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000011380 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000011381 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000011382
11383 Sema &S;
11384
11385 /// The current destination type.
11386 QualType DestType;
11387
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011388 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11389 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000011390
John McCalla5fc4722011-04-09 22:50:59 +000011391 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000011392 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000011393 }
11394
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011395 ExprResult VisitExpr(Expr *E) {
11396 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11397 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011398 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011399 }
11400
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011401 ExprResult VisitCallExpr(CallExpr *E);
11402 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000011403
John McCalla5fc4722011-04-09 22:50:59 +000011404 /// Rebuild an expression which simply semantically wraps another
11405 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011406 template <class T> ExprResult rebuildSugarExpr(T *E) {
11407 ExprResult SubResult = Visit(E->getSubExpr());
11408 if (SubResult.isInvalid()) return ExprError();
11409 Expr *SubExpr = SubResult.take();
11410 E->setSubExpr(SubExpr);
11411 E->setType(SubExpr->getType());
11412 E->setValueKind(SubExpr->getValueKind());
11413 assert(E->getObjectKind() == OK_Ordinary);
11414 return E;
John McCalla5fc4722011-04-09 22:50:59 +000011415 }
John McCall1de4d4e2011-04-07 08:22:57 +000011416
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011417 ExprResult VisitParenExpr(ParenExpr *E) {
11418 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011419 }
11420
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011421 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11422 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000011423 }
11424
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011425 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11426 const PointerType *Ptr = DestType->getAs<PointerType>();
11427 if (!Ptr) {
11428 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11429 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011430 return ExprError();
11431 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011432 assert(E->getValueKind() == VK_RValue);
11433 assert(E->getObjectKind() == OK_Ordinary);
11434 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000011435
11436 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011437 DestType = Ptr->getPointeeType();
11438 ExprResult SubResult = Visit(E->getSubExpr());
11439 if (SubResult.isInvalid()) return ExprError();
11440 E->setSubExpr(SubResult.take());
11441 return E;
John McCall755d8492011-04-12 00:42:48 +000011442 }
11443
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011444 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000011445
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011446 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000011447
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011448 ExprResult VisitMemberExpr(MemberExpr *E) {
11449 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000011450 }
John McCalla5fc4722011-04-09 22:50:59 +000011451
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011452 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11453 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000011454 }
11455 };
11456}
11457
John McCall379b5152011-04-11 07:02:50 +000011458/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011459ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11460 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011461
11462 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000011463 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000011464 FK_FunctionPointer,
11465 FK_BlockPointer
11466 };
11467
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011468 FnKind Kind;
11469 QualType CalleeType = CalleeExpr->getType();
11470 if (CalleeType == S.Context.BoundMemberTy) {
11471 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11472 Kind = FK_MemberFunction;
11473 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11474 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11475 CalleeType = Ptr->getPointeeType();
11476 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000011477 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011478 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11479 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000011480 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011481 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000011482
11483 // Verify that this is a legal result type of a function.
11484 if (DestType->isArrayType() || DestType->isFunctionType()) {
11485 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011486 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000011487 diagID = diag::err_block_returning_array_function;
11488
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011489 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000011490 << DestType->isFunctionType() << DestType;
11491 return ExprError();
11492 }
11493
11494 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011495 E->setType(DestType.getNonLValueExprType(S.Context));
11496 E->setValueKind(Expr::getValueKindForType(DestType));
11497 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011498
11499 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011500 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall379b5152011-04-11 07:02:50 +000011501 DestType = S.Context.getFunctionType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011502 Proto->arg_type_begin(),
11503 Proto->getNumArgs(),
11504 Proto->getExtProtoInfo());
John McCall379b5152011-04-11 07:02:50 +000011505 else
11506 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011507 FnType->getExtInfo());
John McCall379b5152011-04-11 07:02:50 +000011508
11509 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011510 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000011511 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011512 // Nothing to do.
11513 break;
11514
11515 case FK_FunctionPointer:
11516 DestType = S.Context.getPointerType(DestType);
11517 break;
11518
11519 case FK_BlockPointer:
11520 DestType = S.Context.getBlockPointerType(DestType);
11521 break;
11522 }
11523
11524 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011525 ExprResult CalleeResult = Visit(CalleeExpr);
11526 if (!CalleeResult.isUsable()) return ExprError();
11527 E->setCallee(CalleeResult.take());
John McCall379b5152011-04-11 07:02:50 +000011528
11529 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011530 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011531}
11532
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011533ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011534 // Verify that this is a legal result type of a call.
11535 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011536 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000011537 << DestType->isFunctionType() << DestType;
11538 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011539 }
11540
John McCall48218c62011-07-13 17:56:40 +000011541 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011542 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11543 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11544 Method->setResultType(DestType);
John McCall48218c62011-07-13 17:56:40 +000011545 }
John McCall755d8492011-04-12 00:42:48 +000011546
John McCall379b5152011-04-11 07:02:50 +000011547 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011548 E->setType(DestType.getNonReferenceType());
11549 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011550
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011551 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000011552}
11553
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011554ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000011555 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000011556 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000011557 assert(E->getValueKind() == VK_RValue);
11558 assert(E->getObjectKind() == OK_Ordinary);
11559
11560 E->setType(DestType);
11561
11562 // Rebuild the sub-expression as the pointee (function) type.
11563 DestType = DestType->castAs<PointerType>()->getPointeeType();
11564
11565 ExprResult Result = Visit(E->getSubExpr());
11566 if (!Result.isUsable()) return ExprError();
11567
11568 E->setSubExpr(Result.take());
11569 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011570 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000011571 assert(E->getValueKind() == VK_RValue);
11572 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000011573
Sean Callanance9c8312012-03-06 21:34:12 +000011574 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000011575
Sean Callanance9c8312012-03-06 21:34:12 +000011576 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011577
Sean Callanance9c8312012-03-06 21:34:12 +000011578 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11579 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000011580
Sean Callanance9c8312012-03-06 21:34:12 +000011581 ExprResult Result = Visit(E->getSubExpr());
11582 if (!Result.isUsable()) return ExprError();
11583
11584 E->setSubExpr(Result.take());
11585 return S.Owned(E);
Sean Callananba66c6c2012-03-06 23:12:57 +000011586 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000011587 llvm_unreachable("Unhandled cast type!");
11588 }
John McCall379b5152011-04-11 07:02:50 +000011589}
11590
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011591ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11592 ExprValueKind ValueKind = VK_LValue;
11593 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000011594
11595 // We know how to make this work for certain kinds of decls:
11596
11597 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011598 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11599 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11600 DestType = Ptr->getPointeeType();
11601 ExprResult Result = resolveDecl(E, VD);
11602 if (Result.isInvalid()) return ExprError();
11603 return S.ImpCastExprToType(Result.take(), Type,
John McCalla19950e2011-08-10 04:12:23 +000011604 CK_FunctionToPointerDecay, VK_RValue);
11605 }
11606
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011607 if (!Type->isFunctionType()) {
11608 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11609 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000011610 return ExprError();
11611 }
John McCall379b5152011-04-11 07:02:50 +000011612
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011613 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11614 if (MD->isInstance()) {
11615 ValueKind = VK_RValue;
11616 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000011617 }
11618
John McCall379b5152011-04-11 07:02:50 +000011619 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000011620 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011621 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000011622
11623 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011624 } else if (isa<VarDecl>(VD)) {
11625 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11626 Type = RefTy->getPointeeType();
11627 } else if (Type->isFunctionType()) {
11628 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11629 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000011630 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011631 }
11632
11633 // - nothing else
11634 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011635 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11636 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011637 return ExprError();
11638 }
11639
Richard Trieu5e4c80b2011-09-09 03:59:41 +000011640 VD->setType(DestType);
11641 E->setType(Type);
11642 E->setValueKind(ValueKind);
11643 return S.Owned(E);
John McCall379b5152011-04-11 07:02:50 +000011644}
11645
John McCall1de4d4e2011-04-07 08:22:57 +000011646/// Check a cast of an unknown-any type. We intentionally only
11647/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000011648ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11649 Expr *CastExpr, CastKind &CastKind,
11650 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011651 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000011652 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000011653 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011654
Richard Trieuccd891a2011-09-09 01:45:06 +000011655 CastExpr = result.take();
11656 VK = CastExpr->getValueKind();
11657 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000011658
Richard Trieuccd891a2011-09-09 01:45:06 +000011659 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011660}
11661
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000011662ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11663 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11664}
11665
Richard Trieuccd891a2011-09-09 01:45:06 +000011666static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11667 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000011668 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011669 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000011670 E = E->IgnoreParenImpCasts();
11671 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11672 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011673 diagID = diag::err_uncasted_call_of_unknown_any;
11674 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011675 break;
John McCall379b5152011-04-11 07:02:50 +000011676 }
John McCall1de4d4e2011-04-07 08:22:57 +000011677 }
11678
John McCall379b5152011-04-11 07:02:50 +000011679 SourceLocation loc;
11680 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000011681 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011682 loc = ref->getLocation();
11683 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011684 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011685 loc = mem->getMemberLoc();
11686 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000011687 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000011688 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000011689 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000011690 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000011691 if (!d) {
11692 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11693 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11694 << orig->getSourceRange();
11695 return ExprError();
11696 }
John McCall379b5152011-04-11 07:02:50 +000011697 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000011698 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11699 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000011700 return ExprError();
11701 }
11702
11703 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011704
11705 // Never recoverable.
11706 return ExprError();
11707}
11708
John McCall2a984ca2010-10-12 00:20:44 +000011709/// Check for operands with placeholder types and complain if found.
11710/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011711ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall5acb0c92011-10-17 18:40:02 +000011712 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11713 if (!placeholderType) return Owned(E);
11714
11715 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000011716
John McCall1de4d4e2011-04-07 08:22:57 +000011717 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000011718 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000011719 // Try to resolve a single function template specialization.
11720 // This is obligatory.
11721 ExprResult result = Owned(E);
11722 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11723 return result;
11724
11725 // If that failed, try to recover with a call.
11726 } else {
11727 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11728 /*complain*/ true);
11729 return result;
11730 }
11731 }
John McCall1de4d4e2011-04-07 08:22:57 +000011732
John McCall864c0412011-04-26 20:42:42 +000011733 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000011734 case BuiltinType::BoundMember: {
John McCall6dbba4f2011-10-11 23:14:30 +000011735 ExprResult result = Owned(E);
11736 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11737 /*complain*/ true);
11738 return result;
John McCall5acb0c92011-10-17 18:40:02 +000011739 }
11740
11741 // ARC unbridged casts.
11742 case BuiltinType::ARCUnbridgedCast: {
11743 Expr *realCast = stripARCUnbridgedCast(E);
11744 diagnoseARCUnbridgedCast(realCast);
11745 return Owned(realCast);
11746 }
John McCall864c0412011-04-26 20:42:42 +000011747
John McCall1de4d4e2011-04-07 08:22:57 +000011748 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000011749 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000011750 return diagnoseUnknownAnyExpr(*this, E);
11751
John McCall3c3b7f92011-10-25 17:37:35 +000011752 // Pseudo-objects.
11753 case BuiltinType::PseudoObject:
11754 return checkPseudoObjectRValue(E);
11755
John McCalle0a22d02011-10-18 21:02:43 +000011756 // Everything else should be impossible.
11757#define BUILTIN_TYPE(Id, SingletonId) \
11758 case BuiltinType::Id:
11759#define PLACEHOLDER_TYPE(Id, SingletonId)
11760#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000011761 break;
11762 }
11763
11764 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000011765}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011766
Richard Trieuccd891a2011-09-09 01:45:06 +000011767bool Sema::CheckCaseExpression(Expr *E) {
11768 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000011769 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000011770 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11771 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000011772 return false;
11773}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011774
11775/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11776ExprResult
11777Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11778 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11779 "Unknown Objective-C Boolean value!");
11780 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian93a49942012-04-16 21:03:30 +000011781 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremenekebcb57a2012-03-06 20:05:56 +000011782}