blob: d18aeab57a0af875b777eb9842ae289cba4e4e0c [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "TreeTransform.h"
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000016#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/ASTContext.h"
Faisal Valic00e4192013-11-07 05:17:06 +000018#include "clang/AST/ASTLambda.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000034#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall19510852010-08-20 18:27:03 +000035#include "clang/Sema/DeclSpec.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "clang/Sema/DelayedDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000037#include "clang/Sema/Designator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
John McCall19510852010-08-20 18:27:03 +000041#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000042#include "clang/Sema/ScopeInfo.h"
Anna Zaks67221552011-07-28 19:51:27 +000043#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000044#include "clang/Sema/Template.h"
Stephen Hines176edba2014-12-01 14:53:08 -080045#include "llvm/Support/ConvertUTF.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000047using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000048
Sebastian Redl14b0c192011-09-24 17:48:00 +000049/// \brief Determine whether the use of this declaration is valid, without
50/// emitting diagnostics.
51bool Sema::CanUseDecl(NamedDecl *D) {
52 // See if this is an auto-typed variable whose initializer we are parsing.
53 if (ParsingInitForAutoVars.count(D))
54 return false;
55
56 // See if this is a deleted function.
57 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
58 if (FD->isDeleted())
59 return false;
Richard Smith60e141e2013-05-04 07:00:32 +000060
61 // If the function has a deduced return type, and we can't deduce it,
62 // then we can't use it either.
Stephen Hines176edba2014-12-01 14:53:08 -080063 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070064 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
Richard Smith60e141e2013-05-04 07:00:32 +000065 return false;
Sebastian Redl14b0c192011-09-24 17:48:00 +000066 }
Sebastian Redl28bdb142011-10-16 18:19:16 +000067
68 // See if this function is unavailable.
69 if (D->getAvailability() == AR_Unavailable &&
70 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
71 return false;
72
Sebastian Redl14b0c192011-09-24 17:48:00 +000073 return true;
74}
David Chisnall0f436562009-08-17 16:35:33 +000075
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000076static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
77 // Warn if this is used but marked unused.
78 if (D->hasAttr<UnusedAttr>()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070079 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
80 if (DC && !DC->hasAttr<UnusedAttr>())
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +000081 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
82 }
83}
84
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070085static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
86 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
87 if (!OMD)
88 return false;
89 const ObjCInterfaceDecl *OID = OMD->getClassInterface();
90 if (!OID)
91 return false;
92
93 for (const ObjCCategoryDecl *Cat : OID->visible_categories())
94 if (ObjCMethodDecl *CatMeth =
95 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
96 if (!CatMeth->hasAttr<AvailabilityAttr>())
97 return true;
98 return false;
99}
100
101static AvailabilityResult
102DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
103 const ObjCInterfaceDecl *UnknownObjCClass,
104 bool ObjCPropertyAccess) {
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000105 // See if this declaration is unavailable or deprecated.
106 std::string Message;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700107
108 // Forward class declarations get their attributes from their definition.
109 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
110 if (IDecl->getDefinition())
111 D = IDecl->getDefinition();
112 }
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000113 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000114 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
115 if (Result == AR_Available) {
116 const DeclContext *DC = ECD->getDeclContext();
117 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
118 Result = TheEnumDecl->getAvailability(&Message);
119 }
Jordan Rose04bec392012-10-10 16:42:54 +0000120
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700121 const ObjCPropertyDecl *ObjCPDecl = nullptr;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700122 if (Result == AR_Deprecated || Result == AR_Unavailable ||
123 AR_NotYetIntroduced) {
Jordan Rose04bec392012-10-10 16:42:54 +0000124 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
125 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700126 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
Jordan Rose04bec392012-10-10 16:42:54 +0000127 if (PDeclResult == Result)
128 ObjCPDecl = PD;
129 }
Fariborz Jahanianfd090882012-09-21 20:46:37 +0000130 }
Jordan Rose04bec392012-10-10 16:42:54 +0000131 }
Fariborz Jahanian39b4fc82011-11-28 19:45:58 +0000132
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000133 switch (Result) {
134 case AR_Available:
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000135 break;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700136
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000137 case AR_Deprecated:
Stephen Hines651f13c2014-04-23 16:59:28 -0700138 if (S.getCurContextAvailability() != AR_Deprecated)
139 S.EmitAvailabilityWarning(Sema::AD_Deprecation,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700140 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
141 ObjCPropertyAccess);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000142 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700143
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700144 case AR_NotYetIntroduced: {
145 // Don't do this for enums, they can't be redeclared.
146 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
147 break;
148
149 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
150 // Objective-C method declarations in categories are not modelled as
151 // redeclarations, so manually look for a redeclaration in a category
152 // if necessary.
153 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
154 Warn = false;
155 // In general, D will point to the most recent redeclaration. However,
156 // for `@class A;` decls, this isn't true -- manually go through the
157 // redecl chain in that case.
158 if (Warn && isa<ObjCInterfaceDecl>(D))
159 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
160 Redecl = Redecl->getPreviousDecl())
161 if (!Redecl->hasAttr<AvailabilityAttr>() ||
162 Redecl->getAttr<AvailabilityAttr>()->isInherited())
163 Warn = false;
164
165 if (Warn)
166 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
167 UnknownObjCClass, ObjCPDecl,
168 ObjCPropertyAccess);
169 break;
170 }
171
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000172 case AR_Unavailable:
Stephen Hines651f13c2014-04-23 16:59:28 -0700173 if (S.getCurContextAvailability() != AR_Unavailable)
174 S.EmitAvailabilityWarning(Sema::AD_Unavailable,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700175 D, Message, Loc, UnknownObjCClass, ObjCPDecl,
176 ObjCPropertyAccess);
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000177 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700178
Fariborz Jahanian0f32caf2011-09-29 22:45:21 +0000179 }
180 return Result;
181}
182
Eli Friedmanc4ef9482013-07-18 23:29:14 +0000183/// \brief Emit a note explaining that this function is deleted.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000184void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +0000185 assert(Decl->isDeleted());
186
Richard Smith6c4c36c2012-03-30 20:53:28 +0000187 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
188
Eli Friedmanc4ef9482013-07-18 23:29:14 +0000189 if (Method && Method->isDeleted() && Method->isDefaulted()) {
Richard Smith5bdaac52012-04-02 20:59:25 +0000190 // If the method was explicitly defaulted, point at that declaration.
191 if (!Method->isImplicit())
192 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
193
194 // Try to diagnose why this special member function was implicitly
195 // deleted. This might fail, if that reason no longer applies.
Richard Smith6c4c36c2012-03-30 20:53:28 +0000196 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +0000197 if (CSM != CXXInvalid)
198 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
199
200 return;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000201 }
202
Eli Friedmanc4ef9482013-07-18 23:29:14 +0000203 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
204 if (CXXConstructorDecl *BaseCD =
205 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
206 Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
207 if (BaseCD->isDeleted()) {
208 NoteDeletedFunction(BaseCD);
209 } else {
210 // FIXME: An explanation of why exactly it can't be inherited
211 // would be nice.
212 Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
213 }
214 return;
215 }
216 }
217
Stephen Hines651f13c2014-04-23 16:59:28 -0700218 Diag(Decl->getLocation(), diag::note_availability_specified_here)
219 << Decl << true;
Richard Smith6c4c36c2012-03-30 20:53:28 +0000220}
221
Jordan Rose0eb3f452012-06-18 22:09:19 +0000222/// \brief Determine whether a FunctionDecl was ever declared with an
223/// explicit storage class.
224static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700225 for (auto I : D->redecls()) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000226 if (I->getStorageClass() != SC_None)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000227 return true;
228 }
229 return false;
230}
231
232/// \brief Check whether we're in an extern inline function and referring to a
Jordan Rose33c0f372012-06-20 18:50:06 +0000233/// variable or function with internal linkage (C11 6.7.4p3).
Jordan Rose0eb3f452012-06-18 22:09:19 +0000234///
Jordan Rose0eb3f452012-06-18 22:09:19 +0000235/// This is only a warning because we used to silently accept this code, but
Jordan Rose33c0f372012-06-20 18:50:06 +0000236/// in many cases it will not behave correctly. This is not enabled in C++ mode
237/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
238/// and so while there may still be user mistakes, most of the time we can't
239/// prove that there are errors.
Jordan Rose0eb3f452012-06-18 22:09:19 +0000240static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
241 const NamedDecl *D,
242 SourceLocation Loc) {
Jordan Rose33c0f372012-06-20 18:50:06 +0000243 // This is disabled under C++; there are too many ways for this to fire in
244 // contexts where the warning is a false positive, or where it is technically
245 // correct but benign.
246 if (S.getLangOpts().CPlusPlus)
247 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000248
249 // Check if this is an inlined function or method.
250 FunctionDecl *Current = S.getCurFunctionDecl();
251 if (!Current)
252 return;
253 if (!Current->isInlined())
254 return;
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000255 if (!Current->isExternallyVisible())
Jordan Rose0eb3f452012-06-18 22:09:19 +0000256 return;
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000257
Jordan Rose0eb3f452012-06-18 22:09:19 +0000258 // Check if the decl has internal linkage.
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000259 if (D->getFormalLinkage() != InternalLinkage)
Jordan Rose0eb3f452012-06-18 22:09:19 +0000260 return;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000261
Jordan Rose05233272012-06-21 05:54:50 +0000262 // Downgrade from ExtWarn to Extension if
263 // (1) the supposedly external inline function is in the main file,
264 // and probably won't be included anywhere else.
265 // (2) the thing we're referencing is a pure function.
266 // (3) the thing we're referencing is another inline function.
267 // This last can give us false negatives, but it's better than warning on
268 // wrappers for simple C library functions.
269 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
Eli Friedman24146972013-08-22 00:27:10 +0000270 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
Jordan Rose05233272012-06-21 05:54:50 +0000271 if (!DowngradeWarning && UsedFn)
272 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
273
Stephen Hines176edba2014-12-01 14:53:08 -0800274 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
275 : diag::ext_internal_in_extern_inline)
Jordan Rose05233272012-06-21 05:54:50 +0000276 << /*IsVar=*/!UsedFn << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000277
John McCallb421d922013-04-02 02:48:58 +0000278 S.MaybeSuggestAddingStaticToDecl(Current);
Jordan Rose0eb3f452012-06-18 22:09:19 +0000279
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700280 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
281 << D;
Jordan Rose0eb3f452012-06-18 22:09:19 +0000282}
283
John McCallb421d922013-04-02 02:48:58 +0000284void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
Rafael Espindolabc650912013-10-17 15:37:26 +0000285 const FunctionDecl *First = Cur->getFirstDecl();
John McCallb421d922013-04-02 02:48:58 +0000286
287 // Suggest "static" on the function, if possible.
288 if (!hasAnyExplicitStorageClass(First)) {
289 SourceLocation DeclBegin = First->getSourceRange().getBegin();
290 Diag(DeclBegin, diag::note_convert_inline_to_static)
291 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
292 }
293}
294
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000295/// \brief Determine whether the use of this declaration is valid, and
296/// emit any corresponding diagnostics.
297///
298/// This routine diagnoses various problems with referencing
299/// declarations that can occur when using a declaration. For example,
300/// it might warn if a deprecated or unavailable declaration is being
301/// used, or produce an error (and return true) if a C++0x deleted
302/// function is being used.
303///
304/// \returns true if there was an error (this declaration cannot be
305/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +0000306///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +0000307bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700308 const ObjCInterfaceDecl *UnknownObjCClass,
309 bool ObjCPropertyAccess) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000310 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor9b623632010-10-12 23:32:35 +0000311 // If there were any diagnostics suppressed by template argument deduction,
312 // emit them now.
Craig Topperee0a4792013-07-05 04:33:53 +0000313 SuppressedDiagnosticsMap::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +0000314 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
315 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000316 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +0000317 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
318 Diag(Suppressed[I].first, Suppressed[I].second);
Stephen Hines651f13c2014-04-23 16:59:28 -0700319
Douglas Gregor9b623632010-10-12 23:32:35 +0000320 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000321 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +0000322 // entry from the table, because we want to avoid ever emitting these
323 // diagnostics again.
324 Suppressed.clear();
325 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700326
327 // C++ [basic.start.main]p3:
328 // The function 'main' shall not be used within a program.
329 if (cast<FunctionDecl>(D)->isMain())
330 Diag(Loc, diag::ext_main_used);
Douglas Gregor9b623632010-10-12 23:32:35 +0000331 }
332
Richard Smith34b41d92011-02-20 03:19:35 +0000333 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +0000334 if (ParsingInitForAutoVars.count(D)) {
335 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
336 << D->getDeclName();
337 return true;
Richard Smith34b41d92011-02-20 03:19:35 +0000338 }
339
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000340 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +0000341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000342 if (FD->isDeleted()) {
343 Diag(Loc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +0000344 NoteDeletedFunction(FD);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000345 return true;
346 }
Richard Smith60e141e2013-05-04 07:00:32 +0000347
348 // If the function has a deduced return type, and we can't deduce it,
349 // then we can't use it either.
Stephen Hines176edba2014-12-01 14:53:08 -0800350 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
Richard Smith60e141e2013-05-04 07:00:32 +0000351 DeduceReturnType(FD, Loc))
352 return true;
Douglas Gregor25d944a2009-02-24 04:26:15 +0000353 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700354 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
355 ObjCPropertyAccess);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000356
Fariborz Jahanian2d40d9e2012-09-06 16:43:18 +0000357 DiagnoseUnusedOfDecl(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000358
Jordan Rose0eb3f452012-06-18 22:09:19 +0000359 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
Jordan Rose106af9e2012-06-15 18:19:48 +0000360
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000361 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000362}
363
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000364/// \brief Retrieve the message suffix that should be added to a
365/// diagnostic complaining about the given function being deleted or
366/// unavailable.
367std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000368 std::string Message;
369 if (FD->getAvailability(&Message))
370 return ": " + Message;
371
372 return std::string();
373}
374
John McCall3323fad2011-09-09 07:56:05 +0000375/// DiagnoseSentinelCalls - This routine checks whether a call or
376/// message-send is to a declaration with the sentinel attribute, and
377/// if so, it checks that the requirements of the sentinel are
378/// satisfied.
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000379void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000380 ArrayRef<Expr *> Args) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000381 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000382 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000383 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000384
John McCall3323fad2011-09-09 07:56:05 +0000385 // The number of formal parameters of the declaration.
386 unsigned numFormalParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
John McCall3323fad2011-09-09 07:56:05 +0000388 // The kind of declaration. This is also an index into a %select in
389 // the diagnostic.
390 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
391
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000392 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000393 numFormalParams = MD->param_size();
394 calleeType = CT_Method;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000395 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCall3323fad2011-09-09 07:56:05 +0000396 numFormalParams = FD->param_size();
397 calleeType = CT_Function;
398 } else if (isa<VarDecl>(D)) {
399 QualType type = cast<ValueDecl>(D)->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700400 const FunctionType *fn = nullptr;
John McCall3323fad2011-09-09 07:56:05 +0000401 if (const PointerType *ptr = type->getAs<PointerType>()) {
402 fn = ptr->getPointeeType()->getAs<FunctionType>();
403 if (!fn) return;
404 calleeType = CT_Function;
405 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
406 fn = ptr->getPointeeType()->castAs<FunctionType>();
407 calleeType = CT_Block;
408 } else {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000409 return;
John McCall3323fad2011-09-09 07:56:05 +0000410 }
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000411
John McCall3323fad2011-09-09 07:56:05 +0000412 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700413 numFormalParams = proto->getNumParams();
John McCall3323fad2011-09-09 07:56:05 +0000414 } else {
415 numFormalParams = 0;
416 }
417 } else {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000418 return;
419 }
John McCall3323fad2011-09-09 07:56:05 +0000420
421 // "nullPos" is the number of formal parameters at the end which
422 // effectively count as part of the variadic arguments. This is
423 // useful if you would prefer to not have *any* formal parameters,
424 // but the language forces you to have at least one.
425 unsigned nullPos = attr->getNullPos();
426 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
427 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
428
429 // The number of arguments which should follow the sentinel.
430 unsigned numArgsAfterSentinel = attr->getSentinel();
431
432 // If there aren't enough arguments for all the formal parameters,
433 // the sentinel, and the args after the sentinel, complain.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000434 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000435 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000436 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000437 return;
438 }
John McCall3323fad2011-09-09 07:56:05 +0000439
440 // Otherwise, find the sentinel expression.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000441 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
John McCall8eb662e2010-05-06 23:53:00 +0000442 if (!sentinelExpr) return;
John McCall8eb662e2010-05-06 23:53:00 +0000443 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +0000444 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall8eb662e2010-05-06 23:53:00 +0000445
Stephen Hines176edba2014-12-01 14:53:08 -0800446 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
447 // or 'NULL' if those are actually defined in the context. Only use
John McCall3323fad2011-09-09 07:56:05 +0000448 // 'nil' for ObjC methods, where it's much more likely that the
449 // variadic arguments form a list of object pointers.
450 SourceLocation MissingNilLoc
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000451 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
452 std::string NullValue;
John McCall3323fad2011-09-09 07:56:05 +0000453 if (calleeType == CT_Method &&
454 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000455 NullValue = "nil";
Stephen Hines176edba2014-12-01 14:53:08 -0800456 else if (getLangOpts().CPlusPlus11)
457 NullValue = "nullptr";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000458 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
459 NullValue = "NULL";
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000460 else
John McCall3323fad2011-09-09 07:56:05 +0000461 NullValue = "(void*) 0";
Eli Friedman39834ba2011-09-27 23:46:37 +0000462
463 if (MissingNilLoc.isInvalid())
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000464 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
Eli Friedman39834ba2011-09-27 23:46:37 +0000465 else
466 Diag(MissingNilLoc, diag::warn_missing_sentinel)
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000467 << int(calleeType)
Eli Friedman39834ba2011-09-27 23:46:37 +0000468 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000469 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000470}
471
Richard Trieuccd891a2011-09-09 01:45:06 +0000472SourceRange Sema::getExprRange(Expr *E) const {
473 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000474}
475
Chris Lattnere7a2e912008-07-25 21:10:04 +0000476//===----------------------------------------------------------------------===//
477// Standard Promotions and Conversions
478//===----------------------------------------------------------------------===//
479
Chris Lattnere7a2e912008-07-25 21:10:04 +0000480/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000481ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000482 // Handle any placeholder expressions which made it here.
483 if (E->getType()->isPlaceholderType()) {
484 ExprResult result = CheckPlaceholderExpr(E);
485 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700486 E = result.get();
John McCall6dbba4f2011-10-11 23:14:30 +0000487 }
488
Chris Lattnere7a2e912008-07-25 21:10:04 +0000489 QualType Ty = E->getType();
490 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
491
Stephen Hines651f13c2014-04-23 16:59:28 -0700492 if (Ty->isFunctionType()) {
493 // If we are here, we are not calling a function but taking
494 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
495 if (getLangOpts().OpenCL) {
496 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
497 return ExprError();
498 }
John Wiegley429bb272011-04-08 18:41:53 +0000499 E = ImpCastExprToType(E, Context.getPointerType(Ty),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700500 CK_FunctionToPointerDecay).get();
Stephen Hines651f13c2014-04-23 16:59:28 -0700501 } else if (Ty->isArrayType()) {
Chris Lattner67d33d82008-07-25 21:33:13 +0000502 // In C90 mode, arrays only promote to pointers if the array expression is
503 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
504 // type 'array of type' is converted to an expression that has type 'pointer
505 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
506 // that has type 'array of type' ...". The relevant change is "an lvalue"
507 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000508 //
509 // C++ 4.2p1:
510 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
511 // T" can be converted to an rvalue of type "pointer to T".
512 //
David Blaikie4e4d0842012-03-11 07:00:24 +0000513 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000514 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700515 CK_ArrayToPointerDecay).get();
Chris Lattner67d33d82008-07-25 21:33:13 +0000516 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700517 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000518}
519
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000520static void CheckForNullPointerDereference(Sema &S, Expr *E) {
521 // Check to see if we are dereferencing a null pointer. If so,
522 // and if not volatile-qualified, this is undefined behavior that the
523 // optimizer will delete, so warn about it. People sometimes try to use this
524 // to get a deterministic trap and are surprised by clang's behavior. This
525 // only handles the pattern "*null", which is a very syntactic check.
526 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
527 if (UO->getOpcode() == UO_Deref &&
528 UO->getSubExpr()->IgnoreParenCasts()->
529 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
530 !UO->getType().isVolatileQualified()) {
531 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
532 S.PDiag(diag::warn_indirection_through_null)
533 << UO->getSubExpr()->getSourceRange());
534 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
535 S.PDiag(diag::note_indirection_through_null));
536 }
537}
538
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000539static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
Fariborz Jahanian0c701812013-04-02 18:57:54 +0000540 SourceLocation AssignLoc,
541 const Expr* RHS) {
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000542 const ObjCIvarDecl *IV = OIRE->getDecl();
543 if (!IV)
544 return;
545
546 DeclarationName MemberName = IV->getDeclName();
547 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
548 if (!Member || !Member->isStr("isa"))
549 return;
550
551 const Expr *Base = OIRE->getBase();
552 QualType BaseType = Base->getType();
553 if (OIRE->isArrow())
554 BaseType = BaseType->getPointeeType();
555 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
556 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700557 ObjCInterfaceDecl *ClassDeclared = nullptr;
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000558 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
559 if (!ClassDeclared->getSuperClass()
560 && (*ClassDeclared->ivar_begin()) == IV) {
Fariborz Jahanian0c701812013-04-02 18:57:54 +0000561 if (RHS) {
562 NamedDecl *ObjectSetClass =
563 S.LookupSingleName(S.TUScope,
564 &S.Context.Idents.get("object_setClass"),
565 SourceLocation(), S.LookupOrdinaryName);
566 if (ObjectSetClass) {
567 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
568 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
569 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
570 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
571 AssignLoc), ",") <<
572 FixItHint::CreateInsertion(RHSLocEnd, ")");
573 }
574 else
575 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
576 } else {
577 NamedDecl *ObjectGetClass =
578 S.LookupSingleName(S.TUScope,
579 &S.Context.Idents.get("object_getClass"),
580 SourceLocation(), S.LookupOrdinaryName);
581 if (ObjectGetClass)
582 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
583 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
584 FixItHint::CreateReplacement(
585 SourceRange(OIRE->getOpLoc(),
586 OIRE->getLocEnd()), ")");
587 else
588 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
589 }
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000590 S.Diag(IV->getLocation(), diag::note_ivar_decl);
591 }
592 }
593}
594
John Wiegley429bb272011-04-08 18:41:53 +0000595ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall6dbba4f2011-10-11 23:14:30 +0000596 // Handle any placeholder expressions which made it here.
597 if (E->getType()->isPlaceholderType()) {
598 ExprResult result = CheckPlaceholderExpr(E);
599 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700600 E = result.get();
John McCall6dbba4f2011-10-11 23:14:30 +0000601 }
602
John McCall0ae287a2010-12-01 04:43:34 +0000603 // C++ [conv.lval]p1:
604 // A glvalue of a non-function, non-array type T can be
605 // converted to a prvalue.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700606 if (!E->isGLValue()) return E;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +0000607
John McCall409fa9a2010-12-06 20:48:59 +0000608 QualType T = E->getType();
609 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000610
John McCall409fa9a2010-12-06 20:48:59 +0000611 // We don't want to throw lvalue-to-rvalue casts on top of
612 // expressions of certain types in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000613 if (getLangOpts().CPlusPlus &&
John McCall409fa9a2010-12-06 20:48:59 +0000614 (E->getType() == Context.OverloadTy ||
615 T->isDependentType() ||
616 T->isRecordType()))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700617 return E;
John McCall409fa9a2010-12-06 20:48:59 +0000618
619 // The C standard is actually really unclear on this point, and
620 // DR106 tells us what the result should be but not why. It's
621 // generally best to say that void types just doesn't undergo
622 // lvalue-to-rvalue at all. Note that expressions of unqualified
623 // 'void' type are never l-values, but qualified void can be.
624 if (T->isVoidType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700625 return E;
John McCall409fa9a2010-12-06 20:48:59 +0000626
John McCall9dd74c52013-02-12 01:29:43 +0000627 // OpenCL usually rejects direct accesses to values of 'half' type.
628 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
629 T->isHalfType()) {
630 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
631 << 0 << T;
632 return ExprError();
633 }
634
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000635 CheckForNullPointerDereference(*this, E);
Fariborz Jahanianec8deba2013-03-28 19:50:55 +0000636 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
637 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
638 &Context.Idents.get("object_getClass"),
639 SourceLocation(), LookupOrdinaryName);
640 if (ObjectGetClass)
641 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
642 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
643 FixItHint::CreateReplacement(
644 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
645 else
646 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
647 }
Fariborz Jahanian99a72d22013-03-28 23:39:11 +0000648 else if (const ObjCIvarRefExpr *OIRE =
649 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700650 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
651
John McCall409fa9a2010-12-06 20:48:59 +0000652 // C++ [conv.lval]p1:
653 // [...] If T is a non-class type, the type of the prvalue is the
654 // cv-unqualified version of T. Otherwise, the type of the
655 // rvalue is T.
656 //
657 // C99 6.3.2.1p2:
658 // If the lvalue has qualified type, the value has the unqualified
659 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000660 // type of the lvalue.
John McCall409fa9a2010-12-06 20:48:59 +0000661 if (T.hasQualifiers())
662 T = T.getUnqualifiedType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000663
Eli Friedmand2cce132012-02-02 23:15:15 +0000664 UpdateMarkingForLValueToRValue(E);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +0000665
666 // Loading a __weak object implicitly retains the value, so we need a cleanup to
667 // balance that.
668 if (getLangOpts().ObjCAutoRefCount &&
669 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
670 ExprNeedsCleanups = true;
Eli Friedmand2cce132012-02-02 23:15:15 +0000671
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700672 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
673 nullptr, VK_RValue);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000674
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000675 // C11 6.3.2.1p2:
676 // ... if the lvalue has atomic type, the value has the non-atomic version
677 // of the type of the lvalue ...
678 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
679 T = Atomic->getValueType().getUnqualifiedType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700680 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
681 nullptr, VK_RValue);
Douglas Gregorf7ecc302012-04-12 17:51:55 +0000682 }
683
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000684 return Res;
John McCall409fa9a2010-12-06 20:48:59 +0000685}
686
John Wiegley429bb272011-04-08 18:41:53 +0000687ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
688 ExprResult Res = DefaultFunctionArrayConversion(E);
689 if (Res.isInvalid())
690 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700691 Res = DefaultLvalueConversion(Res.get());
John Wiegley429bb272011-04-08 18:41:53 +0000692 if (Res.isInvalid())
693 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000694 return Res;
Douglas Gregora873dfc2010-02-03 00:27:59 +0000695}
696
Stephen Hines651f13c2014-04-23 16:59:28 -0700697/// CallExprUnaryConversions - a special case of an unary conversion
698/// performed on a function designator of a call expression.
699ExprResult Sema::CallExprUnaryConversions(Expr *E) {
700 QualType Ty = E->getType();
701 ExprResult Res = E;
702 // Only do implicit cast for a function type, but not for a pointer
703 // to function type.
704 if (Ty->isFunctionType()) {
705 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700706 CK_FunctionToPointerDecay).get();
Stephen Hines651f13c2014-04-23 16:59:28 -0700707 if (Res.isInvalid())
708 return ExprError();
709 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700710 Res = DefaultLvalueConversion(Res.get());
Stephen Hines651f13c2014-04-23 16:59:28 -0700711 if (Res.isInvalid())
712 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700713 return Res.get();
Stephen Hines651f13c2014-04-23 16:59:28 -0700714}
Douglas Gregora873dfc2010-02-03 00:27:59 +0000715
Chris Lattnere7a2e912008-07-25 21:10:04 +0000716/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000717/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000718/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000719/// apply if the array is an argument to the sizeof or address (&) operators.
720/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000721ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000722 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000723 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
724 if (Res.isInvalid())
Fariborz Jahanian75525c42013-03-06 00:37:40 +0000725 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700726 E = Res.get();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000727
John McCall0ae287a2010-12-01 04:43:34 +0000728 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000729 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000730
Joey Gouly19dbb202013-01-23 11:56:20 +0000731 // Half FP have to be promoted to float unless it is natively supported
732 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700733 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000734
John McCall0ae287a2010-12-01 04:43:34 +0000735 // Try to perform integral promotions if the object has a theoretically
736 // promotable type.
737 if (Ty->isIntegralOrUnscopedEnumerationType()) {
738 // C99 6.3.1.1p2:
739 //
740 // The following may be used in an expression wherever an int or
741 // unsigned int may be used:
742 // - an object or expression with an integer type whose integer
743 // conversion rank is less than or equal to the rank of int
744 // and unsigned int.
745 // - A bit-field of type _Bool, int, signed int, or unsigned int.
746 //
747 // If an int can represent all values of the original type, the
748 // value is converted to an int; otherwise, it is converted to an
749 // unsigned int. These are called the integer promotions. All
750 // other types are unchanged by the integer promotions.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000751
John McCall0ae287a2010-12-01 04:43:34 +0000752 QualType PTy = Context.isPromotableBitField(E);
753 if (!PTy.isNull()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700754 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
755 return E;
John McCall0ae287a2010-12-01 04:43:34 +0000756 }
757 if (Ty->isPromotableIntegerType()) {
758 QualType PT = Context.getPromotedIntegerType(Ty);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700759 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
760 return E;
John McCall0ae287a2010-12-01 04:43:34 +0000761 }
Eli Friedman04e83572009-08-20 04:21:42 +0000762 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700763 return E;
Chris Lattnere7a2e912008-07-25 21:10:04 +0000764}
765
Chris Lattner05faf172008-07-25 22:25:12 +0000766/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Tim Northovere1ac4ae2013-01-30 09:46:55 +0000767/// do not have a prototype. Arguments that have type float or __fp16
768/// are promoted to double. All other argument types are converted by
769/// UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000770ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
771 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000772 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000773
John Wiegley429bb272011-04-08 18:41:53 +0000774 ExprResult Res = UsualUnaryConversions(E);
775 if (Res.isInvalid())
Fariborz Jahanian75525c42013-03-06 00:37:40 +0000776 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700777 E = Res.get();
John McCall40c29132010-12-06 18:36:11 +0000778
Tim Northovere1ac4ae2013-01-30 09:46:55 +0000779 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
780 // double.
781 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
782 if (BTy && (BTy->getKind() == BuiltinType::Half ||
783 BTy->getKind() == BuiltinType::Float))
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700784 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
John Wiegley429bb272011-04-08 18:41:53 +0000785
John McCall96a914a2011-08-27 22:06:17 +0000786 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall709bca82011-08-29 23:55:37 +0000787 // promotion, even on class types, but note:
788 // C++11 [conv.lval]p2:
789 // When an lvalue-to-rvalue conversion occurs in an unevaluated
790 // operand or a subexpression thereof the value contained in the
791 // referenced object is not accessed. Otherwise, if the glvalue
792 // has a class type, the conversion copy-initializes a temporary
793 // of type T from the glvalue and the result of the conversion
794 // is a prvalue for the temporary.
Eli Friedman55693fb2012-01-17 02:13:45 +0000795 // FIXME: add some way to gate this entire thing for correctness in
796 // potentially potentially evaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +0000797 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
Eli Friedman55693fb2012-01-17 02:13:45 +0000798 ExprResult Temp = PerformCopyInitialization(
799 InitializedEntity::InitializeTemporary(E->getType()),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700800 E->getExprLoc(), E);
Eli Friedman55693fb2012-01-17 02:13:45 +0000801 if (Temp.isInvalid())
802 return ExprError();
803 E = Temp.get();
John McCall5f8d6042011-08-27 01:09:30 +0000804 }
805
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700806 return E;
Chris Lattner05faf172008-07-25 22:25:12 +0000807}
808
Richard Smith831421f2012-06-25 20:30:08 +0000809/// Determine the degree of POD-ness for an expression.
810/// Incomplete types are considered POD, since this check can be performed
811/// when we're in an unevaluated context.
812Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
Jordan Roseddcfbc92012-07-19 18:10:23 +0000813 if (Ty->isIncompleteType()) {
Richard Smith0e218972013-08-05 18:49:43 +0000814 // C++11 [expr.call]p7:
815 // After these conversions, if the argument does not have arithmetic,
816 // enumeration, pointer, pointer to member, or class type, the program
817 // is ill-formed.
818 //
819 // Since we've already performed array-to-pointer and function-to-pointer
820 // decay, the only such type in C++ is cv void. This also handles
821 // initializer lists as variadic arguments.
822 if (Ty->isVoidType())
823 return VAK_Invalid;
824
Jordan Roseddcfbc92012-07-19 18:10:23 +0000825 if (Ty->isObjCObjectType())
826 return VAK_Invalid;
Richard Smith831421f2012-06-25 20:30:08 +0000827 return VAK_Valid;
Jordan Roseddcfbc92012-07-19 18:10:23 +0000828 }
829
830 if (Ty.isCXX98PODType(Context))
831 return VAK_Valid;
832
Richard Smith426391c2012-11-16 00:53:38 +0000833 // C++11 [expr.call]p7:
834 // Passing a potentially-evaluated argument of class type (Clause 9)
Richard Smith831421f2012-06-25 20:30:08 +0000835 // having a non-trivial copy constructor, a non-trivial move constructor,
Richard Smith426391c2012-11-16 00:53:38 +0000836 // or a non-trivial destructor, with no corresponding parameter,
Richard Smith831421f2012-06-25 20:30:08 +0000837 // is conditionally-supported with implementation-defined semantics.
Richard Smith80ad52f2013-01-02 11:42:31 +0000838 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
Richard Smith831421f2012-06-25 20:30:08 +0000839 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
Richard Smith426391c2012-11-16 00:53:38 +0000840 if (!Record->hasNonTrivialCopyConstructor() &&
841 !Record->hasNonTrivialMoveConstructor() &&
842 !Record->hasNonTrivialDestructor())
Richard Smith831421f2012-06-25 20:30:08 +0000843 return VAK_ValidInCXX11;
844
845 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
846 return VAK_Valid;
Richard Smith0e218972013-08-05 18:49:43 +0000847
848 if (Ty->isObjCObjectType())
849 return VAK_Invalid;
850
Stephen Hines176edba2014-12-01 14:53:08 -0800851 if (getLangOpts().MSVCCompat)
852 return VAK_MSVCUndefined;
853
Richard Smith0e218972013-08-05 18:49:43 +0000854 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
855 // permitted to reject them. We should consider doing so.
856 return VAK_Undefined;
Richard Smith831421f2012-06-25 20:30:08 +0000857}
858
Richard Smith0e218972013-08-05 18:49:43 +0000859void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
Richard Smith831421f2012-06-25 20:30:08 +0000860 // Don't allow one to pass an Objective-C interface to a vararg.
Richard Smith0e218972013-08-05 18:49:43 +0000861 const QualType &Ty = E->getType();
862 VarArgKind VAK = isValidVarArgType(Ty);
Richard Smith831421f2012-06-25 20:30:08 +0000863
864 // Complain about passing non-POD types through varargs.
Richard Smith0e218972013-08-05 18:49:43 +0000865 switch (VAK) {
Richard Smith0e218972013-08-05 18:49:43 +0000866 case VAK_ValidInCXX11:
867 DiagRuntimeBehavior(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700868 E->getLocStart(), nullptr,
Richard Smith0e218972013-08-05 18:49:43 +0000869 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
Stephen Hines651f13c2014-04-23 16:59:28 -0700870 << Ty << CT);
871 // Fall through.
872 case VAK_Valid:
873 if (Ty->isRecordType()) {
874 // This is unlikely to be what the user intended. If the class has a
875 // 'c_str' member function, the user probably meant to call that.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700876 DiagRuntimeBehavior(E->getLocStart(), nullptr,
Stephen Hines651f13c2014-04-23 16:59:28 -0700877 PDiag(diag::warn_pass_class_arg_to_vararg)
878 << Ty << CT << hasCStrMethod(E) << ".c_str()");
879 }
Richard Smith0e218972013-08-05 18:49:43 +0000880 break;
881
882 case VAK_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -0800883 case VAK_MSVCUndefined:
Richard Smith0e218972013-08-05 18:49:43 +0000884 DiagRuntimeBehavior(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700885 E->getLocStart(), nullptr,
Richard Smith0e218972013-08-05 18:49:43 +0000886 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
887 << getLangOpts().CPlusPlus11 << Ty << CT);
888 break;
889
890 case VAK_Invalid:
891 if (Ty->isObjCObjectType())
892 DiagRuntimeBehavior(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700893 E->getLocStart(), nullptr,
Richard Smith0e218972013-08-05 18:49:43 +0000894 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
895 << Ty << CT);
896 else
897 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
898 << isa<InitListExpr>(E) << Ty << CT;
899 break;
Richard Smith831421f2012-06-25 20:30:08 +0000900 }
Richard Smith831421f2012-06-25 20:30:08 +0000901}
902
Chris Lattner312531a2009-04-12 08:11:20 +0000903/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
Jordan Roseddcfbc92012-07-19 18:10:23 +0000904/// will create a trap if the resulting type is not a POD type.
John Wiegley429bb272011-04-08 18:41:53 +0000905ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000906 FunctionDecl *FDecl) {
Richard Smithe1971a12012-06-27 20:29:39 +0000907 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +0000908 // Strip the unbridged-cast placeholder expression off, if applicable.
909 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
910 (CT == VariadicMethod ||
911 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
912 E = stripARCUnbridgedCast(E);
913
914 // Otherwise, do normal placeholder checking.
915 } else {
916 ExprResult ExprRes = CheckPlaceholderExpr(E);
917 if (ExprRes.isInvalid())
918 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700919 E = ExprRes.get();
John McCall5acb0c92011-10-17 18:40:02 +0000920 }
921 }
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000922
John McCall5acb0c92011-10-17 18:40:02 +0000923 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000924 if (ExprRes.isInvalid())
925 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700926 E = ExprRes.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Richard Smith831421f2012-06-25 20:30:08 +0000928 // Diagnostics regarding non-POD argument types are
929 // emitted along with format string checking in Sema::CheckFunctionCall().
Richard Smith0e218972013-08-05 18:49:43 +0000930 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
Richard Smith831421f2012-06-25 20:30:08 +0000931 // Turn this into a trap.
932 CXXScopeSpec SS;
933 SourceLocation TemplateKWLoc;
934 UnqualifiedId Name;
935 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
936 E->getLocStart());
937 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
938 Name, true, false);
939 if (TrapFn.isInvalid())
940 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000941
Richard Smith831421f2012-06-25 20:30:08 +0000942 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000943 E->getLocStart(), None,
Richard Smith831421f2012-06-25 20:30:08 +0000944 E->getLocEnd());
945 if (Call.isInvalid())
946 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000947
Richard Smith831421f2012-06-25 20:30:08 +0000948 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
949 Call.get(), E);
950 if (Comma.isInvalid())
951 return ExprError();
952 return Comma.get();
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000953 }
Richard Smith831421f2012-06-25 20:30:08 +0000954
David Blaikie4e4d0842012-03-11 07:00:24 +0000955 if (!getLangOpts().CPlusPlus &&
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000956 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahaniana0e005b2012-03-02 17:05:03 +0000957 diag::err_call_incomplete_argument))
Fariborz Jahaniane853bb32012-03-01 23:42:00 +0000958 return ExprError();
Richard Smith831421f2012-06-25 20:30:08 +0000959
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700960 return E;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000961}
962
Richard Trieu8289f492011-09-02 20:58:51 +0000963/// \brief Converts an integer to complex float type. Helper function of
964/// UsualArithmeticConversions()
965///
966/// \return false if the integer expression is an integer type and is
967/// successfully converted to the complex type.
Richard Trieuccd891a2011-09-09 01:45:06 +0000968static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
969 ExprResult &ComplexExpr,
970 QualType IntTy,
971 QualType ComplexTy,
972 bool SkipCast) {
973 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
974 if (SkipCast) return false;
975 if (IntTy->isIntegerType()) {
976 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700977 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
978 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000979 CK_FloatingRealToComplex);
980 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +0000981 assert(IntTy->isComplexIntegerType());
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700982 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
Richard Trieu8289f492011-09-02 20:58:51 +0000983 CK_IntegralComplexToFloatingComplex);
984 }
985 return false;
986}
987
Richard Trieu8289f492011-09-02 20:58:51 +0000988/// \brief Handle arithmetic conversion with complex types. Helper function of
989/// UsualArithmeticConversions()
Richard Trieucafd30b2011-09-06 18:25:09 +0000990static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
991 ExprResult &RHS, QualType LHSType,
992 QualType RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000993 bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +0000994 // if we have an integer operand, the result is the complex type.
Richard Trieucafd30b2011-09-06 18:25:09 +0000995 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +0000996 /*skipCast*/false))
Richard Trieucafd30b2011-09-06 18:25:09 +0000997 return LHSType;
998 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +0000999 /*skipCast*/IsCompAssign))
Richard Trieucafd30b2011-09-06 18:25:09 +00001000 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001001
1002 // This handles complex/complex, complex/float, or float/complex.
1003 // When both operands are complex, the shorter operand is converted to the
1004 // type of the longer, and that is the type of the result. This corresponds
1005 // to what is done when combining two real floating-point operands.
1006 // The fun begins when size promotion occur across type domains.
1007 // From H&S 6.3.4: When one operand is complex and the other is a real
1008 // floating-point type, the less precise type is converted, within it's
1009 // real or complex domain, to the precision of the other type. For example,
1010 // when combining a "long double" with a "double _Complex", the
1011 // "double _Complex" is promoted to "long double _Complex".
1012
Stephen Hines176edba2014-12-01 14:53:08 -08001013 // Compute the rank of the two types, regardless of whether they are complex.
1014 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +00001015
Stephen Hines176edba2014-12-01 14:53:08 -08001016 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1017 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1018 QualType LHSElementType =
1019 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1020 QualType RHSElementType =
1021 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001022
Stephen Hines176edba2014-12-01 14:53:08 -08001023 QualType ResultType = S.Context.getComplexType(LHSElementType);
1024 if (Order < 0) {
1025 // Promote the precision of the LHS if not an assignment.
1026 ResultType = S.Context.getComplexType(RHSElementType);
1027 if (!IsCompAssign) {
1028 if (LHSComplexType)
1029 LHS =
1030 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1031 else
1032 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1033 }
1034 } else if (Order > 0) {
1035 // Promote the precision of the RHS.
1036 if (RHSComplexType)
1037 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1038 else
1039 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1040 }
1041 return ResultType;
Richard Trieu8289f492011-09-02 20:58:51 +00001042}
1043
1044/// \brief Hande arithmetic conversion from integer to float. Helper function
1045/// of UsualArithmeticConversions()
Richard Trieuccd891a2011-09-09 01:45:06 +00001046static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1047 ExprResult &IntExpr,
1048 QualType FloatTy, QualType IntTy,
1049 bool ConvertFloat, bool ConvertInt) {
1050 if (IntTy->isIntegerType()) {
1051 if (ConvertInt)
Richard Trieu8289f492011-09-02 20:58:51 +00001052 // Convert intExpr to the lhs floating point type.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001053 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
Richard Trieu8289f492011-09-02 20:58:51 +00001054 CK_IntegralToFloating);
Richard Trieuccd891a2011-09-09 01:45:06 +00001055 return FloatTy;
Richard Trieu8289f492011-09-02 20:58:51 +00001056 }
1057
1058 // Convert both sides to the appropriate complex float.
Richard Trieuccd891a2011-09-09 01:45:06 +00001059 assert(IntTy->isComplexIntegerType());
1060 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu8289f492011-09-02 20:58:51 +00001061
1062 // _Complex int -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +00001063 if (ConvertInt)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001064 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
Richard Trieu8289f492011-09-02 20:58:51 +00001065 CK_IntegralComplexToFloatingComplex);
1066
1067 // float -> _Complex float
Richard Trieuccd891a2011-09-09 01:45:06 +00001068 if (ConvertFloat)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001069 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
Richard Trieu8289f492011-09-02 20:58:51 +00001070 CK_FloatingRealToComplex);
1071
1072 return result;
1073}
1074
1075/// \brief Handle arithmethic conversion with floating point types. Helper
1076/// function of UsualArithmeticConversions()
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001077static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1078 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001079 QualType RHSType, bool IsCompAssign) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001080 bool LHSFloat = LHSType->isRealFloatingType();
1081 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu8289f492011-09-02 20:58:51 +00001082
1083 // If we have two real floating types, convert the smaller operand
1084 // to the bigger result.
1085 if (LHSFloat && RHSFloat) {
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001086 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu8289f492011-09-02 20:58:51 +00001087 if (order > 0) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001088 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001089 return LHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001090 }
1091
1092 assert(order < 0 && "illegal float comparison");
Richard Trieuccd891a2011-09-09 01:45:06 +00001093 if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001094 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001095 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001096 }
1097
1098 if (LHSFloat)
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001099 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001100 /*convertFloat=*/!IsCompAssign,
Richard Trieu8289f492011-09-02 20:58:51 +00001101 /*convertInt=*/ true);
1102 assert(RHSFloat);
Richard Trieu8ef5c8e2011-09-06 18:38:41 +00001103 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu8289f492011-09-02 20:58:51 +00001104 /*convertInt=*/ true,
Richard Trieuccd891a2011-09-09 01:45:06 +00001105 /*convertFloat=*/!IsCompAssign);
Richard Trieu8289f492011-09-02 20:58:51 +00001106}
1107
Bill Schmidt57dab712013-02-01 15:34:29 +00001108typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
Richard Trieu8289f492011-09-02 20:58:51 +00001109
Bill Schmidt57dab712013-02-01 15:34:29 +00001110namespace {
1111/// These helper callbacks are placed in an anonymous namespace to
1112/// permit their use as function template parameters.
1113ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1114 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1115}
Richard Trieu8289f492011-09-02 20:58:51 +00001116
Bill Schmidt57dab712013-02-01 15:34:29 +00001117ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1118 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1119 CK_IntegralComplexCast);
1120}
Richard Trieu8289f492011-09-02 20:58:51 +00001121}
1122
1123/// \brief Handle integer arithmetic conversions. Helper function of
1124/// UsualArithmeticConversions()
Bill Schmidt57dab712013-02-01 15:34:29 +00001125template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001126static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1127 ExprResult &RHS, QualType LHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001128 QualType RHSType, bool IsCompAssign) {
Richard Trieu8289f492011-09-02 20:58:51 +00001129 // The rules for this case are in C99 6.3.1.8
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001130 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1131 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1132 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1133 if (LHSSigned == RHSSigned) {
Richard Trieu8289f492011-09-02 20:58:51 +00001134 // Same signedness; use the higher-ranked type
1135 if (order >= 0) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001136 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001137 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001138 } else if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001139 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001140 return RHSType;
1141 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001142 // The unsigned type has greater than or equal rank to the
1143 // signed type, so use the unsigned type
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001144 if (RHSSigned) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001145 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001146 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001147 } else if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001148 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001149 return RHSType;
1150 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu8289f492011-09-02 20:58:51 +00001151 // The two types are different widths; if we are here, that
1152 // means the signed type is larger than the unsigned type, so
1153 // use the signed type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001154 if (LHSSigned) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001155 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001156 return LHSType;
Richard Trieuccd891a2011-09-09 01:45:06 +00001157 } else if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001158 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001159 return RHSType;
Richard Trieu8289f492011-09-02 20:58:51 +00001160 } else {
1161 // The signed type is higher-ranked than the unsigned type,
1162 // but isn't actually any bigger (like unsigned int and long
1163 // on most 32-bit systems). Use the unsigned type corresponding
1164 // to the signed type.
1165 QualType result =
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001166 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001167 RHS = (*doRHSCast)(S, RHS.get(), result);
Richard Trieuccd891a2011-09-09 01:45:06 +00001168 if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001169 LHS = (*doLHSCast)(S, LHS.get(), result);
Richard Trieu8289f492011-09-02 20:58:51 +00001170 return result;
1171 }
1172}
1173
Bill Schmidt57dab712013-02-01 15:34:29 +00001174/// \brief Handle conversions with GCC complex int extension. Helper function
1175/// of UsualArithmeticConversions()
1176static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1177 ExprResult &RHS, QualType LHSType,
1178 QualType RHSType,
1179 bool IsCompAssign) {
1180 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1181 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1182
1183 if (LHSComplexInt && RHSComplexInt) {
1184 QualType LHSEltType = LHSComplexInt->getElementType();
1185 QualType RHSEltType = RHSComplexInt->getElementType();
1186 QualType ScalarType =
1187 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1188 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1189
1190 return S.Context.getComplexType(ScalarType);
1191 }
1192
1193 if (LHSComplexInt) {
1194 QualType LHSEltType = LHSComplexInt->getElementType();
1195 QualType ScalarType =
1196 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1197 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1198 QualType ComplexType = S.Context.getComplexType(ScalarType);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001199 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
Bill Schmidt57dab712013-02-01 15:34:29 +00001200 CK_IntegralRealToComplex);
1201
1202 return ComplexType;
1203 }
1204
1205 assert(RHSComplexInt);
1206
1207 QualType RHSEltType = RHSComplexInt->getElementType();
1208 QualType ScalarType =
1209 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1210 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1211 QualType ComplexType = S.Context.getComplexType(ScalarType);
1212
1213 if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001214 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
Bill Schmidt57dab712013-02-01 15:34:29 +00001215 CK_IntegralRealToComplex);
1216 return ComplexType;
1217}
1218
Chris Lattnere7a2e912008-07-25 21:10:04 +00001219/// UsualArithmeticConversions - Performs various conversions that are common to
1220/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +00001221/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +00001222/// responsible for emitting appropriate error diagnostics.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001223QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00001224 bool IsCompAssign) {
1225 if (!IsCompAssign) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001226 LHS = UsualUnaryConversions(LHS.get());
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001227 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001228 return QualType();
1229 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00001230
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001231 RHS = UsualUnaryConversions(RHS.get());
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001232 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00001233 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001234
Mike Stump1eb44332009-09-09 15:08:12 +00001235 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +00001236 // For example, "const float" and "float" are equivalent.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001237 QualType LHSType =
1238 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1239 QualType RHSType =
1240 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001241
Eli Friedman860a3192012-06-16 02:19:17 +00001242 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1243 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1244 LHSType = AtomicLHS->getValueType();
1245
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001246 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001247 if (LHSType == RHSType)
1248 return LHSType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001249
1250 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1251 // The caller can deal with this (e.g. pointer + int).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001252 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman860a3192012-06-16 02:19:17 +00001253 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001254
John McCallcf33b242010-11-13 08:17:45 +00001255 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001256 QualType LHSUnpromotedType = LHSType;
1257 if (LHSType->isPromotableIntegerType())
1258 LHSType = Context.getPromotedIntegerType(LHSType);
1259 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +00001260 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001261 LHSType = LHSBitfieldPromoteTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00001262 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001263 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +00001264
John McCallcf33b242010-11-13 08:17:45 +00001265 // If both types are identical, no conversion is needed.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001266 if (LHSType == RHSType)
1267 return LHSType;
John McCallcf33b242010-11-13 08:17:45 +00001268
1269 // At this point, we have two different arithmetic types.
1270
1271 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001272 if (LHSType->isComplexType() || RHSType->isComplexType())
1273 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001274 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001275
1276 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001277 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1278 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001279 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001280
1281 // Handle GCC complex int extension.
Richard Trieu2e8a95d2011-09-06 19:52:52 +00001282 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer5cc86802011-09-06 19:57:14 +00001283 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuccd891a2011-09-09 01:45:06 +00001284 IsCompAssign);
John McCallcf33b242010-11-13 08:17:45 +00001285
1286 // Finally, we have two differing integer types.
Bill Schmidt57dab712013-02-01 15:34:29 +00001287 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1288 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001289}
1290
Bill Schmidt57dab712013-02-01 15:34:29 +00001291
Chris Lattnere7a2e912008-07-25 21:10:04 +00001292//===----------------------------------------------------------------------===//
1293// Semantic Analysis for various Expression Types
1294//===----------------------------------------------------------------------===//
1295
1296
Peter Collingbournef111d932011-04-15 00:35:48 +00001297ExprResult
1298Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1299 SourceLocation DefaultLoc,
1300 SourceLocation RParenLoc,
1301 Expr *ControllingExpr,
Dmitri Gribenko80613222013-05-10 13:06:58 +00001302 ArrayRef<ParsedType> ArgTypes,
1303 ArrayRef<Expr *> ArgExprs) {
Richard Trieuccd891a2011-09-09 01:45:06 +00001304 unsigned NumAssocs = ArgTypes.size();
1305 assert(NumAssocs == ArgExprs.size());
Peter Collingbournef111d932011-04-15 00:35:48 +00001306
Peter Collingbournef111d932011-04-15 00:35:48 +00001307 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1308 for (unsigned i = 0; i < NumAssocs; ++i) {
Dmitri Gribenko80613222013-05-10 13:06:58 +00001309 if (ArgTypes[i])
1310 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
Peter Collingbournef111d932011-04-15 00:35:48 +00001311 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001312 Types[i] = nullptr;
Peter Collingbournef111d932011-04-15 00:35:48 +00001313 }
1314
1315 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
Dmitri Gribenko80613222013-05-10 13:06:58 +00001316 ControllingExpr,
1317 llvm::makeArrayRef(Types, NumAssocs),
1318 ArgExprs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +00001319 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +00001320 return ER;
1321}
1322
1323ExprResult
1324Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1325 SourceLocation DefaultLoc,
1326 SourceLocation RParenLoc,
1327 Expr *ControllingExpr,
Dmitri Gribenko80613222013-05-10 13:06:58 +00001328 ArrayRef<TypeSourceInfo *> Types,
1329 ArrayRef<Expr *> Exprs) {
1330 unsigned NumAssocs = Types.size();
1331 assert(NumAssocs == Exprs.size());
John McCalla2905ea2013-02-12 02:08:12 +00001332 if (ControllingExpr->getType()->isPlaceholderType()) {
1333 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1334 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001335 ControllingExpr = result.get();
John McCalla2905ea2013-02-12 02:08:12 +00001336 }
1337
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001338 // The controlling expression is an unevaluated operand, so side effects are
1339 // likely unintended.
1340 if (ActiveTemplateInstantiations.empty() &&
1341 ControllingExpr->HasSideEffects(Context, false))
1342 Diag(ControllingExpr->getExprLoc(),
1343 diag::warn_side_effects_unevaluated_context);
1344
Peter Collingbournef111d932011-04-15 00:35:48 +00001345 bool TypeErrorFound = false,
1346 IsResultDependent = ControllingExpr->isTypeDependent(),
1347 ContainsUnexpandedParameterPack
1348 = ControllingExpr->containsUnexpandedParameterPack();
1349
1350 for (unsigned i = 0; i < NumAssocs; ++i) {
1351 if (Exprs[i]->containsUnexpandedParameterPack())
1352 ContainsUnexpandedParameterPack = true;
1353
1354 if (Types[i]) {
1355 if (Types[i]->getType()->containsUnexpandedParameterPack())
1356 ContainsUnexpandedParameterPack = true;
1357
1358 if (Types[i]->getType()->isDependentType()) {
1359 IsResultDependent = true;
1360 } else {
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001361 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbournef111d932011-04-15 00:35:48 +00001362 // complete object type other than a variably modified type."
1363 unsigned D = 0;
1364 if (Types[i]->getType()->isIncompleteType())
1365 D = diag::err_assoc_type_incomplete;
1366 else if (!Types[i]->getType()->isObjectType())
1367 D = diag::err_assoc_type_nonobject;
1368 else if (Types[i]->getType()->isVariablyModifiedType())
1369 D = diag::err_assoc_type_variably_modified;
1370
1371 if (D != 0) {
1372 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1373 << Types[i]->getTypeLoc().getSourceRange()
1374 << Types[i]->getType();
1375 TypeErrorFound = true;
1376 }
1377
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001378 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbournef111d932011-04-15 00:35:48 +00001379 // selection shall specify compatible types."
1380 for (unsigned j = i+1; j < NumAssocs; ++j)
1381 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1382 Context.typesAreCompatible(Types[i]->getType(),
1383 Types[j]->getType())) {
1384 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1385 diag::err_assoc_compatible_types)
1386 << Types[j]->getTypeLoc().getSourceRange()
1387 << Types[j]->getType()
1388 << Types[i]->getType();
1389 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1390 diag::note_compat_assoc)
1391 << Types[i]->getTypeLoc().getSourceRange()
1392 << Types[i]->getType();
1393 TypeErrorFound = true;
1394 }
1395 }
1396 }
1397 }
1398 if (TypeErrorFound)
1399 return ExprError();
1400
1401 // If we determined that the generic selection is result-dependent, don't
1402 // try to compute the result expression.
1403 if (IsResultDependent)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001404 return new (Context) GenericSelectionExpr(
1405 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1406 ContainsUnexpandedParameterPack);
Peter Collingbournef111d932011-04-15 00:35:48 +00001407
Chris Lattner5f9e2722011-07-23 10:55:15 +00001408 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +00001409 unsigned DefaultIndex = -1U;
1410 for (unsigned i = 0; i < NumAssocs; ++i) {
1411 if (!Types[i])
1412 DefaultIndex = i;
1413 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1414 Types[i]->getType()))
1415 CompatIndices.push_back(i);
1416 }
1417
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001418 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbournef111d932011-04-15 00:35:48 +00001419 // type compatible with at most one of the types named in its generic
1420 // association list."
1421 if (CompatIndices.size() > 1) {
1422 // We strip parens here because the controlling expression is typically
1423 // parenthesized in macro definitions.
1424 ControllingExpr = ControllingExpr->IgnoreParens();
1425 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1426 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1427 << (unsigned) CompatIndices.size();
Craig Topper09d19ef2013-07-04 03:08:24 +00001428 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +00001429 E = CompatIndices.end(); I != E; ++I) {
1430 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1431 diag::note_compat_assoc)
1432 << Types[*I]->getTypeLoc().getSourceRange()
1433 << Types[*I]->getType();
1434 }
1435 return ExprError();
1436 }
1437
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001438 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbournef111d932011-04-15 00:35:48 +00001439 // its controlling expression shall have type compatible with exactly one of
1440 // the types named in its generic association list."
1441 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1442 // We strip parens here because the controlling expression is typically
1443 // parenthesized in macro definitions.
1444 ControllingExpr = ControllingExpr->IgnoreParens();
1445 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1446 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1447 return ExprError();
1448 }
1449
Benjamin Kramerffbe9b92011-12-23 17:00:35 +00001450 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbournef111d932011-04-15 00:35:48 +00001451 // type name that is compatible with the type of the controlling expression,
1452 // then the result expression of the generic selection is the expression
1453 // in that generic association. Otherwise, the result expression of the
1454 // generic selection is the expression in the default generic association."
1455 unsigned ResultIndex =
1456 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1457
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001458 return new (Context) GenericSelectionExpr(
1459 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1460 ContainsUnexpandedParameterPack, ResultIndex);
Peter Collingbournef111d932011-04-15 00:35:48 +00001461}
1462
Richard Smithdd66be72012-03-08 01:34:56 +00001463/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1464/// location of the token and the offset of the ud-suffix within it.
1465static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1466 unsigned Offset) {
1467 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001468 S.getLangOpts());
Richard Smithdd66be72012-03-08 01:34:56 +00001469}
1470
Richard Smith36f5cfe2012-03-09 08:00:36 +00001471/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1472/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1473static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1474 IdentifierInfo *UDSuffix,
1475 SourceLocation UDSuffixLoc,
1476 ArrayRef<Expr*> Args,
1477 SourceLocation LitEndLoc) {
1478 assert(Args.size() <= 2 && "too many arguments for literal operator");
1479
1480 QualType ArgTy[2];
1481 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1482 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1483 if (ArgTy[ArgIdx]->isArrayType())
1484 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1485 }
1486
1487 DeclarationName OpName =
1488 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1489 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1490 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1491
1492 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1493 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
Richard Smithb328e292013-10-07 19:57:58 +00001494 /*AllowRaw*/false, /*AllowTemplate*/false,
1495 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
Richard Smith36f5cfe2012-03-09 08:00:36 +00001496 return ExprError();
1497
1498 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1499}
1500
Steve Narofff69936d2007-09-16 03:34:24 +00001501/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001502/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1503/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1504/// multiple tokens. However, the common case is that StringToks points to one
1505/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001506///
John McCall60d7b3a2010-08-24 06:29:42 +00001507ExprResult
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001508Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1509 assert(!StringToks.empty() && "Must have at least one string!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001510
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001511 StringLiteralParser Literal(StringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001513 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001514
Chris Lattner5f9e2722011-07-23 10:55:15 +00001515 SmallVector<SourceLocation, 4> StringTokLocs;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001516 for (unsigned i = 0; i != StringToks.size(); ++i)
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001518
Richard Smithb328e292013-10-07 19:57:58 +00001519 QualType CharTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001520 StringLiteral::StringKind Kind = StringLiteral::Ascii;
Richard Smithb328e292013-10-07 19:57:58 +00001521 if (Literal.isWide()) {
1522 CharTy = Context.getWideCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001523 Kind = StringLiteral::Wide;
Richard Smithb328e292013-10-07 19:57:58 +00001524 } else if (Literal.isUTF8()) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00001525 Kind = StringLiteral::UTF8;
Richard Smithb328e292013-10-07 19:57:58 +00001526 } else if (Literal.isUTF16()) {
1527 CharTy = Context.Char16Ty;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001528 Kind = StringLiteral::UTF16;
Richard Smithb328e292013-10-07 19:57:58 +00001529 } else if (Literal.isUTF32()) {
1530 CharTy = Context.Char32Ty;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001531 Kind = StringLiteral::UTF32;
Richard Smithb328e292013-10-07 19:57:58 +00001532 } else if (Literal.isPascal()) {
1533 CharTy = Context.UnsignedCharTy;
1534 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00001535
Richard Smithb328e292013-10-07 19:57:58 +00001536 QualType CharTyConst = CharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001537 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +00001538 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Richard Smithb328e292013-10-07 19:57:58 +00001539 CharTyConst.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001540
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001541 // Get an array type for the string, according to C99 6.4.5. This includes
1542 // the nul terminator character as well as the string length for pascal
1543 // strings.
Richard Smithb328e292013-10-07 19:57:58 +00001544 QualType StrTy = Context.getConstantArrayType(CharTyConst,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001545 llvm::APInt(32, Literal.GetNumStringChars()+1),
Richard Smithb328e292013-10-07 19:57:58 +00001546 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Joey Gouly758c4d82013-11-14 18:26:10 +00001548 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1549 if (getLangOpts().OpenCL) {
1550 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1551 }
1552
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smith9fcce652012-03-07 08:35:16 +00001554 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1555 Kind, Literal.Pascal, StrTy,
1556 &StringTokLocs[0],
1557 StringTokLocs.size());
1558 if (Literal.getUDSuffix().empty())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001559 return Lit;
Richard Smith9fcce652012-03-07 08:35:16 +00001560
1561 // We're building a user-defined literal.
1562 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smithdd66be72012-03-08 01:34:56 +00001563 SourceLocation UDSuffixLoc =
1564 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1565 Literal.getUDSuffixOffset());
Richard Smith9fcce652012-03-07 08:35:16 +00001566
Richard Smith36f5cfe2012-03-09 08:00:36 +00001567 // Make sure we're allowed user-defined literals here.
1568 if (!UDLScope)
1569 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1570
Richard Smith9fcce652012-03-07 08:35:16 +00001571 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1572 // operator "" X (str, len)
1573 QualType SizeType = Context.getSizeType();
Richard Smithb328e292013-10-07 19:57:58 +00001574
1575 DeclarationName OpName =
1576 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1577 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1578 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1579
1580 QualType ArgTy[] = {
1581 Context.getArrayDecayedType(StrTy), SizeType
1582 };
1583
1584 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1585 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1586 /*AllowRaw*/false, /*AllowTemplate*/false,
1587 /*AllowStringTemplate*/true)) {
1588
1589 case LOLR_Cooked: {
1590 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1591 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1592 StringTokLocs[0]);
1593 Expr *Args[] = { Lit, LenArg };
1594
1595 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1596 }
1597
1598 case LOLR_StringTemplate: {
1599 TemplateArgumentListInfo ExplicitArgs;
1600
1601 unsigned CharBits = Context.getIntWidth(CharTy);
1602 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1603 llvm::APSInt Value(CharBits, CharIsUnsigned);
1604
1605 TemplateArgument TypeArg(CharTy);
1606 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1607 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1608
1609 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1610 Value = Lit->getCodeUnit(I);
1611 TemplateArgument Arg(Context, Value, CharTy);
1612 TemplateArgumentLocInfo ArgInfo;
1613 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1614 }
1615 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1616 &ExplicitArgs);
1617 }
1618 case LOLR_Raw:
1619 case LOLR_Template:
1620 llvm_unreachable("unexpected literal operator lookup result");
1621 case LOLR_Error:
1622 return ExprError();
1623 }
1624 llvm_unreachable("unexpected literal operator lookup result");
Reid Spencer5f016e22007-07-11 17:01:13 +00001625}
1626
John McCall60d7b3a2010-08-24 06:29:42 +00001627ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001628Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001629 SourceLocation Loc,
1630 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001631 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001632 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001633}
1634
John McCall76a40212011-02-09 01:13:10 +00001635/// BuildDeclRefExpr - Build an expression that references a
1636/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001637ExprResult
John McCall76a40212011-02-09 01:13:10 +00001638Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001639 const DeclarationNameInfo &NameInfo,
Larisse Voufoef4579c2013-08-06 01:03:05 +00001640 const CXXScopeSpec *SS, NamedDecl *FoundD,
1641 const TemplateArgumentListInfo *TemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001642 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001643 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1644 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001645 if (CheckCUDATarget(Caller, Callee)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001646 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001647 << IdentifyCUDATarget(Callee) << D->getIdentifier()
1648 << IdentifyCUDATarget(Caller);
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00001649 Diag(D->getLocation(), diag::note_previous_decl)
1650 << D->getIdentifier();
1651 return ExprError();
1652 }
1653 }
1654
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001655 bool RefersToCapturedVariable =
1656 isa<VarDecl>(D) &&
1657 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
John McCallf4b88a42012-03-10 09:33:50 +00001658
Larisse Voufoef4579c2013-08-06 01:03:05 +00001659 DeclRefExpr *E;
1660 if (isa<VarTemplateSpecializationDecl>(D)) {
1661 VarTemplateSpecializationDecl *VarSpec =
1662 cast<VarTemplateSpecializationDecl>(D);
1663
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001664 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1665 : NestedNameSpecifierLoc(),
1666 VarSpec->getTemplateKeywordLoc(), D,
1667 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1668 FoundD, TemplateArgs);
Larisse Voufoef4579c2013-08-06 01:03:05 +00001669 } else {
1670 assert(!TemplateArgs && "No template arguments for non-variable"
Stephen Hines651f13c2014-04-23 16:59:28 -07001671 " template specialization references");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001672 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1673 : NestedNameSpecifierLoc(),
1674 SourceLocation(), D, RefersToCapturedVariable,
1675 NameInfo, Ty, VK, FoundD);
Larisse Voufoef4579c2013-08-06 01:03:05 +00001676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Eli Friedman5f2987c2012-02-02 03:46:19 +00001678 MarkDeclRefReferenced(E);
John McCall7eb0a9e2010-11-24 05:12:34 +00001679
Jordan Rose7a270482012-09-28 22:21:35 +00001680 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001681 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1682 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
Fariborz Jahanian569b4ad2013-05-21 21:20:26 +00001683 recordUseOfEvaluatedWeak(E);
Jordan Rose7a270482012-09-28 22:21:35 +00001684
John McCall7eb0a9e2010-11-24 05:12:34 +00001685 // Just in case we're building an illegal pointer-to-member.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001686 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1687 if (FD && FD->isBitField())
John McCall7eb0a9e2010-11-24 05:12:34 +00001688 E->setObjectKind(OK_BitField);
1689
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001690 return E;
Douglas Gregor1a49af92009-01-06 05:10:23 +00001691}
1692
Abramo Bagnara25777432010-08-11 22:01:17 +00001693/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001694/// possibly a list of template arguments.
1695///
1696/// If this produces template arguments, it is permitted to call
1697/// DecomposeTemplateName.
1698///
1699/// This actually loses a lot of source location information for
1700/// non-standard name kinds; we should consider preserving that in
1701/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001702void
1703Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1704 TemplateArgumentListInfo &Buffer,
1705 DeclarationNameInfo &NameInfo,
1706 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001707 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1708 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1709 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1710
Benjamin Kramer5354e772012-08-23 23:38:35 +00001711 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
John McCall129e2df2009-11-30 22:42:35 +00001712 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001713 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001714
John McCall2b5289b2010-08-23 07:28:44 +00001715 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001716 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001717 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001718 TemplateArgs = &Buffer;
1719 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001720 NameInfo = GetNameFromUnqualifiedId(Id);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001721 TemplateArgs = nullptr;
John McCall129e2df2009-11-30 22:42:35 +00001722 }
1723}
1724
Stephen Hines176edba2014-12-01 14:53:08 -08001725static void emitEmptyLookupTypoDiagnostic(
1726 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1727 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1728 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1729 DeclContext *Ctx =
1730 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1731 if (!TC) {
1732 // Emit a special diagnostic for failed member lookups.
1733 // FIXME: computing the declaration context might fail here (?)
1734 if (Ctx)
1735 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1736 << SS.getRange();
1737 else
1738 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1739 return;
1740 }
1741
1742 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1743 bool DroppedSpecifier =
1744 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1745 unsigned NoteID =
1746 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1747 ? diag::note_implicit_param_decl
1748 : diag::note_previous_decl;
1749 if (!Ctx)
1750 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1751 SemaRef.PDiag(NoteID));
1752 else
1753 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1754 << Typo << Ctx << DroppedSpecifier
1755 << SS.getRange(),
1756 SemaRef.PDiag(NoteID));
1757}
1758
John McCall578b69b2009-12-16 08:11:27 +00001759/// Diagnose an empty lookup.
1760///
1761/// \return false if new lookup candidates were found
Stephen Hines176edba2014-12-01 14:53:08 -08001762bool
1763Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1764 std::unique_ptr<CorrectionCandidateCallback> CCC,
1765 TemplateArgumentListInfo *ExplicitTemplateArgs,
1766 ArrayRef<Expr *> Args, TypoExpr **Out) {
John McCall578b69b2009-12-16 08:11:27 +00001767 DeclarationName Name = R.getLookupName();
1768
John McCall578b69b2009-12-16 08:11:27 +00001769 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001770 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001771 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1772 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001773 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001774 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001775 diagnostic_suggest = diag::err_undeclared_use_suggest;
1776 }
John McCall578b69b2009-12-16 08:11:27 +00001777
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001778 // If the original lookup was an unqualified lookup, fake an
1779 // unqualified lookup. This is useful when (for example) the
1780 // original lookup would not have found something because it was a
1781 // dependent name.
David Blaikie4872e102012-05-28 01:26:45 +00001782 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001783 ? CurContext : nullptr;
Francois Pichetc8ff9152011-11-25 01:10:54 +00001784 while (DC) {
John McCall578b69b2009-12-16 08:11:27 +00001785 if (isa<CXXRecordDecl>(DC)) {
1786 LookupQualifiedName(R, DC);
1787
1788 if (!R.empty()) {
1789 // Don't give errors about ambiguities in this lookup.
1790 R.suppressDiagnostics();
1791
Francois Pichete6226ae2011-11-17 03:44:24 +00001792 // During a default argument instantiation the CurContext points
1793 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1794 // function parameter list, hence add an explicit check.
1795 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1796 ActiveTemplateInstantiations.back().Kind ==
1797 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCall578b69b2009-12-16 08:11:27 +00001798 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1799 bool isInstance = CurMethod &&
1800 CurMethod->isInstance() &&
Francois Pichete6226ae2011-11-17 03:44:24 +00001801 DC == CurMethod->getParent() && !isDefaultArgument;
1802
John McCall578b69b2009-12-16 08:11:27 +00001803
1804 // Give a code modification hint to insert 'this->'.
1805 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1806 // Actually quite difficult!
Stephen Hines651f13c2014-04-23 16:59:28 -07001807 if (getLangOpts().MSVCCompat)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001808 diagnostic = diag::ext_found_via_dependent_bases_lookup;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001809 if (isInstance) {
Nico Weber94c4d612012-06-22 16:39:39 +00001810 Diag(R.getNameLoc(), diagnostic) << Name
1811 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewycky03d98c52010-07-06 19:51:49 +00001812 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1813 CallsUndergoingInstantiation.back()->getCallee());
Nico Weber94c4d612012-06-22 16:39:39 +00001814
Nico Weber94c4d612012-06-22 16:39:39 +00001815 CXXMethodDecl *DepMethod;
Douglas Gregore79ce292013-03-26 22:43:55 +00001816 if (CurMethod->isDependentContext())
1817 DepMethod = CurMethod;
1818 else if (CurMethod->getTemplatedKind() ==
Nico Weber94c4d612012-06-22 16:39:39 +00001819 FunctionDecl::TK_FunctionTemplateSpecialization)
1820 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1821 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1822 else
1823 DepMethod = cast<CXXMethodDecl>(
1824 CurMethod->getInstantiatedFromMemberFunction());
1825 assert(DepMethod && "No template pattern found");
1826
1827 QualType DepThisType = DepMethod->getThisType(Context);
1828 CheckCXXThisCapture(R.getNameLoc());
1829 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1830 R.getNameLoc(), DepThisType, false);
1831 TemplateArgumentListInfo TList;
1832 if (ULE->hasExplicitTemplateArgs())
1833 ULE->copyTemplateArgumentsInto(TList);
1834
1835 CXXScopeSpec SS;
1836 SS.Adopt(ULE->getQualifierLoc());
1837 CXXDependentScopeMemberExpr *DepExpr =
1838 CXXDependentScopeMemberExpr::Create(
1839 Context, DepThis, DepThisType, true, SourceLocation(),
1840 SS.getWithLocInContext(Context),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001841 ULE->getTemplateKeywordLoc(), nullptr,
Nico Weber94c4d612012-06-22 16:39:39 +00001842 R.getLookupNameInfo(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001843 ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
Nico Weber94c4d612012-06-22 16:39:39 +00001844 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Nick Lewycky03d98c52010-07-06 19:51:49 +00001845 } else {
John McCall578b69b2009-12-16 08:11:27 +00001846 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001847 }
John McCall578b69b2009-12-16 08:11:27 +00001848
1849 // Do we really want to note all of these?
1850 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1851 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1852
Francois Pichete6226ae2011-11-17 03:44:24 +00001853 // Return true if we are inside a default argument instantiation
1854 // and the found name refers to an instance member function, otherwise
1855 // the function calling DiagnoseEmptyLookup will try to create an
1856 // implicit member call and this is wrong for default argument.
1857 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1858 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1859 return true;
1860 }
1861
John McCall578b69b2009-12-16 08:11:27 +00001862 // Tell the callee to try to recover.
1863 return false;
1864 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001865
1866 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001867 }
Francois Pichetc8ff9152011-11-25 01:10:54 +00001868
1869 // In Microsoft mode, if we are performing lookup from within a friend
1870 // function definition declared at class scope then we must set
1871 // DC to the lexical parent to be able to search into the parent
1872 // class.
Stephen Hines651f13c2014-04-23 16:59:28 -07001873 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00001874 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1875 DC->getLexicalParent()->isRecord())
1876 DC = DC->getLexicalParent();
1877 else
1878 DC = DC->getParent();
John McCall578b69b2009-12-16 08:11:27 +00001879 }
1880
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001881 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001882 TypoCorrection Corrected;
Stephen Hines176edba2014-12-01 14:53:08 -08001883 if (S && Out) {
1884 SourceLocation TypoLoc = R.getNameLoc();
1885 assert(!ExplicitTemplateArgs &&
1886 "Diagnosing an empty lookup with explicit template args!");
1887 *Out = CorrectTypoDelayed(
1888 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1889 [=](const TypoCorrection &TC) {
1890 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1891 diagnostic, diagnostic_suggest);
1892 },
1893 nullptr, CTK_ErrorRecovery);
1894 if (*Out)
1895 return true;
1896 } else if (S && (Corrected =
1897 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1898 &SS, std::move(CCC), CTK_ErrorRecovery))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001899 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
Richard Smith2d670972013-08-17 00:46:16 +00001900 bool DroppedSpecifier =
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00001901 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001902 R.setLookupName(Corrected.getCorrection());
1903
Richard Smith2d670972013-08-17 00:46:16 +00001904 bool AcceptableWithRecovery = false;
1905 bool AcceptableWithoutRecovery = false;
1906 NamedDecl *ND = Corrected.getCorrectionDecl();
1907 if (ND) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001908 if (Corrected.isOverloaded()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001909 OverloadCandidateSet OCS(R.getNameLoc(),
1910 OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001911 OverloadCandidateSet::iterator Best;
1912 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1913 CDEnd = Corrected.end();
1914 CD != CDEnd; ++CD) {
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001915 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00001916 dyn_cast<FunctionTemplateDecl>(*CD))
1917 AddTemplateOverloadCandidate(
1918 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00001919 Args, OCS);
Kaelyn Uhrainadc7a732011-08-08 17:35:31 +00001920 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1921 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1922 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001923 Args, OCS);
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001924 }
1925 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
Richard Smith2d670972013-08-17 00:46:16 +00001926 case OR_Success:
1927 ND = Best->Function;
1928 Corrected.setCorrectionDecl(ND);
1929 break;
1930 default:
1931 // FIXME: Arbitrarily pick the first declaration for the note.
1932 Corrected.setCorrectionDecl(ND);
1933 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001934 }
1935 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001936 R.addDecl(ND);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001937 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1938 CXXRecordDecl *Record = nullptr;
1939 if (Corrected.getCorrectionSpecifier()) {
1940 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1941 Record = Ty->getAsCXXRecordDecl();
1942 }
1943 if (!Record)
1944 Record = cast<CXXRecordDecl>(
1945 ND->getDeclContext()->getRedeclContext());
1946 R.setNamingClass(Record);
1947 }
Ted Kremenek63631bd2013-02-21 21:40:44 +00001948
Richard Smith2d670972013-08-17 00:46:16 +00001949 AcceptableWithRecovery =
1950 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1951 // FIXME: If we ended up with a typo for a type name or
1952 // Objective-C class name, we're in trouble because the parser
1953 // is in the wrong place to recover. Suggest the typo
1954 // correction, but don't make it a fix-it since we're not going
1955 // to recover well anyway.
1956 AcceptableWithoutRecovery =
1957 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001958 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001959 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001960 // because we aren't able to recover.
Richard Smith2d670972013-08-17 00:46:16 +00001961 AcceptableWithoutRecovery = true;
1962 }
1963
1964 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1965 unsigned NoteID = (Corrected.getCorrectionDecl() &&
1966 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1967 ? diag::note_implicit_param_decl
1968 : diag::note_previous_decl;
Douglas Gregord203a162010-01-01 00:15:04 +00001969 if (SS.isEmpty())
Richard Smith2d670972013-08-17 00:46:16 +00001970 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1971 PDiag(NoteID), AcceptableWithRecovery);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001972 else
Richard Smith2d670972013-08-17 00:46:16 +00001973 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1974 << Name << computeDeclContext(SS, false)
1975 << DroppedSpecifier << SS.getRange(),
1976 PDiag(NoteID), AcceptableWithRecovery);
1977
1978 // Tell the callee whether to try to recover.
1979 return !AcceptableWithRecovery;
Douglas Gregord203a162010-01-01 00:15:04 +00001980 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001981 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001982 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001983
1984 // Emit a special diagnostic for failed member lookups.
1985 // FIXME: computing the declaration context might fail here (?)
1986 if (!SS.isEmpty()) {
1987 Diag(R.getNameLoc(), diag::err_no_member)
1988 << Name << computeDeclContext(SS, false)
1989 << SS.getRange();
1990 return true;
1991 }
1992
John McCall578b69b2009-12-16 08:11:27 +00001993 // Give up, we can't recover.
1994 Diag(R.getNameLoc(), diagnostic) << Name;
1995 return true;
1996}
1997
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001998/// In Microsoft mode, if we are inside a template class whose parent class has
1999/// dependent base classes, and we can't resolve an unqualified identifier, then
2000/// assume the identifier is a member of a dependent base class. We can only
2001/// recover successfully in static methods, instance methods, and other contexts
2002/// where 'this' is available. This doesn't precisely match MSVC's
2003/// instantiation model, but it's close enough.
2004static Expr *
2005recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2006 DeclarationNameInfo &NameInfo,
2007 SourceLocation TemplateKWLoc,
2008 const TemplateArgumentListInfo *TemplateArgs) {
2009 // Only try to recover from lookup into dependent bases in static methods or
2010 // contexts where 'this' is available.
2011 QualType ThisType = S.getCurrentThisType();
2012 const CXXRecordDecl *RD = nullptr;
2013 if (!ThisType.isNull())
2014 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2015 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2016 RD = MD->getParent();
2017 if (!RD || !RD->hasAnyDependentBases())
2018 return nullptr;
2019
2020 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2021 // is available, suggest inserting 'this->' as a fixit.
2022 SourceLocation Loc = NameInfo.getLoc();
2023 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2024 DB << NameInfo.getName() << RD;
2025
2026 if (!ThisType.isNull()) {
2027 DB << FixItHint::CreateInsertion(Loc, "this->");
2028 return CXXDependentScopeMemberExpr::Create(
2029 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2030 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2031 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2032 }
2033
2034 // Synthesize a fake NNS that points to the derived class. This will
2035 // perform name lookup during template instantiation.
2036 CXXScopeSpec SS;
2037 auto *NNS =
2038 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2039 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2040 return DependentScopeDeclRefExpr::Create(
2041 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2042 TemplateArgs);
2043}
2044
Stephen Hines176edba2014-12-01 14:53:08 -08002045ExprResult
2046Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2047 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2048 bool HasTrailingLParen, bool IsAddressOfOperand,
2049 std::unique_ptr<CorrectionCandidateCallback> CCC,
2050 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
Richard Trieuccd891a2011-09-09 01:45:06 +00002051 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCallf7a1a742009-11-24 19:00:30 +00002052 "cannot be direct & operand and have a trailing lparen");
John McCallf7a1a742009-11-24 19:00:30 +00002053 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002054 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002055
John McCall129e2df2009-11-30 22:42:35 +00002056 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00002057
2058 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00002059 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00002060 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00002061 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002062
Abramo Bagnara25777432010-08-11 22:01:17 +00002063 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00002064 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00002065 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002066
John McCallf7a1a742009-11-24 19:00:30 +00002067 // C++ [temp.dep.expr]p3:
2068 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00002069 // -- an identifier that was declared with a dependent type,
2070 // (note: handled after lookup)
2071 // -- a template-id that is dependent,
2072 // (note: handled in BuildTemplateIdExpr)
2073 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00002074 // -- a nested-name-specifier that contains a class-name that
2075 // names a dependent type.
2076 // Determine whether this is a member of an unknown specialization;
2077 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00002078 bool DependentID = false;
2079 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2080 Name.getCXXNameType()->isDependentType()) {
2081 DependentID = true;
2082 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00002083 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00002084 if (RequireCompleteDeclContext(SS, DC))
2085 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00002086 } else {
2087 DependentID = true;
2088 }
2089 }
2090
Chris Lattner337e5502011-02-18 01:27:55 +00002091 if (DependentID)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002092 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2093 IsAddressOfOperand, TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00002094
John McCallf7a1a742009-11-24 19:00:30 +00002095 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00002096 LookupResult R(*this, NameInfo,
2097 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2098 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002099 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00002100 // Lookup the template name again to correctly establish the context in
2101 // which it was found. This is really unfortunate as we already did the
2102 // lookup to determine that it was a template name in the first place. If
2103 // this becomes a performance hit, we can work harder to preserve those
2104 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002105 bool MemberOfUnknownSpecialization;
2106 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2107 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00002108
2109 if (MemberOfUnknownSpecialization ||
2110 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002111 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2112 IsAddressOfOperand, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00002113 } else {
Benjamin Kramerb7ff74a2012-01-20 14:57:34 +00002114 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002115 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00002117 // If the result might be in a dependent base class, this is a dependent
2118 // id-expression.
2119 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002120 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2121 IsAddressOfOperand, TemplateArgs);
2122
John McCallf7a1a742009-11-24 19:00:30 +00002123 // If this reference is in an Objective-C method, then we need to do
2124 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002125 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00002126 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00002127 if (E.isInvalid())
2128 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002130 if (Expr *Ex = E.getAs<Expr>())
2131 return Ex;
Steve Naroffe3e9add2008-06-02 23:03:37 +00002132 }
Chris Lattner8a934232008-03-31 00:36:02 +00002133 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00002134
John McCallf7a1a742009-11-24 19:00:30 +00002135 if (R.isAmbiguous())
2136 return ExprError();
2137
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002138 // This could be an implicitly declared function reference (legal in C90,
2139 // extension in C99, forbidden in C++).
2140 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2141 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2142 if (D) R.addDecl(D);
2143 }
2144
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002145 // Determine whether this name might be a candidate for
2146 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00002147 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002148
John McCallf7a1a742009-11-24 19:00:30 +00002149 if (R.empty() && !ADL) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002150 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2151 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2152 TemplateKWLoc, TemplateArgs))
2153 return E;
John McCallf7a1a742009-11-24 19:00:30 +00002154 }
2155
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002156 // Don't diagnose an empty lookup for inline assembly.
2157 if (IsInlineAsmIdentifier)
2158 return ExprError();
2159
John McCallf7a1a742009-11-24 19:00:30 +00002160 // If this name wasn't predeclared and if this is not a function
2161 // call, diagnose the problem.
Stephen Hines176edba2014-12-01 14:53:08 -08002162 TypoExpr *TE = nullptr;
2163 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2164 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2165 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002166 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2167 "Typo correction callback misconfigured");
Stephen Hines176edba2014-12-01 14:53:08 -08002168 if (CCC) {
2169 // Make sure the callback knows what the typo being diagnosed is.
2170 CCC->setTypoName(II);
2171 if (SS.isValid())
2172 CCC->setTypoNNS(SS.getScopeRep());
2173 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002174 if (DiagnoseEmptyLookup(S, SS, R,
2175 CCC ? std::move(CCC) : std::move(DefaultValidator),
2176 nullptr, None, &TE)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002177 if (TE && KeywordReplacement) {
2178 auto &State = getTypoExprState(TE);
2179 auto BestTC = State.Consumer->getNextCorrection();
2180 if (BestTC.isKeyword()) {
2181 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2182 if (State.DiagHandler)
2183 State.DiagHandler(BestTC);
2184 KeywordReplacement->startToken();
2185 KeywordReplacement->setKind(II->getTokenID());
2186 KeywordReplacement->setIdentifierInfo(II);
2187 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2188 // Clean up the state associated with the TypoExpr, since it has
2189 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2190 clearDelayedTypo(TE);
2191 // Signal that a correction to a keyword was performed by returning a
2192 // valid-but-null ExprResult.
2193 return (Expr*)nullptr;
2194 }
2195 State.Consumer->resetCorrectionStream();
2196 }
2197 return TE ? TE : ExprError();
2198 }
Francois Pichetfce1a3a2011-09-24 10:38:05 +00002199
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002200 assert(!R.empty() &&
2201 "DiagnoseEmptyLookup returned false but added no results");
2202
2203 // If we found an Objective-C instance variable, let
2204 // LookupInObjCMethod build the appropriate expression to
2205 // reference the ivar.
2206 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2207 R.clear();
2208 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2209 // In a hopelessly buggy code, Objective-C instance variable
2210 // lookup fails and no expression will be built to reference it.
2211 if (!E.isInvalid() && !E.get())
Chad Rosier942dfe22013-05-24 18:32:55 +00002212 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002213 return E;
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 }
2215 }
Mike Stump1eb44332009-09-09 15:08:12 +00002216
John McCallf7a1a742009-11-24 19:00:30 +00002217 // This is guaranteed from this point on.
2218 assert(!R.empty() || ADL);
2219
John McCallaa81e162009-12-01 22:10:20 +00002220 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00002221 // C++ [class.mfct.non-static]p3:
2222 // When an id-expression that is not part of a class member access
2223 // syntax and not used to form a pointer to member is used in the
2224 // body of a non-static member function of class X, if name lookup
2225 // resolves the name in the id-expression to a non-static non-type
2226 // member of some class C, the id-expression is transformed into a
2227 // class member access expression using (*this) as the
2228 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00002229 //
2230 // But we don't actually need to do this for '&' operands if R
2231 // resolved to a function or overloaded function set, because the
2232 // expression is ill-formed if it actually works out to be a
2233 // non-static member function:
2234 //
2235 // C++ [expr.ref]p4:
2236 // Otherwise, if E1.E2 refers to a non-static member function. . .
2237 // [t]he expression can be used only as the left-hand operand of a
2238 // member function call.
2239 //
2240 // There are other safeguards against such uses, but it's important
2241 // to get this right here so that we don't end up making a
2242 // spuriously dependent expression if we're inside a dependent
2243 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00002244 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00002245 bool MightBeImplicitMember;
Richard Trieuccd891a2011-09-09 01:45:06 +00002246 if (!IsAddressOfOperand)
John McCall9c72c602010-08-27 09:08:28 +00002247 MightBeImplicitMember = true;
2248 else if (!SS.isEmpty())
2249 MightBeImplicitMember = false;
2250 else if (R.isOverloadedResult())
2251 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00002252 else if (R.isUnresolvableResult())
2253 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00002254 else
Francois Pichet87c2e122010-11-21 06:08:52 +00002255 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
Reid Klecknerf67129a2013-06-19 16:37:23 +00002256 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2257 isa<MSPropertyDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00002258
2259 if (MightBeImplicitMember)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002260 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2261 R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002262 }
2263
Larisse Voufoef4579c2013-08-06 01:03:05 +00002264 if (TemplateArgs || TemplateKWLoc.isValid()) {
2265
2266 // In C++1y, if this is a variable template id, then check it
2267 // in BuildTemplateIdExpr().
2268 // The single lookup result must be a variable template declaration.
2269 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2270 Id.TemplateId->Kind == TNK_Var_template) {
2271 assert(R.getAsSingle<VarTemplateDecl>() &&
2272 "There should only be one declaration found.");
2273 }
2274
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002275 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002276 }
John McCall5b3f9132009-11-22 01:44:31 +00002277
John McCallf7a1a742009-11-24 19:00:30 +00002278 return BuildDeclarationNameExpr(SS, R, ADL);
2279}
2280
John McCall129e2df2009-11-30 22:42:35 +00002281/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2282/// declaration name, generally during template instantiation.
2283/// There's a large number of things which don't need to be done along
2284/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002285ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002286Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Richard Smithefeeccf2012-10-21 03:28:35 +00002287 const DeclarationNameInfo &NameInfo,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002288 bool IsAddressOfOperand,
2289 TypeSourceInfo **RecoveryTSI) {
Richard Smith713c2872012-10-23 19:56:01 +00002290 DeclContext *DC = computeDeclContext(SS, false);
2291 if (!DC)
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00002292 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002293 NameInfo, /*TemplateArgs=*/nullptr);
John McCallf7a1a742009-11-24 19:00:30 +00002294
John McCall77bb1aa2010-05-01 00:40:08 +00002295 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002296 return ExprError();
2297
Abramo Bagnara25777432010-08-11 22:01:17 +00002298 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002299 LookupQualifiedName(R, DC);
2300
2301 if (R.isAmbiguous())
2302 return ExprError();
2303
Richard Smith713c2872012-10-23 19:56:01 +00002304 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2305 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002306 NameInfo, /*TemplateArgs=*/nullptr);
Richard Smith713c2872012-10-23 19:56:01 +00002307
John McCallf7a1a742009-11-24 19:00:30 +00002308 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002309 Diag(NameInfo.getLoc(), diag::err_no_member)
2310 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002311 return ExprError();
2312 }
2313
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002314 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2315 // Diagnose a missing typename if this resolved unambiguously to a type in
2316 // a dependent context. If we can recover with a type, downgrade this to
2317 // a warning in Microsoft compatibility mode.
2318 unsigned DiagID = diag::err_typename_missing;
2319 if (RecoveryTSI && getLangOpts().MSVCCompat)
2320 DiagID = diag::ext_typename_missing;
2321 SourceLocation Loc = SS.getBeginLoc();
2322 auto D = Diag(Loc, DiagID);
2323 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2324 << SourceRange(Loc, NameInfo.getEndLoc());
2325
2326 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2327 // context.
2328 if (!RecoveryTSI)
2329 return ExprError();
2330
2331 // Only issue the fixit if we're prepared to recover.
2332 D << FixItHint::CreateInsertion(Loc, "typename ");
2333
2334 // Recover by pretending this was an elaborated type.
2335 QualType Ty = Context.getTypeDeclType(TD);
2336 TypeLocBuilder TLB;
2337 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2338
2339 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2340 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2341 QTL.setElaboratedKeywordLoc(SourceLocation());
2342 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2343
2344 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2345
2346 return ExprEmpty();
2347 }
2348
Richard Smithefeeccf2012-10-21 03:28:35 +00002349 // Defend against this resolving to an implicit member access. We usually
2350 // won't get here if this might be a legitimate a class member (we end up in
2351 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2352 // a pointer-to-member or in an unevaluated context in C++11.
2353 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2354 return BuildPossibleImplicitMemberExpr(SS,
2355 /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002356 R, /*TemplateArgs=*/nullptr);
Richard Smithefeeccf2012-10-21 03:28:35 +00002357
2358 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
John McCallf7a1a742009-11-24 19:00:30 +00002359}
2360
2361/// LookupInObjCMethod - The parser has read a name in, and Sema has
2362/// detected that we're currently inside an ObjC method. Perform some
2363/// additional lookup.
2364///
2365/// Ideally, most of this would be done by lookup, but there's
2366/// actually quite a lot of extra work involved.
2367///
2368/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002369ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002370Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002371 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002372 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002373 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Fariborz Jahanian0dc4ff22013-02-18 17:22:23 +00002374
2375 // Check for error condition which is already reported.
2376 if (!CurMethod)
2377 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002378
John McCallf7a1a742009-11-24 19:00:30 +00002379 // There are two cases to handle here. 1) scoped lookup could have failed,
2380 // in which case we should look for an ivar. 2) scoped lookup could have
2381 // found a decl, but that decl is outside the current instance method (i.e.
2382 // a global variable). In these two cases, we do a lookup for an ivar with
2383 // this name, if the lookup sucedes, we replace it our current decl.
2384
2385 // If we're in a class method, we don't normally want to look for
2386 // ivars. But if we don't find anything else, and there's an
2387 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002388 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002389
2390 bool LookForIvars;
2391 if (Lookup.empty())
2392 LookForIvars = true;
2393 else if (IsClassMethod)
2394 LookForIvars = false;
2395 else
2396 LookForIvars = (Lookup.isSingleResult() &&
2397 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002398 ObjCInterfaceDecl *IFace = nullptr;
John McCallf7a1a742009-11-24 19:00:30 +00002399 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002400 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002401 ObjCInterfaceDecl *ClassDeclared;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002402 ObjCIvarDecl *IV = nullptr;
Argyrios Kyrtzidis7c81c2a2011-10-19 02:25:16 +00002403 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCallf7a1a742009-11-24 19:00:30 +00002404 // Diagnose using an ivar in a class method.
2405 if (IsClassMethod)
2406 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2407 << IV->getDeclName());
2408
2409 // If we're referencing an invalid decl, just return this as a silent
2410 // error node. The error diagnostic was already emitted on the decl.
2411 if (IV->isInvalidDecl())
2412 return ExprError();
2413
2414 // Check if referencing a field with __attribute__((deprecated)).
2415 if (DiagnoseUseOfDecl(IV, Loc))
2416 return ExprError();
2417
2418 // Diagnose the use of an ivar outside of the declaring class.
2419 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00002420 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002421 !getLangOpts().DebuggerSupport)
John McCallf7a1a742009-11-24 19:00:30 +00002422 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2423
2424 // FIXME: This should use a new expr for a direct reference, don't
2425 // turn this into Self->ivar, just return a BareIVarExpr or something.
2426 IdentifierInfo &II = Context.Idents.get("self");
2427 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002428 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00002429 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00002430 CXXScopeSpec SelfScopeSpec;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002431 SourceLocation TemplateKWLoc;
2432 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002433 SelfName, false, false);
2434 if (SelfExpr.isInvalid())
2435 return ExprError();
2436
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002437 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
John Wiegley429bb272011-04-08 18:41:53 +00002438 if (SelfExpr.isInvalid())
2439 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002440
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +00002441 MarkAnyDeclReferenced(Loc, IV, true);
Stephen Hines651f13c2014-04-23 16:59:28 -07002442
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002443 ObjCMethodFamily MF = CurMethod->getMethodFamily();
Fariborz Jahanian26202292013-02-14 19:07:19 +00002444 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2445 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00002446 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
Jordan Rose7a270482012-09-28 22:21:35 +00002447
Stephen Hines176edba2014-12-01 14:53:08 -08002448 ObjCIvarRefExpr *Result = new (Context)
2449 ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2450 SelfExpr.get(), true, true);
Jordan Rose7a270482012-09-28 22:21:35 +00002451
2452 if (getLangOpts().ObjCAutoRefCount) {
2453 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002454 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Fariborz Jahanian569b4ad2013-05-21 21:20:26 +00002455 recordUseOfEvaluatedWeak(Result);
Jordan Rose7a270482012-09-28 22:21:35 +00002456 }
Fariborz Jahanian3f001ff2012-10-03 17:55:29 +00002457 if (CurContext->isClosure())
2458 Diag(Loc, diag::warn_implicitly_retains_self)
2459 << FixItHint::CreateInsertion(Loc, "self->");
Jordan Rose7a270482012-09-28 22:21:35 +00002460 }
2461
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002462 return Result;
John McCallf7a1a742009-11-24 19:00:30 +00002463 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002464 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002465 // We should warn if a local variable hides an ivar.
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002466 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2467 ObjCInterfaceDecl *ClassDeclared;
2468 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2469 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor60ef3082011-12-15 00:29:59 +00002470 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian90f7b622011-11-08 22:51:27 +00002471 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2472 }
John McCallf7a1a742009-11-24 19:00:30 +00002473 }
Fariborz Jahanianb5ea9db2011-12-20 22:21:08 +00002474 } else if (Lookup.isSingleResult() &&
2475 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2476 // If accessing a stand-alone ivar in a class method, this is an error.
2477 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2478 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2479 << IV->getDeclName());
John McCallf7a1a742009-11-24 19:00:30 +00002480 }
2481
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002482 if (Lookup.empty() && II && AllowBuiltinCreation) {
2483 // FIXME. Consolidate this with similar code in LookupName.
2484 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002485 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002486 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2487 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2488 S, Lookup.isForRedeclaration(),
2489 Lookup.getNameLoc());
2490 if (D) Lookup.addDecl(D);
2491 }
2492 }
2493 }
John McCallf7a1a742009-11-24 19:00:30 +00002494 // Sentinel value saying that we didn't do anything special.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002495 return ExprResult((Expr *)nullptr);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002496}
John McCallba135432009-11-21 08:51:07 +00002497
John McCall6bb80172010-03-30 21:47:33 +00002498/// \brief Cast a base object to a member's actual type.
2499///
2500/// Logically this happens in three phases:
2501///
2502/// * First we cast from the base type to the naming class.
2503/// The naming class is the class into which we were looking
2504/// when we found the member; it's the qualifier type if a
2505/// qualifier was provided, and otherwise it's the base type.
2506///
2507/// * Next we cast from the naming class to the declaring class.
2508/// If the member we found was brought into a class's scope by
2509/// a using declaration, this is that class; otherwise it's
2510/// the class declaring the member.
2511///
2512/// * Finally we cast from the declaring class to the "true"
2513/// declaring class of the member. This conversion does not
2514/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002515ExprResult
2516Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002517 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002518 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002519 NamedDecl *Member) {
2520 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2521 if (!RD)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002522 return From;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002523
Douglas Gregor5fccd362010-03-03 23:55:11 +00002524 QualType DestRecordType;
2525 QualType DestType;
2526 QualType FromRecordType;
2527 QualType FromType = From->getType();
2528 bool PointerConversions = false;
2529 if (isa<FieldDecl>(Member)) {
2530 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002531
Douglas Gregor5fccd362010-03-03 23:55:11 +00002532 if (FromType->getAs<PointerType>()) {
2533 DestType = Context.getPointerType(DestRecordType);
2534 FromRecordType = FromType->getPointeeType();
2535 PointerConversions = true;
2536 } else {
2537 DestType = DestRecordType;
2538 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002539 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002540 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2541 if (Method->isStatic())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002542 return From;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002543
Douglas Gregor5fccd362010-03-03 23:55:11 +00002544 DestType = Method->getThisType(Context);
2545 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002546
Douglas Gregor5fccd362010-03-03 23:55:11 +00002547 if (FromType->getAs<PointerType>()) {
2548 FromRecordType = FromType->getPointeeType();
2549 PointerConversions = true;
2550 } else {
2551 FromRecordType = FromType;
2552 DestType = DestRecordType;
2553 }
2554 } else {
2555 // No conversion necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002556 return From;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002557 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002558
Douglas Gregor5fccd362010-03-03 23:55:11 +00002559 if (DestType->isDependentType() || FromType->isDependentType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002560 return From;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002561
Douglas Gregor5fccd362010-03-03 23:55:11 +00002562 // If the unqualified types are the same, no conversion is necessary.
2563 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002564 return From;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002565
John McCall6bb80172010-03-30 21:47:33 +00002566 SourceRange FromRange = From->getSourceRange();
2567 SourceLocation FromLoc = FromRange.getBegin();
2568
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002569 ExprValueKind VK = From->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00002570
Douglas Gregor5fccd362010-03-03 23:55:11 +00002571 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002572 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002573 // class name.
2574 //
2575 // If the member was a qualified name and the qualified referred to a
2576 // specific base subobject type, we'll cast to that intermediate type
2577 // first and then to the object in which the member is declared. That allows
2578 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2579 //
2580 // class Base { public: int x; };
2581 // class Derived1 : public Base { };
2582 // class Derived2 : public Base { };
2583 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2584 //
2585 // void VeryDerived::f() {
2586 // x = 17; // error: ambiguous base subobjects
2587 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2588 // }
David Majnemer8b051ce2013-08-05 04:53:41 +00002589 if (Qualifier && Qualifier->getAsType()) {
John McCall6bb80172010-03-30 21:47:33 +00002590 QualType QType = QualType(Qualifier->getAsType(), 0);
John McCall6bb80172010-03-30 21:47:33 +00002591 assert(QType->isRecordType() && "lookup done with non-record type");
2592
2593 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2594
2595 // In C++98, the qualifier type doesn't actually have to be a base
2596 // type of the object type, in which case we just ignore it.
2597 // Otherwise build the appropriate casts.
2598 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002599 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002600 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002601 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002602 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002603
Douglas Gregor5fccd362010-03-03 23:55:11 +00002604 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002605 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002606 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002607 VK, &BasePath).get();
John McCall6bb80172010-03-30 21:47:33 +00002608
2609 FromType = QType;
2610 FromRecordType = QRecordType;
2611
2612 // If the qualifier type was the same as the destination type,
2613 // we're done.
2614 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002615 return From;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002616 }
2617 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002618
John McCall6bb80172010-03-30 21:47:33 +00002619 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002620
John McCall6bb80172010-03-30 21:47:33 +00002621 // If we actually found the member through a using declaration, cast
2622 // down to the using declaration's type.
2623 //
2624 // Pointer equality is fine here because only one declaration of a
2625 // class ever has member declarations.
2626 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2627 assert(isa<UsingShadowDecl>(FoundDecl));
2628 QualType URecordType = Context.getTypeDeclType(
2629 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2630
2631 // We only need to do this if the naming-class to declaring-class
2632 // conversion is non-trivial.
2633 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2634 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002635 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002636 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002637 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002638 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002639
John McCall6bb80172010-03-30 21:47:33 +00002640 QualType UType = URecordType;
2641 if (PointerConversions)
2642 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002643 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002644 VK, &BasePath).get();
John McCall6bb80172010-03-30 21:47:33 +00002645 FromType = UType;
2646 FromRecordType = URecordType;
2647 }
2648
2649 // We don't do access control for the conversion from the
2650 // declaring class to the true declaring class.
2651 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002652 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002653
John McCallf871d0c2010-08-07 06:22:56 +00002654 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002655 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2656 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002657 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002658 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002659
John Wiegley429bb272011-04-08 18:41:53 +00002660 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2661 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002662}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002663
John McCallf7a1a742009-11-24 19:00:30 +00002664bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002665 const LookupResult &R,
2666 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002667 // Only when used directly as the postfix-expression of a call.
2668 if (!HasTrailingLParen)
2669 return false;
2670
2671 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002672 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002673 return false;
2674
2675 // Only in C++ or ObjC++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002676 if (!getLangOpts().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002677 return false;
2678
2679 // Turn off ADL when we find certain kinds of declarations during
2680 // normal lookup:
2681 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2682 NamedDecl *D = *I;
2683
2684 // C++0x [basic.lookup.argdep]p3:
2685 // -- a declaration of a class member
2686 // Since using decls preserve this property, we check this on the
2687 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002688 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002689 return false;
2690
2691 // C++0x [basic.lookup.argdep]p3:
2692 // -- a block-scope function declaration that is not a
2693 // using-declaration
2694 // NOTE: we also trigger this for function templates (in fact, we
2695 // don't check the decl type at all, since all other decl types
2696 // turn off ADL anyway).
2697 if (isa<UsingShadowDecl>(D))
2698 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Richard Smitha41c97a2013-09-20 01:15:31 +00002699 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
John McCallba135432009-11-21 08:51:07 +00002700 return false;
2701
2702 // C++0x [basic.lookup.argdep]p3:
2703 // -- a declaration that is neither a function or a function
2704 // template
2705 // And also for builtin functions.
2706 if (isa<FunctionDecl>(D)) {
2707 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2708
2709 // But also builtin functions.
2710 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2711 return false;
2712 } else if (!isa<FunctionTemplateDecl>(D))
2713 return false;
2714 }
2715
2716 return true;
2717}
2718
2719
John McCallba135432009-11-21 08:51:07 +00002720/// Diagnoses obvious problems with the use of the given declaration
2721/// as an expression. This is only actually called for lookups that
2722/// were not overloaded, and it doesn't promise that the declaration
2723/// will in fact be used.
2724static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002725 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002726 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2727 return true;
2728 }
2729
2730 if (isa<ObjCInterfaceDecl>(D)) {
2731 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2732 return true;
2733 }
2734
2735 if (isa<NamespaceDecl>(D)) {
2736 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2737 return true;
2738 }
2739
2740 return false;
2741}
2742
Stephen Hines176edba2014-12-01 14:53:08 -08002743ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2744 LookupResult &R, bool NeedsADL,
2745 bool AcceptInvalidDecl) {
John McCallfead20c2009-12-08 22:45:53 +00002746 // If this is a single, fully-resolved result and we don't need ADL,
2747 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002748 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Daniel Jasper8ff563c2013-03-22 10:01:35 +00002749 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
Stephen Hines176edba2014-12-01 14:53:08 -08002750 R.getRepresentativeDecl(), nullptr,
2751 AcceptInvalidDecl);
John McCallba135432009-11-21 08:51:07 +00002752
2753 // We only need to check the declaration if there's exactly one
2754 // result, because in the overloaded case the results can only be
2755 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002756 if (R.isSingleResult() &&
2757 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002758 return ExprError();
2759
John McCallc373d482010-01-27 01:50:18 +00002760 // Otherwise, just build an unresolved lookup expression. Suppress
2761 // any lookup-related diagnostics; we'll hash these out later, when
2762 // we've picked a target.
2763 R.suppressDiagnostics();
2764
John McCallba135432009-11-21 08:51:07 +00002765 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002766 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002767 SS.getWithLocInContext(Context),
2768 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002769 NeedsADL, R.isOverloadedResult(),
2770 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002771
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002772 return ULE;
John McCallba135432009-11-21 08:51:07 +00002773}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002774
John McCallba135432009-11-21 08:51:07 +00002775/// \brief Complete semantic analysis for a reference to the given declaration.
Larisse Voufoef4579c2013-08-06 01:03:05 +00002776ExprResult Sema::BuildDeclarationNameExpr(
2777 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
Stephen Hines176edba2014-12-01 14:53:08 -08002778 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2779 bool AcceptInvalidDecl) {
John McCallba135432009-11-21 08:51:07 +00002780 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002781 assert(!isa<FunctionTemplateDecl>(D) &&
2782 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002783
Abramo Bagnara25777432010-08-11 22:01:17 +00002784 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002785 if (CheckDeclInExpr(*this, Loc, D))
2786 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002787
Douglas Gregor9af2f522009-12-01 16:58:18 +00002788 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2789 // Specifically diagnose references to class templates that are missing
2790 // a template argument list.
Larisse Voufoef4579c2013-08-06 01:03:05 +00002791 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2792 << Template << SS.getRange();
Douglas Gregor9af2f522009-12-01 16:58:18 +00002793 Diag(Template->getLocation(), diag::note_template_decl_here);
2794 return ExprError();
2795 }
2796
2797 // Make sure that we're referring to a value.
2798 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2799 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002800 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002801 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002802 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002803 return ExprError();
2804 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002805
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002806 // Check whether this declaration can be used. Note that we suppress
2807 // this check when we're going to perform argument-dependent lookup
2808 // on this function name, because this might not be the function
2809 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002810 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002811 return ExprError();
2812
Steve Naroffdd972f22008-09-05 22:11:13 +00002813 // Only create DeclRefExpr's for valid Decl's.
Stephen Hines176edba2014-12-01 14:53:08 -08002814 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002815 return ExprError();
2816
John McCall5808ce42011-02-03 08:15:49 +00002817 // Handle members of anonymous structs and unions. If we got here,
2818 // and the reference is to a class member indirect field, then this
2819 // must be the subject of a pointer-to-member expression.
2820 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2821 if (!indirectField->isCXXClassMember())
2822 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2823 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002824
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002825 {
John McCall76a40212011-02-09 01:13:10 +00002826 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002827 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002828
2829 switch (D->getKind()) {
2830 // Ignore all the non-ValueDecl kinds.
2831#define ABSTRACT_DECL(kind)
2832#define VALUE(type, base)
2833#define DECL(type, base) \
2834 case Decl::type:
2835#include "clang/AST/DeclNodes.inc"
2836 llvm_unreachable("invalid value decl kind");
John McCall76a40212011-02-09 01:13:10 +00002837
2838 // These shouldn't make it here.
2839 case Decl::ObjCAtDefsField:
2840 case Decl::ObjCIvar:
2841 llvm_unreachable("forming non-member reference to ivar?");
John McCall76a40212011-02-09 01:13:10 +00002842
2843 // Enum constants are always r-values and never references.
2844 // Unresolved using declarations are dependent.
2845 case Decl::EnumConstant:
2846 case Decl::UnresolvedUsingValue:
2847 valueKind = VK_RValue;
2848 break;
2849
2850 // Fields and indirect fields that got here must be for
2851 // pointer-to-member expressions; we just call them l-values for
2852 // internal consistency, because this subexpression doesn't really
2853 // exist in the high-level semantics.
2854 case Decl::Field:
2855 case Decl::IndirectField:
David Blaikie4e4d0842012-03-11 07:00:24 +00002856 assert(getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002857 "building reference to field in C?");
2858
2859 // These can't have reference type in well-formed programs, but
2860 // for internal consistency we do this anyway.
2861 type = type.getNonReferenceType();
2862 valueKind = VK_LValue;
2863 break;
2864
2865 // Non-type template parameters are either l-values or r-values
2866 // depending on the type.
2867 case Decl::NonTypeTemplateParm: {
2868 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2869 type = reftype->getPointeeType();
2870 valueKind = VK_LValue; // even if the parameter is an r-value reference
2871 break;
2872 }
2873
2874 // For non-references, we need to strip qualifiers just in case
2875 // the template parameter was declared as 'const int' or whatever.
2876 valueKind = VK_RValue;
2877 type = type.getUnqualifiedType();
2878 break;
2879 }
2880
2881 case Decl::Var:
Larisse Voufoef4579c2013-08-06 01:03:05 +00002882 case Decl::VarTemplateSpecialization:
2883 case Decl::VarTemplatePartialSpecialization:
John McCall76a40212011-02-09 01:13:10 +00002884 // In C, "extern void blah;" is valid and is an r-value.
David Blaikie4e4d0842012-03-11 07:00:24 +00002885 if (!getLangOpts().CPlusPlus &&
John McCall76a40212011-02-09 01:13:10 +00002886 !type.hasQualifiers() &&
2887 type->isVoidType()) {
2888 valueKind = VK_RValue;
2889 break;
2890 }
2891 // fallthrough
2892
2893 case Decl::ImplicitParam:
Douglas Gregor68932842012-02-18 05:51:20 +00002894 case Decl::ParmVar: {
John McCall76a40212011-02-09 01:13:10 +00002895 // These are always l-values.
2896 valueKind = VK_LValue;
2897 type = type.getNonReferenceType();
Eli Friedman3c0e80e2012-02-03 02:04:35 +00002898
Douglas Gregor68932842012-02-18 05:51:20 +00002899 // FIXME: Does the addition of const really only apply in
2900 // potentially-evaluated contexts? Since the variable isn't actually
2901 // captured in an unevaluated context, it seems that the answer is no.
David Blaikie71f55f72012-08-06 22:47:24 +00002902 if (!isUnevaluatedContext()) {
Douglas Gregor68932842012-02-18 05:51:20 +00002903 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2904 if (!CapturedType.isNull())
2905 type = CapturedType;
2906 }
2907
John McCall76a40212011-02-09 01:13:10 +00002908 break;
Douglas Gregor68932842012-02-18 05:51:20 +00002909 }
2910
John McCall76a40212011-02-09 01:13:10 +00002911 case Decl::Function: {
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002912 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2913 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2914 type = Context.BuiltinFnTy;
2915 valueKind = VK_RValue;
2916 break;
2917 }
2918 }
2919
John McCall755d8492011-04-12 00:42:48 +00002920 const FunctionType *fty = type->castAs<FunctionType>();
2921
2922 // If we're referring to a function with an __unknown_anytype
2923 // result type, make the entire expression __unknown_anytype.
Stephen Hines651f13c2014-04-23 16:59:28 -07002924 if (fty->getReturnType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00002925 type = Context.UnknownAnyTy;
2926 valueKind = VK_RValue;
2927 break;
2928 }
2929
John McCall76a40212011-02-09 01:13:10 +00002930 // Functions are l-values in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00002931 if (getLangOpts().CPlusPlus) {
John McCall76a40212011-02-09 01:13:10 +00002932 valueKind = VK_LValue;
2933 break;
2934 }
2935
2936 // C99 DR 316 says that, if a function type comes from a
2937 // function definition (without a prototype), that type is only
2938 // used for checking compatibility. Therefore, when referencing
2939 // the function, we pretend that we don't have the full function
2940 // type.
John McCall755d8492011-04-12 00:42:48 +00002941 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2942 isa<FunctionProtoType>(fty))
Stephen Hines651f13c2014-04-23 16:59:28 -07002943 type = Context.getFunctionNoProtoType(fty->getReturnType(),
John McCall755d8492011-04-12 00:42:48 +00002944 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002945
2946 // Functions are r-values in C.
2947 valueKind = VK_RValue;
2948 break;
2949 }
2950
John McCall76da55d2013-04-16 07:28:30 +00002951 case Decl::MSProperty:
2952 valueKind = VK_LValue;
2953 break;
2954
John McCall76a40212011-02-09 01:13:10 +00002955 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002956 // If we're referring to a method with an __unknown_anytype
2957 // result type, make the entire expression __unknown_anytype.
2958 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002959 if (const FunctionProtoType *proto
2960 = dyn_cast<FunctionProtoType>(VD->getType()))
Stephen Hines651f13c2014-04-23 16:59:28 -07002961 if (proto->getReturnType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00002962 type = Context.UnknownAnyTy;
2963 valueKind = VK_RValue;
2964 break;
2965 }
2966
John McCall76a40212011-02-09 01:13:10 +00002967 // C++ methods are l-values if static, r-values if non-static.
2968 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2969 valueKind = VK_LValue;
2970 break;
2971 }
2972 // fallthrough
2973
2974 case Decl::CXXConversion:
2975 case Decl::CXXDestructor:
2976 case Decl::CXXConstructor:
2977 valueKind = VK_RValue;
2978 break;
2979 }
2980
Larisse Voufoef4579c2013-08-06 01:03:05 +00002981 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2982 TemplateArgs);
John McCall76a40212011-02-09 01:13:10 +00002983 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002984}
2985
Stephen Hines176edba2014-12-01 14:53:08 -08002986static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2987 SmallString<32> &Target) {
2988 Target.resize(CharByteWidth * (Source.size() + 1));
2989 char *ResultPtr = &Target[0];
2990 const UTF8 *ErrorPtr;
2991 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2992 (void)success;
2993 assert(success);
2994 Target.resize(ResultPtr - &Target[0]);
2995}
2996
Wei Pan33129332013-09-16 13:57:27 +00002997ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2998 PredefinedExpr::IdentType IT) {
2999 // Pick the current block, lambda, captured statement or function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003000 Decl *currentDecl = nullptr;
Benjamin Kramer28bdbf02013-08-21 11:45:27 +00003001 if (const BlockScopeInfo *BSI = getCurBlock())
3002 currentDecl = BSI->TheDecl;
3003 else if (const LambdaScopeInfo *LSI = getCurLambda())
3004 currentDecl = LSI->CallOperator;
Wei Pan15b26742013-08-26 14:27:34 +00003005 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3006 currentDecl = CSI->TheCapturedDecl;
Benjamin Kramer28bdbf02013-08-21 11:45:27 +00003007 else
3008 currentDecl = getCurFunctionOrMethodDecl();
Benjamin Kramer42427402012-12-06 15:42:21 +00003009
Anders Carlsson3a082d82009-09-08 18:24:21 +00003010 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00003011 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00003012 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00003013 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003014
Anders Carlsson773f3972009-09-11 01:22:35 +00003015 QualType ResTy;
Stephen Hines176edba2014-12-01 14:53:08 -08003016 StringLiteral *SL = nullptr;
Wei Pan33129332013-09-16 13:57:27 +00003017 if (cast<DeclContext>(currentDecl)->isDependentContext())
Anders Carlsson773f3972009-09-11 01:22:35 +00003018 ResTy = Context.DependentTy;
Wei Pan33129332013-09-16 13:57:27 +00003019 else {
3020 // Pre-defined identifiers are of type char[x], where x is the length of
3021 // the string.
Stephen Hines176edba2014-12-01 14:53:08 -08003022 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3023 unsigned Length = Str.length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003024
Anders Carlsson773f3972009-09-11 01:22:35 +00003025 llvm::APInt LengthI(32, Length + 1);
Stephen Hines176edba2014-12-01 14:53:08 -08003026 if (IT == PredefinedExpr::LFunction) {
Hans Wennborg15f92ba2013-05-10 10:08:40 +00003027 ResTy = Context.WideCharTy.withConst();
Stephen Hines176edba2014-12-01 14:53:08 -08003028 SmallString<32> RawChars;
3029 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3030 Str, RawChars);
3031 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3032 /*IndexTypeQuals*/ 0);
3033 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3034 /*Pascal*/ false, ResTy, Loc);
3035 } else {
Nico Weber28ad0632012-06-23 02:07:59 +00003036 ResTy = Context.CharTy.withConst();
Stephen Hines176edba2014-12-01 14:53:08 -08003037 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3038 /*IndexTypeQuals*/ 0);
3039 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3040 /*Pascal*/ false, ResTy, Loc);
3041 }
Anders Carlsson773f3972009-09-11 01:22:35 +00003042 }
Wei Pan33129332013-09-16 13:57:27 +00003043
Stephen Hines176edba2014-12-01 14:53:08 -08003044 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
Reid Spencer5f016e22007-07-11 17:01:13 +00003045}
3046
Wei Pan33129332013-09-16 13:57:27 +00003047ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3048 PredefinedExpr::IdentType IT;
3049
3050 switch (Kind) {
3051 default: llvm_unreachable("Unknown simple primary expr!");
3052 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3053 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
David Majnemerbafa74f2013-11-06 23:31:56 +00003054 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003055 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
Wei Pan33129332013-09-16 13:57:27 +00003056 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3057 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3058 }
3059
3060 return BuildPredefinedExpr(Loc, IT);
3061}
3062
Richard Smith36f5cfe2012-03-09 08:00:36 +00003063ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003064 SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00003065 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003066 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00003067 if (Invalid)
3068 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003069
Benjamin Kramerddeea562010-02-27 13:44:12 +00003070 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003071 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00003072 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00003073 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00003074
Chris Lattnere8337df2009-12-30 21:19:39 +00003075 QualType Ty;
Seth Cantrell79f0a822012-01-18 12:27:06 +00003076 if (Literal.isWide())
Hans Wennborg15f92ba2013-05-10 10:08:40 +00003077 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00003078 else if (Literal.isUTF16())
Seth Cantrell79f0a822012-01-18 12:27:06 +00003079 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregor5cee1192011-07-27 05:40:30 +00003080 else if (Literal.isUTF32())
Seth Cantrell79f0a822012-01-18 12:27:06 +00003081 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikie4e4d0842012-03-11 07:00:24 +00003082 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell79f0a822012-01-18 12:27:06 +00003083 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00003084 else
3085 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00003086
Douglas Gregor5cee1192011-07-27 05:40:30 +00003087 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3088 if (Literal.isWide())
3089 Kind = CharacterLiteral::Wide;
3090 else if (Literal.isUTF16())
3091 Kind = CharacterLiteral::UTF16;
3092 else if (Literal.isUTF32())
3093 Kind = CharacterLiteral::UTF32;
3094
Richard Smithdd66be72012-03-08 01:34:56 +00003095 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3096 Tok.getLocation());
3097
3098 if (Literal.getUDSuffix().empty())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003099 return Lit;
Richard Smithdd66be72012-03-08 01:34:56 +00003100
3101 // We're building a user-defined literal.
3102 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3103 SourceLocation UDSuffixLoc =
3104 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3105
Richard Smith36f5cfe2012-03-09 08:00:36 +00003106 // Make sure we're allowed user-defined literals here.
3107 if (!UDLScope)
3108 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3109
Richard Smithdd66be72012-03-08 01:34:56 +00003110 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3111 // operator "" X (ch)
Richard Smith36f5cfe2012-03-09 08:00:36 +00003112 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003113 Lit, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003114}
3115
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003116ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3117 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003118 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3119 Context.IntTy, Loc);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003120}
3121
Richard Smithb453ad32012-03-08 08:45:32 +00003122static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3123 QualType Ty, SourceLocation Loc) {
3124 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3125
3126 using llvm::APFloat;
3127 APFloat Val(Format);
3128
3129 APFloat::opStatus result = Literal.GetFloatValue(Val);
3130
3131 // Overflow is always an error, but underflow is only an error if
3132 // we underflowed to zero (APFloat reports denormals as underflow).
3133 if ((result & APFloat::opOverflow) ||
3134 ((result & APFloat::opUnderflow) && Val.isZero())) {
3135 unsigned diagnostic;
3136 SmallString<20> buffer;
3137 if (result & APFloat::opOverflow) {
3138 diagnostic = diag::warn_float_overflow;
3139 APFloat::getLargest(Format).toString(buffer);
3140 } else {
3141 diagnostic = diag::warn_float_underflow;
3142 APFloat::getSmallest(Format).toString(buffer);
3143 }
3144
3145 S.Diag(Loc, diagnostic)
3146 << Ty
3147 << StringRef(buffer.data(), buffer.size());
3148 }
3149
3150 bool isExact = (result == APFloat::opOK);
3151 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3152}
3153
Stephen Hines176edba2014-12-01 14:53:08 -08003154bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3155 assert(E && "Invalid expression");
3156
3157 if (E->isValueDependent())
3158 return false;
3159
3160 QualType QT = E->getType();
3161 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3162 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3163 return true;
3164 }
3165
3166 llvm::APSInt ValueAPS;
3167 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3168
3169 if (R.isInvalid())
3170 return true;
3171
3172 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3173 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3174 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3175 << ValueAPS.toString(10) << ValueIsPositive;
3176 return true;
3177 }
3178
3179 return false;
3180}
3181
Richard Smith36f5cfe2012-03-09 08:00:36 +00003182ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00003183 // Fast path for a single digit (which is quite common). A single digit
Richard Smith36f5cfe2012-03-09 08:00:36 +00003184 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00003186 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003187 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 }
Ted Kremenek28396602009-01-13 23:19:12 +00003189
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00003190 SmallString<128> SpellingBuffer;
3191 // NumericLiteralParser wants to overread by one character. Add padding to
3192 // the buffer in case the token is copied to the buffer. If getSpelling()
3193 // returns a StringRef to the memory buffer, it should have a null char at
3194 // the EOF, so it is also safe.
3195 SpellingBuffer.resize(Tok.getLength() + 1);
Sebastian Redlcd965b92009-01-18 18:53:16 +00003196
Reid Spencer5f016e22007-07-11 17:01:13 +00003197 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00003198 bool Invalid = false;
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00003199 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00003200 if (Invalid)
3201 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003202
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00003203 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00003204 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00003205 return ExprError();
3206
Richard Smithb453ad32012-03-08 08:45:32 +00003207 if (Literal.hasUDSuffix()) {
3208 // We're building a user-defined literal.
3209 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3210 SourceLocation UDSuffixLoc =
3211 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3212
Richard Smith36f5cfe2012-03-09 08:00:36 +00003213 // Make sure we're allowed user-defined literals here.
3214 if (!UDLScope)
3215 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smithb453ad32012-03-08 08:45:32 +00003216
Richard Smith36f5cfe2012-03-09 08:00:36 +00003217 QualType CookedTy;
Richard Smithb453ad32012-03-08 08:45:32 +00003218 if (Literal.isFloatingLiteral()) {
3219 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3220 // long double, the literal is treated as a call of the form
3221 // operator "" X (f L)
Richard Smith36f5cfe2012-03-09 08:00:36 +00003222 CookedTy = Context.LongDoubleTy;
Richard Smithb453ad32012-03-08 08:45:32 +00003223 } else {
3224 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3225 // unsigned long long, the literal is treated as a call of the form
3226 // operator "" X (n ULL)
Richard Smith36f5cfe2012-03-09 08:00:36 +00003227 CookedTy = Context.UnsignedLongLongTy;
Richard Smithb453ad32012-03-08 08:45:32 +00003228 }
3229
Richard Smith36f5cfe2012-03-09 08:00:36 +00003230 DeclarationName OpName =
3231 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3232 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3233 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3234
Richard Smithb328e292013-10-07 19:57:58 +00003235 SourceLocation TokLoc = Tok.getLocation();
3236
Richard Smith36f5cfe2012-03-09 08:00:36 +00003237 // Perform literal operator lookup to determine if we're building a raw
3238 // literal or a cooked one.
3239 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003240 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
Richard Smithb328e292013-10-07 19:57:58 +00003241 /*AllowRaw*/true, /*AllowTemplate*/true,
3242 /*AllowStringTemplate*/false)) {
Richard Smith36f5cfe2012-03-09 08:00:36 +00003243 case LOLR_Error:
3244 return ExprError();
3245
3246 case LOLR_Cooked: {
3247 Expr *Lit;
3248 if (Literal.isFloatingLiteral()) {
3249 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3250 } else {
3251 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3252 if (Literal.GetIntegerValue(ResultVal))
Stephen Hines176edba2014-12-01 14:53:08 -08003253 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3254 << /* Unsigned */ 1;
Richard Smith36f5cfe2012-03-09 08:00:36 +00003255 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3256 Tok.getLocation());
3257 }
Richard Smithb328e292013-10-07 19:57:58 +00003258 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smith36f5cfe2012-03-09 08:00:36 +00003259 }
3260
3261 case LOLR_Raw: {
3262 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3263 // literal is treated as a call of the form
3264 // operator "" X ("n")
Richard Smith36f5cfe2012-03-09 08:00:36 +00003265 unsigned Length = Literal.getUDSuffixOffset();
3266 QualType StrTy = Context.getConstantArrayType(
Richard Smith4ea6a642013-01-23 23:38:20 +00003267 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
Richard Smith36f5cfe2012-03-09 08:00:36 +00003268 ArrayType::Normal, 0);
3269 Expr *Lit = StringLiteral::Create(
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00003270 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
Richard Smith36f5cfe2012-03-09 08:00:36 +00003271 /*Pascal*/false, StrTy, &TokLoc, 1);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003272 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
Richard Smith36f5cfe2012-03-09 08:00:36 +00003273 }
3274
Richard Smithb328e292013-10-07 19:57:58 +00003275 case LOLR_Template: {
Richard Smith36f5cfe2012-03-09 08:00:36 +00003276 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3277 // template), L is treated as a call fo the form
3278 // operator "" X <'c1', 'c2', ... 'ck'>()
3279 // where n is the source character sequence c1 c2 ... ck.
3280 TemplateArgumentListInfo ExplicitArgs;
3281 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3282 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3283 llvm::APSInt Value(CharBits, CharIsUnsigned);
3284 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +00003285 Value = TokSpelling[I];
Benjamin Kramer85524372012-06-07 15:09:51 +00003286 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smith36f5cfe2012-03-09 08:00:36 +00003287 TemplateArgumentLocInfo ArgInfo;
3288 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3289 }
Richard Smithb328e292013-10-07 19:57:58 +00003290 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
Dmitri Gribenko55431692013-05-05 00:41:58 +00003291 &ExplicitArgs);
Richard Smith36f5cfe2012-03-09 08:00:36 +00003292 }
Richard Smithb328e292013-10-07 19:57:58 +00003293 case LOLR_StringTemplate:
3294 llvm_unreachable("unexpected literal operator lookup result");
3295 }
Richard Smithb453ad32012-03-08 08:45:32 +00003296 }
3297
Chris Lattner5d661452007-08-26 03:42:43 +00003298 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00003299
Chris Lattner5d661452007-08-26 03:42:43 +00003300 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00003301 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00003302 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00003303 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00003304 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00003305 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00003306 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00003307 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00003308
Richard Smithb453ad32012-03-08 08:45:32 +00003309 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00003310
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00003311 if (Ty == Context.DoubleTy) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003312 if (getLangOpts().SinglePrecisionConstants) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003313 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003314 } else if (getLangOpts().OpenCL &&
3315 !((getLangOpts().OpenCLVersion >= 120) ||
3316 getOpenCLOptions().cl_khr_fp64)) {
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00003317 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003318 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00003319 }
3320 }
Chris Lattner5d661452007-08-26 03:42:43 +00003321 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00003322 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00003323 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003324 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00003325
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00003326 // 'long long' is a C99 or C++11 feature.
3327 if (!getLangOpts().C99 && Literal.isLongLong) {
3328 if (getLangOpts().CPlusPlus)
3329 Diag(Tok.getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00003330 getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +00003331 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3332 else
3333 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3334 }
Neil Boothb9449512007-08-29 22:00:19 +00003335
Reid Spencer5f016e22007-07-11 17:01:13 +00003336 // Get the value in the widest-possible width.
Stephen Canonb9e05f12012-05-03 22:49:43 +00003337 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3338 // The microsoft literal suffix extensions support 128-bit literals, which
3339 // may be wider than [u]intmax_t.
Richard Smith84268902012-11-29 05:41:51 +00003340 // FIXME: Actually, they don't. We seem to have accidentally invented the
3341 // i128 suffix.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003342 if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003343 Context.getTargetInfo().hasInt128Type())
Stephen Canonb9e05f12012-05-03 22:49:43 +00003344 MaxWidth = 128;
3345 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00003346
Reid Spencer5f016e22007-07-11 17:01:13 +00003347 if (Literal.GetIntegerValue(ResultVal)) {
Eli Friedmanb3da6132013-07-23 00:25:18 +00003348 // If this value didn't fit into uintmax_t, error and force to ull.
Stephen Hines176edba2014-12-01 14:53:08 -08003349 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3350 << /* Unsigned */ 1;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003351 Ty = Context.UnsignedLongLongTy;
3352 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00003353 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00003354 } else {
3355 // If this value fits into a ULL, try to figure out what else it fits into
3356 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00003357
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3359 // be an unsigned int.
3360 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3361
3362 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003363 unsigned Width = 0;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003364
3365 // Microsoft specific integer suffixes are explicitly sized.
3366 if (Literal.MicrosoftInteger) {
3367 if (Literal.MicrosoftInteger > MaxWidth) {
3368 // If this target doesn't support __int128, error and force to ull.
3369 Diag(Tok.getLocation(), diag::err_int128_unsupported);
3370 Width = MaxWidth;
3371 Ty = Context.getIntMaxType();
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003372 } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3373 Width = 8;
3374 Ty = Context.CharTy;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003375 } else {
3376 Width = Literal.MicrosoftInteger;
3377 Ty = Context.getIntTypeForBitwidth(Width,
3378 /*Signed=*/!Literal.isUnsigned);
3379 }
3380 }
3381
3382 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
Chris Lattner97c51562007-08-23 21:58:08 +00003383 // Are int/unsigned possibilities?
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003384 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003385
Reid Spencer5f016e22007-07-11 17:01:13 +00003386 // Does it fit in a unsigned int?
3387 if (ResultVal.isIntN(IntSize)) {
3388 // Does it fit in a signed int?
3389 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003390 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003391 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003392 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003393 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003395 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003396
Reid Spencer5f016e22007-07-11 17:01:13 +00003397 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00003398 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003399 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003400
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 // Does it fit in a unsigned long?
3402 if (ResultVal.isIntN(LongSize)) {
3403 // Does it fit in a signed long?
3404 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003405 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003406 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003407 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003408 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003409 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003410 }
3411
Stephen Canonb9e05f12012-05-03 22:49:43 +00003412 // Check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003413 if (Ty.isNull()) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003414 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003415
Reid Spencer5f016e22007-07-11 17:01:13 +00003416 // Does it fit in a unsigned long long?
3417 if (ResultVal.isIntN(LongLongSize)) {
3418 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00003419 // To be compatible with MSVC, hex integer literals ending with the
3420 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00003421 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003422 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00003423 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003424 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003425 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003426 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003427 }
3428 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003429
Reid Spencer5f016e22007-07-11 17:01:13 +00003430 // If we still couldn't decide a type, we probably have something that
3431 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003432 if (Ty.isNull()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003433 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003434 Ty = Context.UnsignedLongLongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003435 Width = Context.getTargetInfo().getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00003436 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003437
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003438 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003439 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00003440 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003441 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003442 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003443
Chris Lattner5d661452007-08-26 03:42:43 +00003444 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3445 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00003446 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003447 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00003448
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003449 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +00003450}
3451
Richard Trieuccd891a2011-09-09 01:45:06 +00003452ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003453 assert(E && "ActOnParenExpr() missing expr");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003454 return new (Context) ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +00003455}
3456
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003457static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3458 SourceLocation Loc,
3459 SourceRange ArgRange) {
3460 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3461 // scalar or vector data type argument..."
3462 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3463 // type (C99 6.2.5p18) or void.
3464 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3465 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3466 << T << ArgRange;
3467 return true;
3468 }
3469
3470 assert((T->isVoidType() || !T->isIncompleteType()) &&
3471 "Scalar types should always be complete");
3472 return false;
3473}
3474
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003475static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3476 SourceLocation Loc,
3477 SourceRange ArgRange,
3478 UnaryExprOrTypeTrait TraitKind) {
Eli Friedmanc99b90e2013-08-13 22:26:42 +00003479 // Invalid types must be hard errors for SFINAE in C++.
3480 if (S.LangOpts.CPlusPlus)
3481 return true;
3482
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003483 // C99 6.5.3.4p1:
Richard Smith7132be12013-03-18 23:37:25 +00003484 if (T->isFunctionType() &&
3485 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3486 // sizeof(function)/alignof(function) is allowed as an extension.
3487 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3488 << TraitKind << ArgRange;
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003489 return false;
3490 }
3491
Stephen Hines651f13c2014-04-23 16:59:28 -07003492 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3493 // this is an error (OpenCL v1.1 s6.3.k)
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003494 if (T->isVoidType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003495 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3496 : diag::ext_sizeof_alignof_void_type;
3497 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003498 return false;
3499 }
3500
3501 return true;
3502}
3503
3504static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3505 SourceLocation Loc,
3506 SourceRange ArgRange,
3507 UnaryExprOrTypeTrait TraitKind) {
John McCall1503f0d2012-07-31 05:14:30 +00003508 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3509 // runtime doesn't allow it.
3510 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003511 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3512 << T << (TraitKind == UETT_SizeOf)
3513 << ArgRange;
3514 return true;
3515 }
3516
3517 return false;
3518}
3519
Benjamin Kramer52b2e702013-03-29 21:43:21 +00003520/// \brief Check whether E is a pointer from a decayed array type (the decayed
3521/// pointer type is equal to T) and emit a warning if it is.
3522static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3523 Expr *E) {
3524 // Don't warn if the operation changed the type.
3525 if (T != E->getType())
3526 return;
3527
3528 // Now look for array decays.
3529 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3530 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3531 return;
3532
3533 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3534 << ICE->getType()
3535 << ICE->getSubExpr()->getType();
3536}
3537
Stephen Hines651f13c2014-04-23 16:59:28 -07003538/// \brief Check the constraints on expression operands to unary type expression
Chandler Carruth9d342d02011-05-26 08:53:10 +00003539/// and type traits.
3540///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003541/// Completes any types necessary and validates the constraints on the operand
3542/// expression. The logic mostly mirrors the type-based overload, but may modify
3543/// the expression as it completes the type for that expression through template
3544/// instantiation, etc.
Richard Trieuccd891a2011-09-09 01:45:06 +00003545bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003546 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003547 QualType ExprTy = E->getType();
John McCall10f6f062013-05-06 07:40:34 +00003548 assert(!ExprTy->isReferenceType());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003549
3550 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003551 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3552 E->getSourceRange());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003553
3554 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003555 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3556 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003557 return false;
3558
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003559 // 'alignof' applied to an expression only requires the base element type of
3560 // the expression to be complete. 'sizeof' requires the expression's type to
3561 // be complete (and will attempt to complete it if it's an array of unknown
3562 // bound).
3563 if (ExprKind == UETT_AlignOf) {
3564 if (RequireCompleteType(E->getExprLoc(),
3565 Context.getBaseElementType(E->getType()),
3566 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3567 E->getSourceRange()))
3568 return true;
3569 } else {
3570 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3571 ExprKind, E->getSourceRange()))
3572 return true;
3573 }
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003574
John McCall10f6f062013-05-06 07:40:34 +00003575 // Completing the expression's type may have changed it.
Richard Trieuccd891a2011-09-09 01:45:06 +00003576 ExprTy = E->getType();
John McCall10f6f062013-05-06 07:40:34 +00003577 assert(!ExprTy->isReferenceType());
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003578
Eli Friedmanc99b90e2013-08-13 22:26:42 +00003579 if (ExprTy->isFunctionType()) {
3580 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3581 << ExprKind << E->getSourceRange();
3582 return true;
3583 }
3584
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003585 // The operand for sizeof and alignof is in an unevaluated expression context,
3586 // so side effects could result in unintended consequences.
3587 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3588 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3589 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3590
Richard Trieuccd891a2011-09-09 01:45:06 +00003591 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3592 E->getSourceRange(), ExprKind))
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003593 return true;
3594
Nico Webercf739922011-06-15 02:47:03 +00003595 if (ExprKind == UETT_SizeOf) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003596 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Webercf739922011-06-15 02:47:03 +00003597 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3598 QualType OType = PVD->getOriginalType();
3599 QualType Type = PVD->getType();
3600 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003601 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Webercf739922011-06-15 02:47:03 +00003602 << Type << OType;
3603 Diag(PVD->getLocation(), diag::note_declared_at);
3604 }
3605 }
3606 }
Benjamin Kramer52b2e702013-03-29 21:43:21 +00003607
3608 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3609 // decays into a pointer and returns an unintended result. This is most
3610 // likely a typo for "sizeof(array) op x".
3611 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3612 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3613 BO->getLHS());
3614 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3615 BO->getRHS());
3616 }
Nico Webercf739922011-06-15 02:47:03 +00003617 }
3618
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003619 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003620}
3621
3622/// \brief Check the constraints on operands to unary expression and type
3623/// traits.
3624///
3625/// This will complete any types necessary, and validate the various constraints
3626/// on those operands.
3627///
Reid Spencer5f016e22007-07-11 17:01:13 +00003628/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003629/// C99 6.3.2.1p[2-4] all state:
3630/// Except when it is the operand of the sizeof operator ...
3631///
3632/// C++ [expr.sizeof]p4
3633/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3634/// standard conversions are not applied to the operand of sizeof.
3635///
3636/// This policy is followed for all of the unary trait expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +00003637bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003638 SourceLocation OpLoc,
3639 SourceRange ExprRange,
3640 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuccd891a2011-09-09 01:45:06 +00003641 if (ExprType->isDependentType())
Sebastian Redl28507842009-02-26 14:39:58 +00003642 return false;
3643
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003644 // C++ [expr.sizeof]p2:
3645 // When applied to a reference or a reference type, the result
3646 // is the size of the referenced type.
3647 // C++11 [expr.alignof]p3:
3648 // When alignof is applied to a reference type, the result
3649 // shall be the alignment of the referenced type.
Richard Trieuccd891a2011-09-09 01:45:06 +00003650 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3651 ExprType = Ref->getPointeeType();
Sebastian Redl5d484e82009-11-23 17:18:46 +00003652
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003653 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3654 // When alignof or _Alignof is applied to an array type, the result
3655 // is the alignment of the element type.
3656 if (ExprKind == UETT_AlignOf)
3657 ExprType = Context.getBaseElementType(ExprType);
3658
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003659 if (ExprKind == UETT_VecStep)
Richard Trieuccd891a2011-09-09 01:45:06 +00003660 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003661
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003662 // Whitelist some types as extensions
Richard Trieuccd891a2011-09-09 01:45:06 +00003663 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003664 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003665 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Richard Trieuccd891a2011-09-09 01:45:06 +00003667 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregord10099e2012-05-04 16:32:21 +00003668 diag::err_sizeof_alignof_incomplete_type,
3669 ExprKind, ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003670 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Eli Friedmanc99b90e2013-08-13 22:26:42 +00003672 if (ExprType->isFunctionType()) {
3673 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3674 << ExprKind << ExprRange;
3675 return true;
3676 }
3677
Richard Trieuccd891a2011-09-09 01:45:06 +00003678 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003679 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003680 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Chris Lattner1efaa952009-04-24 00:30:45 +00003682 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003683}
3684
Chandler Carruth9d342d02011-05-26 08:53:10 +00003685static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003686 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003687
Sebastian Redl28507842009-02-26 14:39:58 +00003688 // Cannot know anything else if the expression is dependent.
3689 if (E->isTypeDependent())
3690 return false;
3691
John McCall10f6f062013-05-06 07:40:34 +00003692 if (E->getObjectKind() == OK_BitField) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003693 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3694 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003695 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003696 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003697
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003698 ValueDecl *D = nullptr;
John McCall10f6f062013-05-06 07:40:34 +00003699 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3700 D = DRE->getDecl();
3701 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3702 D = ME->getMemberDecl();
3703 }
3704
3705 // If it's a field, require the containing struct to have a
3706 // complete definition so that we can compute the layout.
3707 //
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003708 // This can happen in C++11 onwards, either by naming the member
3709 // in a way that is not transformed into a member access expression
3710 // (in an unevaluated operand, for instance), or by naming the member
3711 // in a trailing-return-type.
John McCall10f6f062013-05-06 07:40:34 +00003712 //
3713 // For the record, since __alignof__ on expressions is a GCC
3714 // extension, GCC seems to permit this but always gives the
3715 // nonsensical answer 0.
3716 //
3717 // We don't really need the layout here --- we could instead just
3718 // directly check for all the appropriate alignment-lowing
3719 // attributes --- but that would require duplicating a lot of
3720 // logic that just isn't worth duplicating for such a marginal
3721 // use-case.
3722 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3723 // Fast path this check, since we at least know the record has a
3724 // definition if we can find a member of it.
3725 if (!FD->getParent()->isCompleteDefinition()) {
3726 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3727 << E->getSourceRange();
3728 return true;
3729 }
3730
3731 // Otherwise, if it's a field, and the field doesn't have
3732 // reference type, then it must have a complete type (or be a
3733 // flexible array member, which we explicitly want to
3734 // white-list anyway), which makes the following checks trivial.
3735 if (!FD->getType()->isReferenceType())
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003736 return false;
John McCall10f6f062013-05-06 07:40:34 +00003737 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003738
Chandler Carruth9d342d02011-05-26 08:53:10 +00003739 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003740}
3741
Chandler Carruth9d342d02011-05-26 08:53:10 +00003742bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003743 E = E->IgnoreParens();
3744
3745 // Cannot know anything else if the expression is dependent.
3746 if (E->isTypeDependent())
3747 return false;
3748
Chandler Carruth9d342d02011-05-26 08:53:10 +00003749 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003750}
3751
Douglas Gregorba498172009-03-13 21:01:28 +00003752/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003753ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003754Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3755 SourceLocation OpLoc,
3756 UnaryExprOrTypeTrait ExprKind,
3757 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003758 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003759 return ExprError();
3760
John McCalla93c9342009-12-07 02:54:59 +00003761 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003762
Douglas Gregorba498172009-03-13 21:01:28 +00003763 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003764 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003765 return ExprError();
3766
3767 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003768 return new (Context) UnaryExprOrTypeTraitExpr(
3769 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
Douglas Gregorba498172009-03-13 21:01:28 +00003770}
3771
3772/// \brief Build a sizeof or alignof expression given an expression
3773/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003774ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003775Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3776 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00003777 ExprResult PE = CheckPlaceholderExpr(E);
3778 if (PE.isInvalid())
3779 return ExprError();
3780
3781 E = PE.get();
3782
Douglas Gregorba498172009-03-13 21:01:28 +00003783 // Verify that the operand is valid.
3784 bool isInvalid = false;
3785 if (E->isTypeDependent()) {
3786 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003787 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003788 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003789 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003790 isInvalid = CheckVecStepExpr(E);
John McCall993f43f2013-05-06 21:39:12 +00003791 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003792 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003793 isInvalid = true;
3794 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003795 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003796 }
3797
3798 if (isInvalid)
3799 return ExprError();
3800
Eli Friedman71b8fb52012-01-21 01:01:51 +00003801 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
Benjamin Krameraccaf192012-11-14 15:08:31 +00003802 PE = TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +00003803 if (PE.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003804 E = PE.get();
Eli Friedman71b8fb52012-01-21 01:01:51 +00003805 }
3806
Douglas Gregorba498172009-03-13 21:01:28 +00003807 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003808 return new (Context) UnaryExprOrTypeTraitExpr(
3809 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
Douglas Gregorba498172009-03-13 21:01:28 +00003810}
3811
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003812/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3813/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003814/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003815ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003816Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003817 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003818 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003819 // If error parsing type, ignore.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003820 if (!TyOrEx) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003821
Richard Trieuccd891a2011-09-09 01:45:06 +00003822 if (IsType) {
John McCalla93c9342009-12-07 02:54:59 +00003823 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003824 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003825 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003826 }
Sebastian Redl05189992008-11-11 17:56:53 +00003827
Douglas Gregorba498172009-03-13 21:01:28 +00003828 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003829 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003830 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00003831}
3832
John Wiegley429bb272011-04-08 18:41:53 +00003833static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003834 bool IsReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003835 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003836 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003837
John McCallf6a16482010-12-04 03:47:34 +00003838 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003839 if (V.get()->getObjectKind() != OK_Ordinary) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003840 V = S.DefaultLvalueConversion(V.get());
John Wiegley429bb272011-04-08 18:41:53 +00003841 if (V.isInvalid())
3842 return QualType();
3843 }
John McCallf6a16482010-12-04 03:47:34 +00003844
Chris Lattnercc26ed72007-08-26 05:39:26 +00003845 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003846 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003847 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Chris Lattnercc26ed72007-08-26 05:39:26 +00003849 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003850 if (V.get()->getType()->isArithmeticType())
3851 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003852
John McCall2cd11fe2010-10-12 02:09:17 +00003853 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003854 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003855 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003856 if (PR.get() != V.get()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003857 V = PR;
Richard Trieuccd891a2011-09-09 01:45:06 +00003858 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003859 }
3860
Chris Lattnercc26ed72007-08-26 05:39:26 +00003861 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003862 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuccd891a2011-09-09 01:45:06 +00003863 << (IsReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003864 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003865}
3866
3867
Reid Spencer5f016e22007-07-11 17:01:13 +00003868
John McCall60d7b3a2010-08-24 06:29:42 +00003869ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003870Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003871 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003872 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003873 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003874 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003875 case tok::plusplus: Opc = UO_PostInc; break;
3876 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003877 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003878
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003879 // Since this might is a postfix expression, get rid of ParenListExprs.
3880 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3881 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003882 Input = Result.get();
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003883
John McCall9ae2f072010-08-23 23:25:46 +00003884 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003885}
3886
John McCall1503f0d2012-07-31 05:14:30 +00003887/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3888///
3889/// \return true on error
3890static bool checkArithmeticOnObjCPointer(Sema &S,
3891 SourceLocation opLoc,
3892 Expr *op) {
3893 assert(op->getType()->isObjCObjectPointerType());
Fariborz Jahaniand9553e32013-11-01 21:58:17 +00003894 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3895 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
John McCall1503f0d2012-07-31 05:14:30 +00003896 return false;
3897
3898 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3899 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3900 << op->getSourceRange();
3901 return true;
3902}
3903
John McCall60d7b3a2010-08-24 06:29:42 +00003904ExprResult
John McCall7a534b92013-03-04 01:30:55 +00003905Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3906 Expr *idx, SourceLocation rbLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003907 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall7a534b92013-03-04 01:30:55 +00003908 if (isa<ParenListExpr>(base)) {
3909 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3910 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003911 base = result.get();
John McCall7a534b92013-03-04 01:30:55 +00003912 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00003913
John McCall7a534b92013-03-04 01:30:55 +00003914 // Handle any non-overload placeholder types in the base and index
3915 // expressions. We can't handle overloads here because the other
3916 // operand might be an overloadable type, in which case the overload
3917 // resolution for the operator overload should get the first crack
3918 // at the overload.
3919 if (base->getType()->isNonOverloadPlaceholderType()) {
3920 ExprResult result = CheckPlaceholderExpr(base);
3921 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003922 base = result.get();
John McCall7a534b92013-03-04 01:30:55 +00003923 }
3924 if (idx->getType()->isNonOverloadPlaceholderType()) {
3925 ExprResult result = CheckPlaceholderExpr(idx);
3926 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003927 idx = result.get();
John McCall7a534b92013-03-04 01:30:55 +00003928 }
Mike Stump1eb44332009-09-09 15:08:12 +00003929
John McCall7a534b92013-03-04 01:30:55 +00003930 // Build an unanalyzed expression if either operand is type-dependent.
David Blaikie4e4d0842012-03-11 07:00:24 +00003931 if (getLangOpts().CPlusPlus &&
John McCall7a534b92013-03-04 01:30:55 +00003932 (base->isTypeDependent() || idx->isTypeDependent())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003933 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3934 VK_LValue, OK_Ordinary, rbLoc);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003935 }
3936
John McCall7a534b92013-03-04 01:30:55 +00003937 // Use C++ overloaded-operator rules if either operand has record
3938 // type. The spec says to do this if either type is *overloadable*,
3939 // but enum types can't declare subscript operators or conversion
3940 // operators, so there's nothing interesting for overload resolution
3941 // to do if there aren't any record types involved.
3942 //
3943 // ObjC pointers have their own subscripting logic that is not tied
3944 // to overload resolution and so should not take this path.
David Blaikie4e4d0842012-03-11 07:00:24 +00003945 if (getLangOpts().CPlusPlus &&
John McCall7a534b92013-03-04 01:30:55 +00003946 (base->getType()->isRecordType() ||
3947 (!base->getType()->isObjCObjectPointerType() &&
3948 idx->getType()->isRecordType()))) {
3949 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003950 }
3951
John McCall7a534b92013-03-04 01:30:55 +00003952 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003953}
3954
John McCall60d7b3a2010-08-24 06:29:42 +00003955ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003956Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00003957 Expr *Idx, SourceLocation RLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00003958 Expr *LHSExp = Base;
3959 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003960
Chris Lattner12d9ff62007-07-16 00:14:47 +00003961 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003962 if (!LHSExp->getType()->getAs<VectorType>()) {
3963 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3964 if (Result.isInvalid())
3965 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003966 LHSExp = Result.get();
John Wiegley429bb272011-04-08 18:41:53 +00003967 }
3968 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3969 if (Result.isInvalid())
3970 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003971 RHSExp = Result.get();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003972
Chris Lattner12d9ff62007-07-16 00:14:47 +00003973 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003974 ExprValueKind VK = VK_LValue;
3975 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003976
Reid Spencer5f016e22007-07-11 17:01:13 +00003977 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003978 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003979 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003980 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003981 Expr *BaseExpr, *IndexExpr;
3982 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003983 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3984 BaseExpr = LHSExp;
3985 IndexExpr = RHSExp;
3986 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003987 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003988 BaseExpr = LHSExp;
3989 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003990 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003991 } else if (const ObjCObjectPointerType *PTy =
John McCall1503f0d2012-07-31 05:14:30 +00003992 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003993 BaseExpr = LHSExp;
3994 IndexExpr = RHSExp;
John McCall1503f0d2012-07-31 05:14:30 +00003995
3996 // Use custom logic if this should be the pseudo-object subscript
3997 // expression.
Fariborz Jahaniand9553e32013-11-01 21:58:17 +00003998 if (!LangOpts.isSubscriptPointerArithmetic())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003999 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4000 nullptr);
John McCall1503f0d2012-07-31 05:14:30 +00004001
Steve Naroff14108da2009-07-10 23:34:53 +00004002 ResultType = PTy->getPointeeType();
Fariborz Jahaniana78eca22012-03-28 17:56:49 +00004003 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4004 // Handle the uncommon case of "123[Ptr]".
4005 BaseExpr = RHSExp;
4006 IndexExpr = LHSExp;
4007 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004008 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00004009 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004010 // Handle the uncommon case of "123[Ptr]".
4011 BaseExpr = RHSExp;
4012 IndexExpr = LHSExp;
4013 ResultType = PTy->getPointeeType();
Fariborz Jahaniand9553e32013-11-01 21:58:17 +00004014 if (!LangOpts.isSubscriptPointerArithmetic()) {
John McCall1503f0d2012-07-31 05:14:30 +00004015 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4016 << ResultType << BaseExpr->getSourceRange();
4017 return ExprError();
4018 }
John McCall183700f2009-09-21 23:43:11 +00004019 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00004020 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00004021 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00004022 VK = LHSExp->getValueKind();
4023 if (VK != VK_RValue)
4024 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00004025
Chris Lattner12d9ff62007-07-16 00:14:47 +00004026 // FIXME: need to deal with const...
4027 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00004028 } else if (LHSTy->isArrayType()) {
4029 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00004030 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00004031 // wasn't promoted because of the C90 rule that doesn't
4032 // allow promoting non-lvalue arrays. Warn, then
4033 // force the promotion here.
4034 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4035 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004036 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004037 CK_ArrayToPointerDecay).get();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00004038 LHSTy = LHSExp->getType();
4039
4040 BaseExpr = LHSExp;
4041 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00004042 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00004043 } else if (RHSTy->isArrayType()) {
4044 // Same as previous, except for 123[f().a] case
4045 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4046 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004047 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004048 CK_ArrayToPointerDecay).get();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00004049 RHSTy = RHSExp->getType();
4050
4051 BaseExpr = RHSExp;
4052 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00004053 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004054 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00004055 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4056 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004057 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004058 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00004059 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00004060 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4061 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00004062
Daniel Dunbar7e88a602009-09-17 06:31:17 +00004063 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00004064 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4065 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00004066 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4067
Douglas Gregore7450f52009-03-24 19:52:54 +00004068 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00004069 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4070 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00004071 // incomplete types are not object types.
4072 if (ResultType->isFunctionType()) {
4073 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4074 << ResultType << BaseExpr->getSourceRange();
4075 return ExprError();
4076 }
Mike Stump1eb44332009-09-09 15:08:12 +00004077
David Blaikie4e4d0842012-03-11 07:00:24 +00004078 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara46358452010-09-13 06:50:07 +00004079 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00004080 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4081 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00004082
4083 // C forbids expressions of unqualified void type from being l-values.
4084 // See IsCForbiddenLValueType.
4085 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00004086 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004087 RequireCompleteType(LLoc, ResultType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004088 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregore7450f52009-03-24 19:52:54 +00004089 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004090
John McCall09431682010-11-18 19:01:18 +00004091 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00004092 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00004093
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004094 return new (Context)
4095 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004096}
4097
John McCall60d7b3a2010-08-24 06:29:42 +00004098ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004099 FunctionDecl *FD,
4100 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004101 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004102 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004103 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004104 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004105 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004106 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004107 return ExprError();
4108 }
4109
4110 if (Param->hasUninstantiatedDefaultArg()) {
4111 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004112
Richard Smithadb1d4c2012-07-22 23:45:10 +00004113 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4114 Param);
4115
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004116 // Instantiate the expression.
Richard Smithc95d4132013-05-03 23:46:09 +00004117 MultiLevelTemplateArgumentList MutiLevelArgList
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004118 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004119
Richard Smith7e54fb52012-07-16 01:09:10 +00004120 InstantiatingTemplate Inst(*this, CallLoc, Param,
Richard Smithc95d4132013-05-03 23:46:09 +00004121 MutiLevelArgList.getInnermost());
Alp Tokerd69f37b2013-10-08 08:09:04 +00004122 if (Inst.isInvalid())
Richard Smithab91ef12012-07-08 02:38:24 +00004123 return ExprError();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004124
Nico Weber08e41a62010-11-29 18:19:25 +00004125 ExprResult Result;
4126 {
4127 // C++ [dcl.fct.default]p5:
4128 // The names in the [default argument] expression are bound, and
4129 // the semantic constraints are checked, at the point where the
4130 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004131 ContextRAII SavedContext(*this, FD);
Douglas Gregor7bdc1522012-02-16 21:36:18 +00004132 LocalInstantiationScope Local(*this);
Richard Smithc95d4132013-05-03 23:46:09 +00004133 Result = SubstExpr(UninstExpr, MutiLevelArgList);
Nico Weber08e41a62010-11-29 18:19:25 +00004134 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004135 if (Result.isInvalid())
4136 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004138 // Check the expression as an initializer for the parameter.
4139 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004140 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004141 InitializationKind Kind
4142 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004143 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004144 Expr *ResultE = Result.getAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004145
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004146 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004147 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004148 if (Result.isInvalid())
4149 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004150
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004151 Expr *Arg = Result.getAs<Expr>();
Richard Smith6c3af3d2013-01-17 01:17:56 +00004152 CheckCompletedExpr(Arg, Param->getOuterLocStart());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004153 // Build the default argument expression.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004154 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004155 }
4156
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004157 // If the default expression creates temporaries, we need to
4158 // push them to the current stack of expression temporaries so they'll
4159 // be properly destroyed.
4160 // FIXME: We should really be rebuilding the default argument with new
4161 // bound temporaries; see the comment in PR5810.
John McCall80ee6e82011-11-10 05:35:25 +00004162 // We don't need to do that with block decls, though, because
4163 // blocks in default argument expression can never capture anything.
4164 if (isa<ExprWithCleanups>(Param->getInit())) {
4165 // Set the "needs cleanups" bit regardless of whether there are
4166 // any explicit objects.
John McCallf85e1932011-06-15 23:02:42 +00004167 ExprNeedsCleanups = true;
John McCall80ee6e82011-11-10 05:35:25 +00004168
4169 // Append all the objects to the cleanup list. Right now, this
4170 // should always be a no-op, because blocks in default argument
4171 // expressions should never be able to capture anything.
4172 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4173 "default argument expression has capturing blocks?");
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004174 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004175
4176 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004177 // Just mark all of the declarations in this potentially-evaluated expression
4178 // as being "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +00004179 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4180 /*SkipLocalVariables=*/true);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004181 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004182}
4183
Richard Smith831421f2012-06-25 20:30:08 +00004184
4185Sema::VariadicCallType
4186Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4187 Expr *Fn) {
4188 if (Proto && Proto->isVariadic()) {
4189 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4190 return VariadicConstructor;
4191 else if (Fn && Fn->getType()->isBlockPointerType())
4192 return VariadicBlock;
4193 else if (FDecl) {
4194 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4195 if (Method->isInstance())
4196 return VariadicMethod;
Richard Trieue2a90b82013-06-22 02:30:38 +00004197 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4198 return VariadicMethod;
Richard Smith831421f2012-06-25 20:30:08 +00004199 return VariadicFunction;
4200 }
4201 return VariadicDoesNotApply;
4202}
4203
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004204namespace {
4205class FunctionCallCCC : public FunctionCallFilterCCC {
4206public:
4207 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004208 unsigned NumArgs, MemberExpr *ME)
4209 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004210 FunctionName(FuncName) {}
4211
Stephen Hines651f13c2014-04-23 16:59:28 -07004212 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004213 if (!candidate.getCorrectionSpecifier() ||
4214 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4215 return false;
4216 }
4217
4218 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4219 }
4220
4221private:
4222 const IdentifierInfo *const FunctionName;
4223};
4224}
4225
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004226static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4227 FunctionDecl *FDecl,
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004228 ArrayRef<Expr *> Args) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004229 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4230 DeclarationName FuncName = FDecl->getDeclName();
4231 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004232
4233 if (TypoCorrection Corrected = S.CorrectTypo(
4234 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
Stephen Hines176edba2014-12-01 14:53:08 -08004235 S.getScopeForContext(S.CurContext), nullptr,
4236 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4237 Args.size(), ME),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004238 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004239 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4240 if (Corrected.isOverloaded()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004241 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004242 OverloadCandidateSet::iterator Best;
4243 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4244 CDEnd = Corrected.end();
4245 CD != CDEnd; ++CD) {
4246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4247 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4248 OCS);
4249 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004250 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004251 case OR_Success:
4252 ND = Best->Function;
4253 Corrected.setCorrectionDecl(ND);
4254 break;
4255 default:
4256 break;
4257 }
4258 }
4259 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4260 return Corrected;
4261 }
4262 }
4263 }
4264 return TypoCorrection();
4265}
4266
Douglas Gregor88a35142008-12-22 05:46:06 +00004267/// ConvertArgumentsForCall - Converts the arguments specified in
4268/// Args/NumArgs to the parameter types of the function FDecl with
4269/// function prototype Proto. Call is the call expression itself, and
4270/// Fn is the function expression. For a C++ member function, this
4271/// routine does not attempt to convert the object argument. Returns
4272/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004273bool
4274Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004275 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004276 const FunctionProtoType *Proto,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004277 ArrayRef<Expr *> Args,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004278 SourceLocation RParenLoc,
4279 bool IsExecConfig) {
John McCall8e10f3b2011-02-26 05:39:39 +00004280 // Bail out early if calling a builtin with custom typechecking.
4281 // We don't need to do this in the
4282 if (FDecl)
4283 if (unsigned ID = FDecl->getBuiltinID())
4284 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4285 return false;
4286
Mike Stumpeed9cac2009-02-19 03:04:26 +00004287 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004288 // assignment, to the types of the corresponding parameter, ...
Stephen Hines651f13c2014-04-23 16:59:28 -07004289 unsigned NumParams = Proto->getNumParams();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004290 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004291 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
Peter Collingbourne1f240762011-10-02 23:49:29 +00004292 unsigned FnKind = Fn->getType()->isBlockPointerType()
4293 ? 1 /* block */
4294 : (IsExecConfig ? 3 /* kernel function (exec config) */
4295 : 0 /* function */);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004296
Douglas Gregor88a35142008-12-22 05:46:06 +00004297 // If too few arguments are available (and we don't have default
4298 // arguments for the remaining parameters), don't make the call.
Stephen Hines651f13c2014-04-23 16:59:28 -07004299 if (Args.size() < NumParams) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004300 if (Args.size() < MinArgs) {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004301 TypoCorrection TC;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004302 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004303 unsigned diag_id =
Stephen Hines651f13c2014-04-23 16:59:28 -07004304 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004305 ? diag::err_typecheck_call_too_few_args_suggest
4306 : diag::err_typecheck_call_too_few_args_at_least_suggest;
Richard Smith2d670972013-08-17 00:46:16 +00004307 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4308 << static_cast<unsigned>(Args.size())
Stephen Hines651f13c2014-04-23 16:59:28 -07004309 << TC.getCorrectionRange());
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004310 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
Stephen Hines651f13c2014-04-23 16:59:28 -07004311 Diag(RParenLoc,
4312 MinArgs == NumParams && !Proto->isVariadic()
4313 ? diag::err_typecheck_call_too_few_args_one
4314 : diag::err_typecheck_call_too_few_args_at_least_one)
4315 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
Richard Smithf7b80562012-05-11 05:16:41 +00004316 else
Stephen Hines651f13c2014-04-23 16:59:28 -07004317 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4318 ? diag::err_typecheck_call_too_few_args
4319 : diag::err_typecheck_call_too_few_args_at_least)
4320 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4321 << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00004322
4323 // Emit the location of the prototype.
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004324 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00004325 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4326 << FDecl;
4327
4328 return true;
4329 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004330 Call->setNumArgs(Context, NumParams);
Douglas Gregor88a35142008-12-22 05:46:06 +00004331 }
4332
4333 // If too many are passed and not variadic, error on the extras and drop
4334 // them.
Stephen Hines651f13c2014-04-23 16:59:28 -07004335 if (Args.size() > NumParams) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004336 if (!Proto->isVariadic()) {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004337 TypoCorrection TC;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004338 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004339 unsigned diag_id =
Stephen Hines651f13c2014-04-23 16:59:28 -07004340 MinArgs == NumParams && !Proto->isVariadic()
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004341 ? diag::err_typecheck_call_too_many_args_suggest
4342 : diag::err_typecheck_call_too_many_args_at_most_suggest;
Stephen Hines651f13c2014-04-23 16:59:28 -07004343 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
Richard Smith2d670972013-08-17 00:46:16 +00004344 << static_cast<unsigned>(Args.size())
Stephen Hines651f13c2014-04-23 16:59:28 -07004345 << TC.getCorrectionRange());
4346 } else if (NumParams == 1 && FDecl &&
Richard Smith2d670972013-08-17 00:46:16 +00004347 FDecl->getParamDecl(0)->getDeclName())
Stephen Hines651f13c2014-04-23 16:59:28 -07004348 Diag(Args[NumParams]->getLocStart(),
4349 MinArgs == NumParams
4350 ? diag::err_typecheck_call_too_many_args_one
4351 : diag::err_typecheck_call_too_many_args_at_most_one)
4352 << FnKind << FDecl->getParamDecl(0)
4353 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4354 << SourceRange(Args[NumParams]->getLocStart(),
4355 Args.back()->getLocEnd());
Richard Smithc608c3c2012-05-15 06:21:54 +00004356 else
Stephen Hines651f13c2014-04-23 16:59:28 -07004357 Diag(Args[NumParams]->getLocStart(),
4358 MinArgs == NumParams
4359 ? diag::err_typecheck_call_too_many_args
4360 : diag::err_typecheck_call_too_many_args_at_most)
4361 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4362 << Fn->getSourceRange()
4363 << SourceRange(Args[NumParams]->getLocStart(),
4364 Args.back()->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004365
4366 // Emit the location of the prototype.
Kaelyn Uhrain6c4898b2013-07-08 23:13:44 +00004367 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne9aab1482011-07-29 00:24:42 +00004368 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4369 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004370
Douglas Gregor88a35142008-12-22 05:46:06 +00004371 // This deletes the extra arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07004372 Call->setNumArgs(Context, NumParams);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004373 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004374 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004375 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00004376 SmallVector<Expr *, 8> AllArgs;
Richard Smith831421f2012-06-25 20:30:08 +00004377 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4378
Daniel Dunbar96a00142012-03-09 18:35:03 +00004379 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004380 Proto, 0, Args, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004381 if (Invalid)
4382 return true;
4383 unsigned TotalNumArgs = AllArgs.size();
4384 for (unsigned i = 0; i < TotalNumArgs; ++i)
4385 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004386
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004387 return false;
4388}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004389
Stephen Hines651f13c2014-04-23 16:59:28 -07004390bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004391 const FunctionProtoType *Proto,
Stephen Hines651f13c2014-04-23 16:59:28 -07004392 unsigned FirstParam, ArrayRef<Expr *> Args,
Craig Topper6b9240e2013-07-05 19:34:19 +00004393 SmallVectorImpl<Expr *> &AllArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07004394 VariadicCallType CallType, bool AllowExplicit,
Richard Smitha4dc51b2013-02-05 05:52:24 +00004395 bool IsListInitialization) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004396 unsigned NumParams = Proto->getNumParams();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004397 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004398 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004399 // Continue to check argument types (even if we have too few/many args).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004400 for (unsigned i = FirstParam; i < NumParams; i++) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004401 QualType ProtoArgType = Proto->getParamType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004402
Douglas Gregor88a35142008-12-22 05:46:06 +00004403 Expr *Arg;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004404 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004405 if (ArgIx < Args.size()) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004406 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004407
Daniel Dunbar96a00142012-03-09 18:35:03 +00004408 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004409 ProtoArgType,
Douglas Gregord10099e2012-05-04 16:32:21 +00004410 diag::err_call_incomplete_argument, Arg))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004411 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004412
John McCall5acb0c92011-10-17 18:40:02 +00004413 // Strip the unbridged-cast placeholder expression off, if applicable.
Fariborz Jahanian650c6052013-07-31 18:39:08 +00004414 bool CFAudited = false;
John McCall5acb0c92011-10-17 18:40:02 +00004415 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4416 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4417 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4418 Arg = stripARCUnbridgedCast(Arg);
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004419 else if (getLangOpts().ObjCAutoRefCount &&
4420 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
Fariborz Jahanian650c6052013-07-31 18:39:08 +00004421 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4422 CFAudited = true;
John McCall5acb0c92011-10-17 18:40:02 +00004423
Stephen Hines651f13c2014-04-23 16:59:28 -07004424 InitializedEntity Entity =
4425 Param ? InitializedEntity::InitializeParameter(Context, Param,
4426 ProtoArgType)
4427 : InitializedEntity::InitializeParameter(
4428 Context, ProtoArgType, Proto->isParamConsumed(i));
4429
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004430 // Remember that parameter belongs to a CF audited API.
Fariborz Jahanian650c6052013-07-31 18:39:08 +00004431 if (CFAudited)
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004432 Entity.setParameterCFAudited();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004433
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004434 ExprResult ArgE = PerformCopyInitialization(
4435 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
Douglas Gregora188ff22009-12-22 16:09:06 +00004436 if (ArgE.isInvalid())
4437 return true;
4438
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004439 Arg = ArgE.getAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004440 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004441 assert(Param && "can't use default arguments without a known callee");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004442
John McCall60d7b3a2010-08-24 06:29:42 +00004443 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004444 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004445 if (ArgExpr.isInvalid())
4446 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004447
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004448 Arg = ArgExpr.getAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004449 }
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004450
4451 // Check for array bounds violations for each argument to the call. This
4452 // check only triggers warnings when the argument isn't a more complex Expr
4453 // with its own checking, such as a BinaryOperator.
4454 CheckArrayAccess(Arg);
4455
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004456 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4457 CheckStaticArrayArgument(CallLoc, Param, Arg);
4458
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004459 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004460 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004461
Douglas Gregor88a35142008-12-22 05:46:06 +00004462 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004463 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004464 // Assume that extern "C" functions with variadic arguments that
4465 // return __unknown_anytype aren't *really* variadic.
Stephen Hines651f13c2014-04-23 16:59:28 -07004466 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4467 FDecl->isExternC()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004468 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
John McCall48f90422013-03-04 07:34:02 +00004469 QualType paramType; // ignored
4470 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
John McCall755d8492011-04-12 00:42:48 +00004471 Invalid |= arg.isInvalid();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004472 AllArgs.push_back(arg.get());
John McCall755d8492011-04-12 00:42:48 +00004473 }
4474
4475 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4476 } else {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004477 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00004478 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4479 FDecl);
John McCall755d8492011-04-12 00:42:48 +00004480 Invalid |= Arg.isInvalid();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004481 AllArgs.push_back(Arg.get());
John McCall755d8492011-04-12 00:42:48 +00004482 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004483 }
Ted Kremenek615eb7c2011-09-26 23:36:13 +00004484
4485 // Check for array bounds violations.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004486 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
Ted Kremenek615eb7c2011-09-26 23:36:13 +00004487 CheckArrayAccess(Args[i]);
Douglas Gregor88a35142008-12-22 05:46:06 +00004488 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004489 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004490}
4491
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004492static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4493 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
Reid Kleckner12df2462013-06-24 17:51:48 +00004494 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4495 TL = DTL.getOriginalLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00004496 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004497 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
David Blaikie39e6ab42013-02-18 22:06:02 +00004498 << ATL.getLocalSourceRange();
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004499}
4500
4501/// CheckStaticArrayArgument - If the given argument corresponds to a static
4502/// array parameter, check that it is non-null, and that if it is formed by
4503/// array-to-pointer decay, the underlying array is sufficiently large.
4504///
4505/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4506/// array type derivation, then for each call to the function, the value of the
4507/// corresponding actual argument shall provide access to the first element of
4508/// an array with at least as many elements as specified by the size expression.
4509void
4510Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4511 ParmVarDecl *Param,
4512 const Expr *ArgExpr) {
4513 // Static array parameters are not supported in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00004514 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbourne013e5ce2011-10-19 00:16:45 +00004515 return;
4516
4517 QualType OrigTy = Param->getOriginalType();
4518
4519 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4520 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4521 return;
4522
4523 if (ArgExpr->isNullPointerConstant(Context,
4524 Expr::NPC_NeverValueDependent)) {
4525 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4526 DiagnoseCalleeStaticArrayParam(*this, Param);
4527 return;
4528 }
4529
4530 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4531 if (!CAT)
4532 return;
4533
4534 const ConstantArrayType *ArgCAT =
4535 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4536 if (!ArgCAT)
4537 return;
4538
4539 if (ArgCAT->getSize().ult(CAT->getSize())) {
4540 Diag(CallLoc, diag::warn_static_array_too_small)
4541 << ArgExpr->getSourceRange()
4542 << (unsigned) ArgCAT->getSize().getZExtValue()
4543 << (unsigned) CAT->getSize().getZExtValue();
4544 DiagnoseCalleeStaticArrayParam(*this, Param);
4545 }
4546}
4547
John McCall755d8492011-04-12 00:42:48 +00004548/// Given a function expression of unknown-any type, try to rebuild it
4549/// to have a function type.
4550static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4551
John McCall76da55d2013-04-16 07:28:30 +00004552/// Is the given type a placeholder that we need to lower out
4553/// immediately during argument processing?
4554static bool isPlaceholderToRemoveAsArg(QualType type) {
4555 // Placeholders are never sugared.
4556 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4557 if (!placeholder) return false;
4558
4559 switch (placeholder->getKind()) {
4560 // Ignore all the non-placeholder types.
4561#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4562#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4563#include "clang/AST/BuiltinTypes.def"
4564 return false;
4565
4566 // We cannot lower out overload sets; they might validly be resolved
4567 // by the call machinery.
4568 case BuiltinType::Overload:
4569 return false;
4570
4571 // Unbridged casts in ARC can be handled in some call positions and
4572 // should be left in place.
4573 case BuiltinType::ARCUnbridgedCast:
4574 return false;
4575
4576 // Pseudo-objects should be converted as soon as possible.
4577 case BuiltinType::PseudoObject:
4578 return true;
4579
4580 // The debugger mode could theoretically but currently does not try
4581 // to resolve unknown-typed arguments based on known parameter types.
4582 case BuiltinType::UnknownAny:
4583 return true;
4584
4585 // These are always invalid as call arguments and should be reported.
4586 case BuiltinType::BoundMember:
4587 case BuiltinType::BuiltinFn:
4588 return true;
4589 }
4590 llvm_unreachable("bad builtin type kind");
4591}
4592
4593/// Check an argument list for placeholders that we won't try to
4594/// handle later.
4595static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4596 // Apply this processing to all the arguments at once instead of
4597 // dying at the first failure.
4598 bool hasInvalid = false;
4599 for (size_t i = 0, e = args.size(); i != e; i++) {
4600 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4601 ExprResult result = S.CheckPlaceholderExpr(args[i]);
4602 if (result.isInvalid()) hasInvalid = true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004603 else args[i] = result.get();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004604 } else if (hasInvalid) {
4605 (void)S.CorrectDelayedTyposInExpr(args[i]);
John McCall76da55d2013-04-16 07:28:30 +00004606 }
4607 }
4608 return hasInvalid;
4609}
4610
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07004611/// If a builtin function has a pointer argument with no explicit address
4612/// space, than it should be able to accept a pointer to any address
4613/// space as input. In order to do this, we need to replace the
4614/// standard builtin declaration with one that uses the same address space
4615/// as the call.
4616///
4617/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4618/// it does not contain any pointer arguments without
4619/// an address space qualifer. Otherwise the rewritten
4620/// FunctionDecl is returned.
4621/// TODO: Handle pointer return types.
4622static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4623 const FunctionDecl *FDecl,
4624 MultiExprArg ArgExprs) {
4625
4626 QualType DeclType = FDecl->getType();
4627 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4628
4629 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4630 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4631 return nullptr;
4632
4633 bool NeedsNewDecl = false;
4634 unsigned i = 0;
4635 SmallVector<QualType, 8> OverloadParams;
4636
4637 for (QualType ParamType : FT->param_types()) {
4638
4639 // Convert array arguments to pointer to simplify type lookup.
4640 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4641 QualType ArgType = Arg->getType();
4642 if (!ParamType->isPointerType() ||
4643 ParamType.getQualifiers().hasAddressSpace() ||
4644 !ArgType->isPointerType() ||
4645 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4646 OverloadParams.push_back(ParamType);
4647 continue;
4648 }
4649
4650 NeedsNewDecl = true;
4651 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4652
4653 QualType PointeeType = ParamType->getPointeeType();
4654 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4655 OverloadParams.push_back(Context.getPointerType(PointeeType));
4656 }
4657
4658 if (!NeedsNewDecl)
4659 return nullptr;
4660
4661 FunctionProtoType::ExtProtoInfo EPI;
4662 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4663 OverloadParams, EPI);
4664 DeclContext *Parent = Context.getTranslationUnitDecl();
4665 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4666 FDecl->getLocation(),
4667 FDecl->getLocation(),
4668 FDecl->getIdentifier(),
4669 OverloadTy,
4670 /*TInfo=*/nullptr,
4671 SC_Extern, false,
4672 /*hasPrototype=*/true);
4673 SmallVector<ParmVarDecl*, 16> Params;
4674 FT = cast<FunctionProtoType>(OverloadTy);
4675 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4676 QualType ParamType = FT->getParamType(i);
4677 ParmVarDecl *Parm =
4678 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4679 SourceLocation(), nullptr, ParamType,
4680 /*TInfo=*/nullptr, SC_None, nullptr);
4681 Parm->setScopeInfo(0, i);
4682 Params.push_back(Parm);
4683 }
4684 OverloadDecl->setParams(Params);
4685 return OverloadDecl;
4686}
4687
Steve Narofff69936d2007-09-16 03:34:24 +00004688/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004689/// This provides the location of the left/right parens and a list of comma
4690/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004691ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004692Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00004693 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004694 Expr *ExecConfig, bool IsExecConfig) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004695 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004696 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004697 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004698 Fn = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004699
John McCall76da55d2013-04-16 07:28:30 +00004700 if (checkArgsForPlaceholders(*this, ArgExprs))
4701 return ExprError();
4702
David Blaikie4e4d0842012-03-11 07:00:24 +00004703 if (getLangOpts().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004704 // If this is a pseudo-destructor expression, build the call immediately.
4705 if (isa<CXXPseudoDestructorExpr>(Fn)) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004706 if (!ArgExprs.empty()) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004707 // Pseudo-destructor calls should not have any arguments.
4708 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004709 << FixItHint::CreateRemoval(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004710 SourceRange(ArgExprs[0]->getLocStart(),
4711 ArgExprs.back()->getLocEnd()));
Douglas Gregora71d8192009-09-04 17:36:40 +00004712 }
Mike Stump1eb44332009-09-09 15:08:12 +00004713
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004714 return new (Context)
4715 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
Douglas Gregora71d8192009-09-04 17:36:40 +00004716 }
John McCall76da55d2013-04-16 07:28:30 +00004717 if (Fn->getType() == Context.PseudoObjectTy) {
4718 ExprResult result = CheckPlaceholderExpr(Fn);
4719 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004720 Fn = result.get();
John McCall76da55d2013-04-16 07:28:30 +00004721 }
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Douglas Gregor17330012009-02-04 15:01:18 +00004723 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004724 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004725 // FIXME: Will need to cache the results of name lookup (including ADL) in
4726 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004727 bool Dependent = false;
4728 if (Fn->isTypeDependent())
4729 Dependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004730 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
Douglas Gregor17330012009-02-04 15:01:18 +00004731 Dependent = true;
4732
Peter Collingbournee08ce652011-02-09 21:07:24 +00004733 if (Dependent) {
4734 if (ExecConfig) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004735 return new (Context) CUDAKernelCallExpr(
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004736 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004737 Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004738 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004739 return new (Context) CallExpr(
4740 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004741 }
4742 }
Douglas Gregor17330012009-02-04 15:01:18 +00004743
4744 // Determine whether this is a call to an object (C++ [over.call.object]).
4745 if (Fn->getType()->isRecordType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004746 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4747 RParenLoc);
Douglas Gregor17330012009-02-04 15:01:18 +00004748
John McCall755d8492011-04-12 00:42:48 +00004749 if (Fn->getType() == Context.UnknownAnyTy) {
4750 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4751 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004752 Fn = result.get();
John McCall755d8492011-04-12 00:42:48 +00004753 }
4754
John McCall864c0412011-04-26 20:42:42 +00004755 if (Fn->getType() == Context.BoundMemberTy) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004756 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004757 }
John McCall864c0412011-04-26 20:42:42 +00004758 }
John McCall129e2df2009-11-30 22:42:35 +00004759
John McCall864c0412011-04-26 20:42:42 +00004760 // Check for overloaded calls. This can happen even in C due to extensions.
4761 if (Fn->getType() == Context.OverloadTy) {
4762 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4763
Douglas Gregoree697e62011-10-13 18:10:35 +00004764 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregor64a371f2011-10-13 18:26:27 +00004765 if (!find.HasFormOfMemberPointer) {
John McCall864c0412011-04-26 20:42:42 +00004766 OverloadExpr *ovl = find.Expression;
4767 if (isa<UnresolvedLookupExpr>(ovl)) {
4768 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004769 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4770 RParenLoc, ExecConfig);
John McCall864c0412011-04-26 20:42:42 +00004771 } else {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004772 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4773 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004774 }
4775 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004776 }
4777
Douglas Gregorfa047642009-02-04 00:32:51 +00004778 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00004779 if (Fn->getType() == Context.UnknownAnyTy) {
4780 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4781 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004782 Fn = result.get();
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00004783 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004784
Eli Friedmanefa42f72009-12-26 03:35:45 +00004785 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004786
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004787 NamedDecl *NDecl = nullptr;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004788 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4789 if (UnOp->getOpcode() == UO_AddrOf)
4790 NakedFn = UnOp->getSubExpr()->IgnoreParens();
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07004791
4792 if (isa<DeclRefExpr>(NakedFn)) {
John McCall3b4294e2009-12-16 12:17:52 +00004793 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07004794
4795 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4796 if (FDecl && FDecl->getBuiltinID()) {
4797 // Rewrite the function decl for this builtin by replacing paramaters
4798 // with no explicit address space with the address space of the arguments
4799 // in ArgExprs.
4800 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4801 NDecl = FDecl;
4802 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4803 SourceLocation(), FDecl, false,
4804 SourceLocation(), FDecl->getType(),
4805 Fn->getValueKind(), FDecl);
4806 }
4807 }
4808 } else if (isa<MemberExpr>(NakedFn))
John McCall864c0412011-04-26 20:42:42 +00004809 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00004810
Stephen Hines651f13c2014-04-23 16:59:28 -07004811 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4812 if (FD->hasAttr<EnableIfAttr>()) {
4813 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4814 Diag(Fn->getLocStart(),
4815 isa<CXXMethodDecl>(FD) ?
4816 diag::err_ovl_no_viable_member_function_in_call :
4817 diag::err_ovl_no_viable_function_in_call)
4818 << FD << FD->getSourceRange();
4819 Diag(FD->getLocation(),
4820 diag::note_ovl_candidate_disabled_by_enable_if_attr)
4821 << Attr->getCond()->getSourceRange() << Attr->getMessage();
4822 }
4823 }
4824 }
4825
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004826 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4827 ExecConfig, IsExecConfig);
Peter Collingbournee08ce652011-02-09 21:07:24 +00004828}
4829
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004830/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4831///
4832/// __builtin_astype( value, dst type )
4833///
Richard Trieuccd891a2011-09-09 01:45:06 +00004834ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004835 SourceLocation BuiltinLoc,
4836 SourceLocation RParenLoc) {
4837 ExprValueKind VK = VK_RValue;
4838 ExprObjectKind OK = OK_Ordinary;
Richard Trieuccd891a2011-09-09 01:45:06 +00004839 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4840 QualType SrcTy = E->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004841 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4842 return ExprError(Diag(BuiltinLoc,
4843 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00004844 << DstTy
4845 << SrcTy
Richard Trieuccd891a2011-09-09 01:45:06 +00004846 << E->getSourceRange());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004847 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004848}
4849
Hal Finkel414a1bd2013-09-18 03:29:45 +00004850/// ActOnConvertVectorExpr - create a new convert-vector expression from the
4851/// provided arguments.
4852///
4853/// __builtin_convertvector( value, dst type )
4854///
4855ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4856 SourceLocation BuiltinLoc,
4857 SourceLocation RParenLoc) {
4858 TypeSourceInfo *TInfo;
4859 GetTypeFromParser(ParsedDestTy, &TInfo);
4860 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4861}
4862
John McCall3b4294e2009-12-16 12:17:52 +00004863/// BuildResolvedCallExpr - Build a call to a resolved expression,
4864/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004865/// unary-convert to an expression of function-pointer or
4866/// block-pointer type.
4867///
4868/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004869ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004870Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4871 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004872 ArrayRef<Expr *> Args,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004873 SourceLocation RParenLoc,
Peter Collingbourne1f240762011-10-02 23:49:29 +00004874 Expr *Config, bool IsExecConfig) {
John McCallaa81e162009-12-01 22:10:20 +00004875 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004876 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
John McCallaa81e162009-12-01 22:10:20 +00004877
Chris Lattner04421082008-04-08 04:40:51 +00004878 // Promote the function operand.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004879 // We special-case function promotion here because we only allow promoting
4880 // builtin functions to function pointers in the callee of a call.
4881 ExprResult Result;
4882 if (BuiltinID &&
4883 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4884 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004885 CK_BuiltinFnToFnPtr).get();
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004886 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07004887 Result = CallExprUnaryConversions(Fn);
Eli Friedmana6c66ce2012-08-31 00:14:07 +00004888 }
John Wiegley429bb272011-04-08 18:41:53 +00004889 if (Result.isInvalid())
4890 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004891 Fn = Result.get();
Chris Lattner04421082008-04-08 04:40:51 +00004892
Chris Lattner925e60d2007-12-28 05:29:59 +00004893 // Make the call expr early, before semantic checks. This guarantees cleanup
4894 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004895 CallExpr *TheCall;
Eric Christophera27cb252012-05-30 01:14:28 +00004896 if (Config)
Peter Collingbournee08ce652011-02-09 21:07:24 +00004897 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004898 cast<CallExpr>(Config), Args,
4899 Context.BoolTy, VK_RValue,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004900 RParenLoc);
Eric Christophera27cb252012-05-30 01:14:28 +00004901 else
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004902 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4903 VK_RValue, RParenLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004904
John McCall8e10f3b2011-02-26 05:39:39 +00004905 // Bail out early if calling a builtin with custom typechecking.
4906 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
Stephen Hines176edba2014-12-01 14:53:08 -08004907 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
John McCall8e10f3b2011-02-26 05:39:39 +00004908
John McCall1de4d4e2011-04-07 08:22:57 +00004909 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004910 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004911 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004912 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4913 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004914 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004915 if (!FuncT)
John McCall8e10f3b2011-02-26 05:39:39 +00004916 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4917 << Fn->getType() << Fn->getSourceRange());
4918 } else if (const BlockPointerType *BPT =
4919 Fn->getType()->getAs<BlockPointerType>()) {
4920 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4921 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00004922 // Handle calls to expressions of unknown-any type.
4923 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00004924 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004925 if (rewrite.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004926 Fn = rewrite.get();
John McCalla5fc4722011-04-09 22:50:59 +00004927 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00004928 goto retry;
4929 }
4930
Sebastian Redl0eb23302009-01-19 00:08:26 +00004931 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4932 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00004933 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004934
David Blaikie4e4d0842012-03-11 07:00:24 +00004935 if (getLangOpts().CUDA) {
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004936 if (Config) {
4937 // CUDA: Kernel calls must be to global functions
4938 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4939 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4940 << FDecl->getName() << Fn->getSourceRange());
4941
4942 // CUDA: Kernel function must have 'void' return type
Stephen Hines651f13c2014-04-23 16:59:28 -07004943 if (!FuncT->getReturnType()->isVoidType())
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004944 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4945 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne8591a7f2011-10-02 23:49:15 +00004946 } else {
4947 // CUDA: Calls to global functions must be configured
4948 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4949 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4950 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne0423fc62011-02-23 01:53:29 +00004951 }
4952 }
4953
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004954 // Check for a valid return type
Stephen Hines651f13c2014-04-23 16:59:28 -07004955 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004956 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004957 return ExprError();
4958
Chris Lattner925e60d2007-12-28 05:29:59 +00004959 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004960 TheCall->setType(FuncT->getCallResultType(Context));
Stephen Hines651f13c2014-04-23 16:59:28 -07004961 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00004962
Richard Smith831421f2012-06-25 20:30:08 +00004963 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4964 if (Proto) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004965 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4966 IsExecConfig))
Sebastian Redl0eb23302009-01-19 00:08:26 +00004967 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00004968 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004969 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00004970
Douglas Gregor74734d52009-04-02 15:37:10 +00004971 if (FDecl) {
4972 // Check if we have too few/too many template arguments, based
4973 // on our knowledge of the function definition.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004974 const FunctionDecl *Def = nullptr;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004975 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
Richard Smith831421f2012-06-25 20:30:08 +00004976 Proto = Def->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004977 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004978 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004979 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00004980 }
Douglas Gregor46542412010-10-25 20:39:23 +00004981
4982 // If the function we're calling isn't a function prototype, but we have
4983 // a function prototype from a prior declaratiom, use that prototype.
4984 if (!FDecl->hasPrototype())
4985 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00004986 }
4987
Steve Naroffb291ab62007-08-28 23:30:39 +00004988 // Promote the arguments (C99 6.5.2.2p6).
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00004989 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Chris Lattner925e60d2007-12-28 05:29:59 +00004990 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00004991
Stephen Hines651f13c2014-04-23 16:59:28 -07004992 if (Proto && i < Proto->getNumParams()) {
4993 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4994 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004995 ExprResult ArgE =
4996 PerformCopyInitialization(Entity, SourceLocation(), Arg);
Douglas Gregor46542412010-10-25 20:39:23 +00004997 if (ArgE.isInvalid())
4998 return true;
4999
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005000 Arg = ArgE.getAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005001
5002 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005003 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5004
5005 if (ArgE.isInvalid())
5006 return true;
5007
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005008 Arg = ArgE.getAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005009 }
5010
Daniel Dunbar96a00142012-03-09 18:35:03 +00005011 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005012 Arg->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005013 diag::err_call_incomplete_argument, Arg))
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005014 return ExprError();
5015
Chris Lattner925e60d2007-12-28 05:29:59 +00005016 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005017 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005018 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005019
Douglas Gregor88a35142008-12-22 05:46:06 +00005020 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5021 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005022 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5023 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005024
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005025 // Check for sentinels
5026 if (NDecl)
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00005027 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00005028
Chris Lattner59907c42007-08-10 20:18:51 +00005029 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005030 if (FDecl) {
Richard Smith831421f2012-06-25 20:30:08 +00005031 if (CheckFunctionCall(FDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00005032 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005033
John McCall8e10f3b2011-02-26 05:39:39 +00005034 if (BuiltinID)
Stephen Hines176edba2014-12-01 14:53:08 -08005035 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005036 } else if (NDecl) {
Richard Trieuf462b012013-06-20 21:03:13 +00005037 if (CheckPointerCall(NDecl, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +00005038 return ExprError();
Richard Trieu0538f0e2013-06-22 00:20:41 +00005039 } else {
5040 if (CheckOtherCall(TheCall, Proto))
5041 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +00005042 }
Chris Lattner59907c42007-08-10 20:18:51 +00005043
John McCall9ae2f072010-08-23 23:25:46 +00005044 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005045}
5046
John McCall60d7b3a2010-08-24 06:29:42 +00005047ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005048Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005049 SourceLocation RParenLoc, Expr *InitExpr) {
David Blaikie7247c882013-05-15 07:37:26 +00005050 assert(Ty && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005051 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005052 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005053
5054 TypeSourceInfo *TInfo;
5055 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5056 if (!TInfo)
5057 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5058
John McCall9ae2f072010-08-23 23:25:46 +00005059 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005060}
5061
John McCall60d7b3a2010-08-24 06:29:42 +00005062ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005063Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuccd891a2011-09-09 01:45:06 +00005064 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005065 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005066
Eli Friedman6223c222008-05-20 05:22:08 +00005067 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005068 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregord10099e2012-05-04 16:32:21 +00005069 diag::err_illegal_decl_array_incomplete_type,
5070 SourceRange(LParenLoc,
5071 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005072 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005073 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005074 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuccd891a2011-09-09 01:45:06 +00005075 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005076 } else if (!literalType->isDependentType() &&
5077 RequireCompleteType(LParenLoc, literalType,
Douglas Gregord10099e2012-05-04 16:32:21 +00005078 diag::err_typecheck_decl_incomplete_type,
5079 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005080 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005081
Douglas Gregor99a2e602009-12-16 01:38:02 +00005082 InitializedEntity Entity
Jordan Rose2624b812013-05-06 16:48:12 +00005083 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005084 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00005085 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00005086 SourceRange(LParenLoc, RParenLoc),
5087 /*InitList=*/true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005088 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
Benjamin Kramer5354e772012-08-23 23:38:35 +00005089 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5090 &literalType);
Eli Friedman08544622009-12-22 02:35:53 +00005091 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005092 return ExprError();
Richard Trieuccd891a2011-09-09 01:45:06 +00005093 LiteralExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005094
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005095 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
Eli Friedman9b93f202013-10-01 00:28:29 +00005096 if (isFileScope &&
5097 !LiteralExpr->isTypeDependent() &&
5098 !LiteralExpr->isValueDependent() &&
5099 !literalType->isDependentType()) { // 6.5.2.5p3
Richard Trieuccd891a2011-09-09 01:45:06 +00005100 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005101 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005102 }
Eli Friedman08544622009-12-22 02:35:53 +00005103
John McCallf89e55a2010-11-18 06:31:45 +00005104 // In C, compound literals are l-values for some reason.
David Blaikie4e4d0842012-03-11 07:00:24 +00005105 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCallf89e55a2010-11-18 06:31:45 +00005106
Douglas Gregor751ec9b2011-06-17 04:59:12 +00005107 return MaybeBindToTemporary(
5108 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuccd891a2011-09-09 01:45:06 +00005109 VK, LiteralExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005110}
5111
John McCall60d7b3a2010-08-24 06:29:42 +00005112ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00005113Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005114 SourceLocation RBraceLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00005115 // Immediately handle non-overload placeholders. Overloads can be
5116 // resolved contextually, but everything else here can't.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005117 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5118 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5119 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
John McCall3c3b7f92011-10-25 17:37:35 +00005120
5121 // Ignore failures; dropping the entire initializer list because
5122 // of one failure would be terrible for indexing/etc.
5123 if (result.isInvalid()) continue;
5124
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005125 InitArgList[I] = result.get();
John McCall3c3b7f92011-10-25 17:37:35 +00005126 }
5127 }
5128
Steve Naroff08d92e42007-09-15 18:49:24 +00005129 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005130 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005131
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005132 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5133 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005134 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005135 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00005136}
5137
John McCalldc05b112011-09-10 01:16:55 +00005138/// Do an explicit extend of the given block pointer if we're in ARC.
5139static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
5140 assert(E.get()->getType()->isBlockPointerType());
5141 assert(E.get()->isRValue());
5142
5143 // Only do this in an r-value context.
David Blaikie4e4d0842012-03-11 07:00:24 +00005144 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCalldc05b112011-09-10 01:16:55 +00005145
5146 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall33e56f32011-09-10 06:18:15 +00005147 CK_ARCExtendBlockObject, E.get(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005148 /*base path*/ nullptr, VK_RValue);
John McCalldc05b112011-09-10 01:16:55 +00005149 S.ExprNeedsCleanups = true;
5150}
5151
5152/// Prepare a conversion of the given expression to an ObjC object
5153/// pointer type.
5154CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5155 QualType type = E.get()->getType();
5156 if (type->isObjCObjectPointerType()) {
5157 return CK_BitCast;
5158 } else if (type->isBlockPointerType()) {
5159 maybeExtendBlockObject(*this, E);
5160 return CK_BlockPointerToObjCPointerCast;
5161 } else {
5162 assert(type->isPointerType());
5163 return CK_CPointerToObjCPointerCast;
5164 }
5165}
5166
John McCallf3ea8cf2010-11-14 08:17:51 +00005167/// Prepares for a scalar cast, performing all the necessary stages
5168/// except the final cast and returning the kind required.
John McCalla180f042011-10-06 23:25:11 +00005169CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005170 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5171 // Also, callers should have filtered out the invalid cases with
5172 // pointers. Everything else should be possible.
5173
John Wiegley429bb272011-04-08 18:41:53 +00005174 QualType SrcTy = Src.get()->getType();
John McCalla180f042011-10-06 23:25:11 +00005175 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005176 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005177
John McCall1d9b3b22011-09-09 05:25:32 +00005178 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005179 case Type::STK_MemberPointer:
5180 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005181
John McCall1d9b3b22011-09-09 05:25:32 +00005182 case Type::STK_CPointer:
5183 case Type::STK_BlockPointer:
5184 case Type::STK_ObjCObjectPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00005185 switch (DestTy->getScalarTypeKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005186 case Type::STK_CPointer: {
5187 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5188 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5189 if (SrcAS != DestAS)
5190 return CK_AddressSpaceConversion;
John McCall1d9b3b22011-09-09 05:25:32 +00005191 return CK_BitCast;
Stephen Hines651f13c2014-04-23 16:59:28 -07005192 }
John McCall1d9b3b22011-09-09 05:25:32 +00005193 case Type::STK_BlockPointer:
5194 return (SrcKind == Type::STK_BlockPointer
5195 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5196 case Type::STK_ObjCObjectPointer:
5197 if (SrcKind == Type::STK_ObjCObjectPointer)
5198 return CK_BitCast;
David Blaikie7530c032012-01-17 06:56:22 +00005199 if (SrcKind == Type::STK_CPointer)
John McCall1d9b3b22011-09-09 05:25:32 +00005200 return CK_CPointerToObjCPointerCast;
David Blaikie7530c032012-01-17 06:56:22 +00005201 maybeExtendBlockObject(*this, Src);
5202 return CK_BlockPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005203 case Type::STK_Bool:
5204 return CK_PointerToBoolean;
5205 case Type::STK_Integral:
5206 return CK_PointerToIntegral;
5207 case Type::STK_Floating:
5208 case Type::STK_FloatingComplex:
5209 case Type::STK_IntegralComplex:
5210 case Type::STK_MemberPointer:
5211 llvm_unreachable("illegal cast from pointer");
5212 }
David Blaikie7530c032012-01-17 06:56:22 +00005213 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005214
John McCalldaa8e4e2010-11-15 09:13:47 +00005215 case Type::STK_Bool: // casting from bool is like casting from an integer
5216 case Type::STK_Integral:
5217 switch (DestTy->getScalarTypeKind()) {
John McCall1d9b3b22011-09-09 05:25:32 +00005218 case Type::STK_CPointer:
5219 case Type::STK_ObjCObjectPointer:
5220 case Type::STK_BlockPointer:
John McCalla180f042011-10-06 23:25:11 +00005221 if (Src.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005222 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005223 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005224 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005225 case Type::STK_Bool:
5226 return CK_IntegralToBoolean;
5227 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005228 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005229 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005230 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005231 case Type::STK_IntegralComplex:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005232 Src = ImpCastExprToType(Src.get(),
John McCalla180f042011-10-06 23:25:11 +00005233 DestTy->castAs<ComplexType>()->getElementType(),
5234 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005235 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005236 case Type::STK_FloatingComplex:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005237 Src = ImpCastExprToType(Src.get(),
John McCalla180f042011-10-06 23:25:11 +00005238 DestTy->castAs<ComplexType>()->getElementType(),
5239 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005240 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005241 case Type::STK_MemberPointer:
5242 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005243 }
David Blaikie7530c032012-01-17 06:56:22 +00005244 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005245
John McCalldaa8e4e2010-11-15 09:13:47 +00005246 case Type::STK_Floating:
5247 switch (DestTy->getScalarTypeKind()) {
5248 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005249 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005250 case Type::STK_Bool:
5251 return CK_FloatingToBoolean;
5252 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005253 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005254 case Type::STK_FloatingComplex:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005255 Src = ImpCastExprToType(Src.get(),
John McCalla180f042011-10-06 23:25:11 +00005256 DestTy->castAs<ComplexType>()->getElementType(),
5257 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005258 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005259 case Type::STK_IntegralComplex:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005260 Src = ImpCastExprToType(Src.get(),
John McCalla180f042011-10-06 23:25:11 +00005261 DestTy->castAs<ComplexType>()->getElementType(),
5262 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005263 return CK_IntegralRealToComplex;
John McCall1d9b3b22011-09-09 05:25:32 +00005264 case Type::STK_CPointer:
5265 case Type::STK_ObjCObjectPointer:
5266 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00005267 llvm_unreachable("valid float->pointer cast?");
5268 case Type::STK_MemberPointer:
5269 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005270 }
David Blaikie7530c032012-01-17 06:56:22 +00005271 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00005272
John McCalldaa8e4e2010-11-15 09:13:47 +00005273 case Type::STK_FloatingComplex:
5274 switch (DestTy->getScalarTypeKind()) {
5275 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005276 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005277 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005278 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005279 case Type::STK_Floating: {
John McCalla180f042011-10-06 23:25:11 +00005280 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5281 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00005282 return CK_FloatingComplexToReal;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005283 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005284 return CK_FloatingCast;
5285 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005286 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005287 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005288 case Type::STK_Integral:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005289 Src = ImpCastExprToType(Src.get(),
John McCalla180f042011-10-06 23:25:11 +00005290 SrcTy->castAs<ComplexType>()->getElementType(),
5291 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005292 return CK_FloatingToIntegral;
John McCall1d9b3b22011-09-09 05:25:32 +00005293 case Type::STK_CPointer:
5294 case Type::STK_ObjCObjectPointer:
5295 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00005296 llvm_unreachable("valid complex float->pointer cast?");
5297 case Type::STK_MemberPointer:
5298 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005299 }
David Blaikie7530c032012-01-17 06:56:22 +00005300 llvm_unreachable("Should have returned before this");
John McCallf3ea8cf2010-11-14 08:17:51 +00005301
John McCalldaa8e4e2010-11-15 09:13:47 +00005302 case Type::STK_IntegralComplex:
5303 switch (DestTy->getScalarTypeKind()) {
5304 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005305 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005306 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005307 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005308 case Type::STK_Integral: {
John McCalla180f042011-10-06 23:25:11 +00005309 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5310 if (Context.hasSameType(ET, DestTy))
John McCall8786da72010-12-14 17:51:41 +00005311 return CK_IntegralComplexToReal;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005312 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005313 return CK_IntegralCast;
5314 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005315 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005316 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005317 case Type::STK_Floating:
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005318 Src = ImpCastExprToType(Src.get(),
John McCalla180f042011-10-06 23:25:11 +00005319 SrcTy->castAs<ComplexType>()->getElementType(),
5320 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005321 return CK_IntegralToFloating;
John McCall1d9b3b22011-09-09 05:25:32 +00005322 case Type::STK_CPointer:
5323 case Type::STK_ObjCObjectPointer:
5324 case Type::STK_BlockPointer:
John McCalldaa8e4e2010-11-15 09:13:47 +00005325 llvm_unreachable("valid complex int->pointer cast?");
5326 case Type::STK_MemberPointer:
5327 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005328 }
David Blaikie7530c032012-01-17 06:56:22 +00005329 llvm_unreachable("Should have returned before this");
Anders Carlsson82debc72009-10-18 18:12:03 +00005330 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005331
John McCallf3ea8cf2010-11-14 08:17:51 +00005332 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson82debc72009-10-18 18:12:03 +00005333}
5334
Stephen Hines651f13c2014-04-23 16:59:28 -07005335static bool breakDownVectorType(QualType type, uint64_t &len,
5336 QualType &eltType) {
5337 // Vectors are simple.
5338 if (const VectorType *vecType = type->getAs<VectorType>()) {
5339 len = vecType->getNumElements();
5340 eltType = vecType->getElementType();
5341 assert(eltType->isScalarType());
5342 return true;
5343 }
5344
5345 // We allow lax conversion to and from non-vector types, but only if
5346 // they're real types (i.e. non-complex, non-pointer scalar types).
5347 if (!type->isRealType()) return false;
5348
5349 len = 1;
5350 eltType = type;
5351 return true;
5352}
5353
5354static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5355 uint64_t srcLen, destLen;
5356 QualType srcElt, destElt;
5357 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5358 if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5359
5360 // ASTContext::getTypeSize will return the size rounded up to a
5361 // power of 2, so instead of using that, we need to use the raw
5362 // element size multiplied by the element count.
5363 uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5364 uint64_t destEltSize = S.Context.getTypeSize(destElt);
5365
5366 return (srcLen * srcEltSize == destLen * destEltSize);
5367}
5368
5369/// Is this a legal conversion between two known vector types?
5370bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5371 assert(destTy->isVectorType() || srcTy->isVectorType());
5372
5373 if (!Context.getLangOpts().LaxVectorConversions)
5374 return false;
5375 return VectorTypesMatch(*this, srcTy, destTy);
5376}
5377
Anders Carlssonc3516322009-10-16 02:48:28 +00005378bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005379 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005380 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005381
Anders Carlssona64db8f2007-11-27 05:51:55 +00005382 if (Ty->isVectorType() || Ty->isIntegerType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005383 if (!VectorTypesMatch(*this, Ty, VectorTy))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005384 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005385 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005386 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005387 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005388 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005389 } else
5390 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005391 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005392 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005393
John McCall2de56d12010-08-25 11:45:40 +00005394 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005395 return false;
5396}
5397
John Wiegley429bb272011-04-08 18:41:53 +00005398ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5399 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005400 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005401
Anders Carlsson16a89042009-10-16 05:23:41 +00005402 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005403
Nate Begeman9b10da62009-06-27 22:05:55 +00005404 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5405 // an ExtVectorType.
Tobias Grosser9df05ea2011-09-22 13:03:14 +00005406 // In OpenCL, casts between vectors of different types are not allowed.
5407 // (See OpenCL 6.2).
Nate Begeman58d29a42009-06-26 00:50:28 +00005408 if (SrcTy->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005409 if (!VectorTypesMatch(*this, SrcTy, DestTy)
David Blaikie4e4d0842012-03-11 07:00:24 +00005410 || (getLangOpts().OpenCL &&
Tobias Grosser9df05ea2011-09-22 13:03:14 +00005411 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00005412 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005413 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005414 return ExprError();
5415 }
John McCall2de56d12010-08-25 11:45:40 +00005416 Kind = CK_BitCast;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005417 return CastExpr;
Nate Begeman58d29a42009-06-26 00:50:28 +00005418 }
5419
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005420 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005421 // conversion will take place first from scalar to elt type, and then
5422 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005423 if (SrcTy->isPointerType())
5424 return Diag(R.getBegin(),
5425 diag::err_invalid_conversion_between_vector_and_scalar)
5426 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005427
5428 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005429 ExprResult CastExprRes = CastExpr;
John McCalla180f042011-10-06 23:25:11 +00005430 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley429bb272011-04-08 18:41:53 +00005431 if (CastExprRes.isInvalid())
5432 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005433 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005434
John McCall2de56d12010-08-25 11:45:40 +00005435 Kind = CK_VectorSplat;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005436 return CastExpr;
Nate Begeman58d29a42009-06-26 00:50:28 +00005437}
5438
John McCall60d7b3a2010-08-24 06:29:42 +00005439ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00005440Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5441 Declarator &D, ParsedType &Ty,
Richard Trieuccd891a2011-09-09 01:45:06 +00005442 SourceLocation RParenLoc, Expr *CastExpr) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005443 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005444 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005445
Richard Trieuccd891a2011-09-09 01:45:06 +00005446 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00005447 if (D.isInvalidType())
5448 return ExprError();
5449
David Blaikie4e4d0842012-03-11 07:00:24 +00005450 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00005451 // Check that there are no default arguments (C++ only).
5452 CheckExtraCXXDefaultArguments(D);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005453 } else {
5454 // Make sure any TypoExprs have been dealt with.
5455 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5456 if (!Res.isUsable())
5457 return ExprError();
5458 CastExpr = Res.get();
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00005459 }
5460
John McCalle82247a2011-10-01 05:17:03 +00005461 checkUnusedDeclAttributes(D);
5462
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00005463 QualType castType = castTInfo->getType();
5464 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00005465
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005466 bool isVectorLiteral = false;
5467
5468 // Check for an altivec or OpenCL literal,
5469 // i.e. all the elements are integer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00005470 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5471 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikie4e4d0842012-03-11 07:00:24 +00005472 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser37c31c22011-09-21 18:28:29 +00005473 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005474 if (PLE && PLE->getNumExprs() == 0) {
5475 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5476 return ExprError();
5477 }
5478 if (PE || PLE->getNumExprs() == 1) {
5479 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5480 if (!E->getType()->isVectorType())
5481 isVectorLiteral = true;
5482 }
5483 else
5484 isVectorLiteral = true;
5485 }
5486
5487 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5488 // then handle it as such.
5489 if (isVectorLiteral)
Richard Trieuccd891a2011-09-09 01:45:06 +00005490 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005491
Nate Begeman2ef13e52009-08-10 23:49:36 +00005492 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005493 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5494 // sequence of BinOp comma operators.
Richard Trieuccd891a2011-09-09 01:45:06 +00005495 if (isa<ParenListExpr>(CastExpr)) {
5496 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005497 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005498 CastExpr = Result.get();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005499 }
John McCallb042fdf2010-01-15 18:56:44 +00005500
Stephen Hines651f13c2014-04-23 16:59:28 -07005501 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5502 !getSourceManager().isInSystemMacro(LParenLoc))
5503 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005504
5505 CheckTollFreeBridgeCast(castType, CastExpr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005506
5507 CheckObjCBridgeRelatedCast(castType, CastExpr);
5508
Richard Trieuccd891a2011-09-09 01:45:06 +00005509 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005510}
5511
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005512ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5513 SourceLocation RParenLoc, Expr *E,
5514 TypeSourceInfo *TInfo) {
5515 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5516 "Expected paren or paren list expression");
5517
5518 Expr **exprs;
5519 unsigned numExprs;
5520 Expr *subExpr;
Richard Smithafbcab82013-02-05 05:55:57 +00005521 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005522 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
Richard Smithafbcab82013-02-05 05:55:57 +00005523 LiteralLParenLoc = PE->getLParenLoc();
5524 LiteralRParenLoc = PE->getRParenLoc();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005525 exprs = PE->getExprs();
5526 numExprs = PE->getNumExprs();
Richard Smithafbcab82013-02-05 05:55:57 +00005527 } else { // isa<ParenExpr> by assertion at function entrance
5528 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5529 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005530 subExpr = cast<ParenExpr>(E)->getSubExpr();
5531 exprs = &subExpr;
5532 numExprs = 1;
5533 }
5534
5535 QualType Ty = TInfo->getType();
5536 assert(Ty->isVectorType() && "Expected vector type");
5537
Chris Lattner5f9e2722011-07-23 10:55:15 +00005538 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00005539 const VectorType *VTy = Ty->getAs<VectorType>();
5540 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5541
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005542 // '(...)' form of vector initialization in AltiVec: the number of
5543 // initializers must be one or must match the size of the vector.
5544 // If a single value is specified in the initializer then it will be
5545 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00005546 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005547 // The number of initializers must be one or must match the size of the
5548 // vector. If a single value is specified in the initializer then it will
5549 // be replicated to all the components of the vector
5550 if (numExprs == 1) {
5551 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00005552 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5553 if (Literal.isInvalid())
5554 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005555 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00005556 PrepareScalarCast(Literal, ElemTy));
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005557 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005558 }
5559 else if (numExprs < numElems) {
5560 Diag(E->getExprLoc(),
5561 diag::err_incorrect_number_of_vector_initializers);
5562 return ExprError();
5563 }
5564 else
Benjamin Kramer14c59822012-02-14 12:06:21 +00005565 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005566 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00005567 else {
5568 // For OpenCL, when the number of initializers is a single value,
5569 // it will be replicated to all components of the vector.
David Blaikie4e4d0842012-03-11 07:00:24 +00005570 if (getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +00005571 VTy->getVectorKind() == VectorType::GenericVector &&
5572 numExprs == 1) {
5573 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith61ffd092011-10-27 23:31:58 +00005574 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5575 if (Literal.isInvalid())
5576 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005577 Literal = ImpCastExprToType(Literal.get(), ElemTy,
John McCalla180f042011-10-06 23:25:11 +00005578 PrepareScalarCast(Literal, ElemTy));
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005579 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
Tanya Lattner61b4bc82011-07-15 23:07:01 +00005580 }
5581
Benjamin Kramer14c59822012-02-14 12:06:21 +00005582 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00005583 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005584 // FIXME: This means that pretty-printing the final AST will produce curly
5585 // braces instead of the original commas.
Richard Smithafbcab82013-02-05 05:55:57 +00005586 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5587 initExprs, LiteralRParenLoc);
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00005588 initE->setType(Ty);
5589 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5590}
5591
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005592/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5593/// the ParenListExpr into a sequence of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005594ExprResult
Richard Trieuccd891a2011-09-09 01:45:06 +00005595Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5596 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005597 if (!E)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005598 return OrigExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00005599
John McCall60d7b3a2010-08-24 06:29:42 +00005600 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005601
Nate Begeman2ef13e52009-08-10 23:49:36 +00005602 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005603 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5604 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005605
John McCall9ae2f072010-08-23 23:25:46 +00005606 if (Result.isInvalid()) return ExprError();
5607
5608 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005609}
5610
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005611ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5612 SourceLocation R,
5613 MultiExprArg Val) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005614 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005615 return expr;
Nate Begeman2ef13e52009-08-10 23:49:36 +00005616}
5617
Chandler Carruth82214a82011-02-18 23:54:50 +00005618/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu26f96072011-09-02 01:51:02 +00005619/// constant and the other is not a pointer. Returns true if a diagnostic is
5620/// emitted.
Richard Trieu33fc7572011-09-06 20:06:39 +00005621bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth82214a82011-02-18 23:54:50 +00005622 SourceLocation QuestionLoc) {
Richard Trieu33fc7572011-09-06 20:06:39 +00005623 Expr *NullExpr = LHSExpr;
5624 Expr *NonPointerExpr = RHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00005625 Expr::NullPointerConstantKind NullKind =
5626 NullExpr->isNullPointerConstant(Context,
5627 Expr::NPC_ValueDependentIsNotNull);
5628
5629 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieu33fc7572011-09-06 20:06:39 +00005630 NullExpr = RHSExpr;
5631 NonPointerExpr = LHSExpr;
Chandler Carruth82214a82011-02-18 23:54:50 +00005632 NullKind =
5633 NullExpr->isNullPointerConstant(Context,
5634 Expr::NPC_ValueDependentIsNotNull);
5635 }
5636
5637 if (NullKind == Expr::NPCK_NotNull)
5638 return false;
5639
David Blaikie50800fc2012-08-08 17:33:31 +00005640 if (NullKind == Expr::NPCK_ZeroExpression)
5641 return false;
5642
5643 if (NullKind == Expr::NPCK_ZeroLiteral) {
Chandler Carruth82214a82011-02-18 23:54:50 +00005644 // In this case, check to make sure that we got here from a "NULL"
5645 // string in the source code.
5646 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005647 SourceLocation loc = NullExpr->getExprLoc();
5648 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005649 return false;
5650 }
5651
Richard Smith4e24f0f2013-01-02 12:01:23 +00005652 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
Chandler Carruth82214a82011-02-18 23:54:50 +00005653 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5654 << NonPointerExpr->getType() << DiagType
5655 << NonPointerExpr->getSourceRange();
5656 return true;
5657}
5658
Richard Trieu26f96072011-09-02 01:51:02 +00005659/// \brief Return false if the condition expression is valid, true otherwise.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005660static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
Richard Trieu26f96072011-09-02 01:51:02 +00005661 QualType CondTy = Cond->getType();
5662
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005663 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5664 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5665 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5666 << CondTy << Cond->getSourceRange();
5667 return true;
5668 }
5669
Richard Trieu26f96072011-09-02 01:51:02 +00005670 // C99 6.5.15p2
5671 if (CondTy->isScalarType()) return false;
5672
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005673 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5674 << CondTy << Cond->getSourceRange();
Richard Trieu26f96072011-09-02 01:51:02 +00005675 return true;
5676}
5677
Richard Trieu26f96072011-09-02 01:51:02 +00005678/// \brief Handle when one or both operands are void type.
5679static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5680 ExprResult &RHS) {
5681 Expr *LHSExpr = LHS.get();
5682 Expr *RHSExpr = RHS.get();
5683
5684 if (!LHSExpr->getType()->isVoidType())
5685 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5686 << RHSExpr->getSourceRange();
5687 if (!RHSExpr->getType()->isVoidType())
5688 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5689 << LHSExpr->getSourceRange();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005690 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5691 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
Richard Trieu26f96072011-09-02 01:51:02 +00005692 return S.Context.VoidTy;
5693}
5694
5695/// \brief Return false if the NullExpr can be promoted to PointerTy,
5696/// true otherwise.
5697static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5698 QualType PointerTy) {
5699 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5700 !NullExpr.get()->isNullPointerConstant(S.Context,
5701 Expr::NPC_ValueDependentIsNull))
5702 return true;
5703
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005704 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
Richard Trieu26f96072011-09-02 01:51:02 +00005705 return false;
5706}
5707
5708/// \brief Checks compatibility between two pointers and return the resulting
5709/// type.
5710static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5711 ExprResult &RHS,
5712 SourceLocation Loc) {
5713 QualType LHSTy = LHS.get()->getType();
5714 QualType RHSTy = RHS.get()->getType();
5715
5716 if (S.Context.hasSameType(LHSTy, RHSTy)) {
5717 // Two identical pointers types are always compatible.
5718 return LHSTy;
5719 }
5720
5721 QualType lhptee, rhptee;
5722
5723 // Get the pointee types.
Fariborz Jahanianb165fdd2013-06-07 16:07:38 +00005724 bool IsBlockPointer = false;
John McCall1d9b3b22011-09-09 05:25:32 +00005725 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5726 lhptee = LHSBTy->getPointeeType();
5727 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb165fdd2013-06-07 16:07:38 +00005728 IsBlockPointer = true;
Richard Trieu26f96072011-09-02 01:51:02 +00005729 } else {
John McCall1d9b3b22011-09-09 05:25:32 +00005730 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5731 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu26f96072011-09-02 01:51:02 +00005732 }
5733
Eli Friedmanae916a12012-04-05 22:30:04 +00005734 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5735 // differently qualified versions of compatible types, the result type is
5736 // a pointer to an appropriately qualified version of the composite
5737 // type.
5738
5739 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5740 // clause doesn't make sense for our extensions. E.g. address space 2 should
5741 // be incompatible with address space 3: they may live on different devices or
5742 // anything.
5743 Qualifiers lhQual = lhptee.getQualifiers();
5744 Qualifiers rhQual = rhptee.getQualifiers();
5745
5746 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5747 lhQual.removeCVRQualifiers();
5748 rhQual.removeCVRQualifiers();
5749
5750 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5751 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5752
5753 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5754
5755 if (CompositeTy.isNull()) {
Stephen Hines176edba2014-12-01 14:53:08 -08005756 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
Richard Trieu26f96072011-09-02 01:51:02 +00005757 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5758 << RHS.get()->getSourceRange();
5759 // In this situation, we assume void* type. No especially good
5760 // reason, but this is what gcc does, and we do have to pick
5761 // to get a consistent AST.
5762 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005763 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5764 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
Richard Trieu26f96072011-09-02 01:51:02 +00005765 return incompatTy;
5766 }
5767
5768 // The pointer types are compatible.
Eli Friedmanae916a12012-04-05 22:30:04 +00005769 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
Fariborz Jahanianb165fdd2013-06-07 16:07:38 +00005770 if (IsBlockPointer)
Fariborz Jahanian75236062013-06-07 00:48:14 +00005771 ResultTy = S.Context.getBlockPointerType(ResultTy);
5772 else
5773 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu26f96072011-09-02 01:51:02 +00005774
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005775 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5776 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
Eli Friedmanae916a12012-04-05 22:30:04 +00005777 return ResultTy;
Richard Trieu26f96072011-09-02 01:51:02 +00005778}
5779
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005780/// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5781/// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5782/// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5783static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5784 if (QT->isObjCIdType())
5785 return true;
5786
5787 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5788 if (!OPT)
5789 return false;
5790
5791 if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5792 if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5793 return false;
5794
5795 ObjCProtocolDecl* PNSCopying =
5796 S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5797 ObjCProtocolDecl* PNSObject =
5798 S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5799
5800 for (auto *Proto : OPT->quals()) {
5801 if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5802 (PNSObject && declaresSameEntity(Proto, PNSObject)))
5803 ;
5804 else
5805 return false;
5806 }
5807 return true;
5808}
5809
Richard Trieu26f96072011-09-02 01:51:02 +00005810/// \brief Return the resulting type when the operands are both block pointers.
5811static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5812 ExprResult &LHS,
5813 ExprResult &RHS,
5814 SourceLocation Loc) {
5815 QualType LHSTy = LHS.get()->getType();
5816 QualType RHSTy = RHS.get()->getType();
5817
5818 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5819 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5820 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005821 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5822 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu26f96072011-09-02 01:51:02 +00005823 return destType;
5824 }
5825 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5826 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5827 << RHS.get()->getSourceRange();
5828 return QualType();
5829 }
5830
5831 // We have 2 block pointer types.
5832 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5833}
5834
5835/// \brief Return the resulting type when the operands are both pointers.
5836static QualType
5837checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5838 ExprResult &RHS,
5839 SourceLocation Loc) {
5840 // get the pointer types
5841 QualType LHSTy = LHS.get()->getType();
5842 QualType RHSTy = RHS.get()->getType();
5843
5844 // get the "pointed to" types
5845 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5846 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5847
5848 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5849 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5850 // Figure out necessary qualifiers (C99 6.5.15p6)
5851 QualType destPointee
5852 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5853 QualType destType = S.Context.getPointerType(destPointee);
5854 // Add qualifiers if necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005855 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Richard Trieu26f96072011-09-02 01:51:02 +00005856 // Promote to void*.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005857 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Richard Trieu26f96072011-09-02 01:51:02 +00005858 return destType;
5859 }
5860 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5861 QualType destPointee
5862 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5863 QualType destType = S.Context.getPointerType(destPointee);
5864 // Add qualifiers if necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005865 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Richard Trieu26f96072011-09-02 01:51:02 +00005866 // Promote to void*.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005867 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Richard Trieu26f96072011-09-02 01:51:02 +00005868 return destType;
5869 }
5870
5871 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5872}
5873
5874/// \brief Return false if the first expression is not an integer and the second
5875/// expression is not a pointer, true otherwise.
5876static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5877 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00005878 bool IsIntFirstExpr) {
Richard Trieu26f96072011-09-02 01:51:02 +00005879 if (!PointerExpr->getType()->isPointerType() ||
5880 !Int.get()->getType()->isIntegerType())
5881 return false;
5882
Richard Trieuccd891a2011-09-09 01:45:06 +00005883 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5884 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu26f96072011-09-02 01:51:02 +00005885
Stephen Hines176edba2014-12-01 14:53:08 -08005886 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
Richard Trieu26f96072011-09-02 01:51:02 +00005887 << Expr1->getType() << Expr2->getType()
5888 << Expr1->getSourceRange() << Expr2->getSourceRange();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005889 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
Richard Trieu26f96072011-09-02 01:51:02 +00005890 CK_IntegralToPointer);
5891 return true;
5892}
5893
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005894/// \brief Simple conversion between integer and floating point types.
5895///
5896/// Used when handling the OpenCL conditional operator where the
5897/// condition is a vector while the other operands are scalar.
5898///
5899/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
5900/// types are either integer or floating type. Between the two
5901/// operands, the type with the higher rank is defined as the "result
5902/// type". The other operand needs to be promoted to the same type. No
5903/// other type promotion is allowed. We cannot use
5904/// UsualArithmeticConversions() for this purpose, since it always
5905/// promotes promotable types.
5906static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
5907 ExprResult &RHS,
5908 SourceLocation QuestionLoc) {
5909 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
5910 if (LHS.isInvalid())
5911 return QualType();
5912 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
5913 if (RHS.isInvalid())
5914 return QualType();
5915
5916 // For conversion purposes, we ignore any qualifiers.
5917 // For example, "const float" and "float" are equivalent.
5918 QualType LHSType =
5919 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5920 QualType RHSType =
5921 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5922
5923 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
5924 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
5925 << LHSType << LHS.get()->getSourceRange();
5926 return QualType();
5927 }
5928
5929 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
5930 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
5931 << RHSType << RHS.get()->getSourceRange();
5932 return QualType();
5933 }
5934
5935 // If both types are identical, no conversion is needed.
5936 if (LHSType == RHSType)
5937 return LHSType;
5938
5939 // Now handle "real" floating types (i.e. float, double, long double).
5940 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
5941 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
5942 /*IsCompAssign = */ false);
5943
5944 // Finally, we have two differing integer types.
5945 return handleIntegerConversion<doIntegralCast, doIntegralCast>
5946 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
5947}
5948
5949/// \brief Convert scalar operands to a vector that matches the
5950/// condition in length.
5951///
5952/// Used when handling the OpenCL conditional operator where the
5953/// condition is a vector while the other operands are scalar.
5954///
5955/// We first compute the "result type" for the scalar operands
5956/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
5957/// into a vector of that type where the length matches the condition
5958/// vector type. s6.11.6 requires that the element types of the result
5959/// and the condition must have the same number of bits.
5960static QualType
5961OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
5962 QualType CondTy, SourceLocation QuestionLoc) {
5963 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
5964 if (ResTy.isNull()) return QualType();
5965
5966 const VectorType *CV = CondTy->getAs<VectorType>();
5967 assert(CV);
5968
5969 // Determine the vector result type
5970 unsigned NumElements = CV->getNumElements();
5971 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
5972
5973 // Ensure that all types have the same number of bits
5974 if (S.Context.getTypeSize(CV->getElementType())
5975 != S.Context.getTypeSize(ResTy)) {
5976 // Since VectorTy is created internally, it does not pretty print
5977 // with an OpenCL name. Instead, we just print a description.
5978 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
5979 SmallString<64> Str;
5980 llvm::raw_svector_ostream OS(Str);
5981 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
5982 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
5983 << CondTy << OS.str();
5984 return QualType();
5985 }
5986
5987 // Convert operands to the vector result type
5988 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
5989 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
5990
5991 return VectorTy;
5992}
5993
5994/// \brief Return false if this is a valid OpenCL condition vector
5995static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
5996 SourceLocation QuestionLoc) {
5997 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
5998 // integral type.
5999 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6000 assert(CondTy);
6001 QualType EleTy = CondTy->getElementType();
6002 if (EleTy->isIntegerType()) return false;
6003
6004 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6005 << Cond->getType() << Cond->getSourceRange();
6006 return true;
6007}
6008
6009/// \brief Return false if the vector condition type and the vector
6010/// result type are compatible.
6011///
6012/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6013/// number of elements, and their element types have the same number
6014/// of bits.
6015static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6016 SourceLocation QuestionLoc) {
6017 const VectorType *CV = CondTy->getAs<VectorType>();
6018 const VectorType *RV = VecResTy->getAs<VectorType>();
6019 assert(CV && RV);
6020
6021 if (CV->getNumElements() != RV->getNumElements()) {
6022 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6023 << CondTy << VecResTy;
6024 return true;
6025 }
6026
6027 QualType CVE = CV->getElementType();
6028 QualType RVE = RV->getElementType();
6029
6030 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6031 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6032 << CondTy << VecResTy;
6033 return true;
6034 }
6035
6036 return false;
6037}
6038
6039/// \brief Return the resulting type for the conditional operator in
6040/// OpenCL (aka "ternary selection operator", OpenCL v1.1
6041/// s6.3.i) when the condition is a vector type.
6042static QualType
6043OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6044 ExprResult &LHS, ExprResult &RHS,
6045 SourceLocation QuestionLoc) {
6046 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6047 if (Cond.isInvalid())
6048 return QualType();
6049 QualType CondTy = Cond.get()->getType();
6050
6051 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6052 return QualType();
6053
6054 // If either operand is a vector then find the vector type of the
6055 // result as specified in OpenCL v1.1 s6.3.i.
6056 if (LHS.get()->getType()->isVectorType() ||
6057 RHS.get()->getType()->isVectorType()) {
6058 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6059 /*isCompAssign*/false);
6060 if (VecResTy.isNull()) return QualType();
6061 // The result type must match the condition type as specified in
6062 // OpenCL v1.1 s6.11.6.
6063 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6064 return QualType();
6065 return VecResTy;
6066 }
6067
6068 // Both operands are scalar.
6069 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6070}
6071
Richard Trieu33fc7572011-09-06 20:06:39 +00006072/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6073/// In that case, LHS = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00006074/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00006075QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6076 ExprResult &RHS, ExprValueKind &VK,
6077 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00006078 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006079
Richard Trieu33fc7572011-09-06 20:06:39 +00006080 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6081 if (!LHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006082 LHS = LHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00006083
Richard Trieu33fc7572011-09-06 20:06:39 +00006084 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6085 if (!RHSResult.isUsable()) return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006086 RHS = RHSResult;
Douglas Gregor7ad5d422010-11-09 21:07:58 +00006087
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006088 // C++ is sufficiently different to merit its own checker.
David Blaikie4e4d0842012-03-11 07:00:24 +00006089 if (getLangOpts().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00006090 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00006091
6092 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006093 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006094
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006095 // The OpenCL operator with a vector condition is sufficiently
6096 // different to merit its own checker.
6097 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6098 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6099
Jin-Gu Kangbb0b6142013-09-02 20:32:37 +00006100 // First, check the condition.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006101 Cond = UsualUnaryConversions(Cond.get());
John Wiegley429bb272011-04-08 18:41:53 +00006102 if (Cond.isInvalid())
6103 return QualType();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006104 if (checkCondition(*this, Cond.get(), QuestionLoc))
Jin-Gu Kangbb0b6142013-09-02 20:32:37 +00006105 return QualType();
6106
6107 // Now check the two expressions.
6108 if (LHS.get()->getType()->isVectorType() ||
6109 RHS.get()->getType()->isVectorType())
6110 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
6111
Stephen Hines176edba2014-12-01 14:53:08 -08006112 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
Eli Friedman09bddcf2013-07-08 20:20:06 +00006113 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00006114 return QualType();
6115
John Wiegley429bb272011-04-08 18:41:53 +00006116 QualType LHSTy = LHS.get()->getType();
6117 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006118
Chris Lattner70d67a92008-01-06 22:42:25 +00006119 // If both operands have arithmetic type, do the usual arithmetic conversions
6120 // to find a common type: C99 6.5.15p3,5.
Stephen Hines176edba2014-12-01 14:53:08 -08006121 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6122 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6123 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6124
6125 return ResTy;
6126 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006127
Chris Lattner70d67a92008-01-06 22:42:25 +00006128 // If both operands are the same structure or union type, the result is that
6129 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006130 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6131 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00006132 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00006133 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00006134 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006135 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006136 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00006137 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006138
Chris Lattner70d67a92008-01-06 22:42:25 +00006139 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00006140 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006141 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu26f96072011-09-02 01:51:02 +00006142 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffe701c0a2008-05-12 21:44:38 +00006143 }
Richard Trieu26f96072011-09-02 01:51:02 +00006144
Steve Naroffb6d54e52008-01-08 01:11:38 +00006145 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6146 // the type of the other operand."
Richard Trieu26f96072011-09-02 01:51:02 +00006147 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6148 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006149
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006150 // All objective-c pointer type analysis is done here.
6151 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6152 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006153 if (LHS.isInvalid() || RHS.isInvalid())
6154 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006155 if (!compositeType.isNull())
6156 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006157
6158
Steve Naroff7154a772009-07-01 14:36:47 +00006159 // Handle block pointer types.
Richard Trieu26f96072011-09-02 01:51:02 +00006160 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6161 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6162 QuestionLoc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006163
Steve Naroff7154a772009-07-01 14:36:47 +00006164 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu26f96072011-09-02 01:51:02 +00006165 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6166 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6167 QuestionLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00006168
John McCall404cd162010-11-13 01:35:44 +00006169 // GCC compatibility: soften pointer/integer mismatch. Note that
6170 // null pointers have been filtered out by this point.
Richard Trieu26f96072011-09-02 01:51:02 +00006171 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6172 /*isIntFirstExpr=*/true))
Steve Naroff7154a772009-07-01 14:36:47 +00006173 return RHSTy;
Richard Trieu26f96072011-09-02 01:51:02 +00006174 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6175 /*isIntFirstExpr=*/false))
Steve Naroff7154a772009-07-01 14:36:47 +00006176 return LHSTy;
Daniel Dunbar5e155f02008-09-11 23:12:46 +00006177
Chandler Carruth82214a82011-02-18 23:54:50 +00006178 // Emit a better diagnostic if one of the expressions is a null pointer
6179 // constant and the other is not a pointer type. In this case, the user most
6180 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00006181 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00006182 return QualType();
6183
Chris Lattner70d67a92008-01-06 22:42:25 +00006184 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006185 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00006186 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6187 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006188 return QualType();
6189}
6190
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006191/// FindCompositeObjCPointerType - Helper method to find composite type of
6192/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00006193QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00006194 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00006195 QualType LHSTy = LHS.get()->getType();
6196 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006197
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006198 // Handle things like Class and struct objc_class*. Here we case the result
6199 // to the pseudo-builtin, because that will be implicitly cast back to the
6200 // redefinition type if an attempt is made to access its fields.
6201 if (LHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006202 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006203 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006204 return LHSTy;
6205 }
6206 if (RHSTy->isObjCClassType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006207 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006208 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006209 return RHSTy;
6210 }
6211 // And the same for struct objc_object* / id
6212 if (LHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006213 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006214 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006215 return LHSTy;
6216 }
6217 if (RHSTy->isObjCIdType() &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006218 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006219 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006220 return RHSTy;
6221 }
6222 // And the same for struct objc_selector* / SEL
6223 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006224 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006225 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006226 return LHSTy;
6227 }
6228 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006229 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006230 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006231 return RHSTy;
6232 }
6233 // Check constraints for Objective-C object pointers types.
6234 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006235
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006236 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6237 // Two identical object pointer types are always compatible.
6238 return LHSTy;
6239 }
John McCall1d9b3b22011-09-09 05:25:32 +00006240 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6241 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006242 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006243
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006244 // If both operands are interfaces and either operand can be
6245 // assigned to the other, use that type as the composite
6246 // type. This allows
6247 // xxx ? (A*) a : (B*) b
6248 // where B is a subclass of A.
6249 //
6250 // Additionally, as for assignment, if either type is 'id'
6251 // allow silent coercion. Finally, if the types are
6252 // incompatible then make sure to use 'id' as the composite
6253 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006254
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006255 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6256 // It could return the composite type.
6257 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6258 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6259 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6260 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6261 } else if ((LHSTy->isObjCQualifiedIdType() ||
6262 RHSTy->isObjCQualifiedIdType()) &&
6263 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6264 // Need to handle "id<xx>" explicitly.
6265 // GCC allows qualified id and any Objective-C type to devolve to
6266 // id. Currently localizing to here until clear this should be
6267 // part of ObjCQualifiedIdTypesAreCompatible.
6268 compositeType = Context.getObjCIdType();
6269 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6270 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006271 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006272 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6273 ;
6274 else {
6275 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6276 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006278 QualType incompatTy = Context.getObjCIdType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006279 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6280 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006281 return incompatTy;
6282 }
6283 // The object pointer types are compatible.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006284 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6285 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006286 return compositeType;
6287 }
6288 // Check Objective-C object pointer types and 'void *'
6289 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006290 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00006291 // ARC forbids the implicit conversion of object pointers to 'void *',
6292 // so these types are not compatible.
6293 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6295 LHS = RHS = true;
6296 return QualType();
6297 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006298 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6299 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6300 QualType destPointee
6301 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6302 QualType destType = Context.getPointerType(destPointee);
6303 // Add qualifiers if necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006304 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006305 // Promote to void*.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006306 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006307 return destType;
6308 }
6309 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006310 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedmana66eccb2012-02-25 00:23:44 +00006311 // ARC forbids the implicit conversion of object pointers to 'void *',
6312 // so these types are not compatible.
6313 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6315 LHS = RHS = true;
6316 return QualType();
6317 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006318 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6319 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6320 QualType destPointee
6321 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6322 QualType destType = Context.getPointerType(destPointee);
6323 // Add qualifiers if necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006324 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006325 // Promote to void*.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006326 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006327 return destType;
6328 }
6329 return QualType();
6330}
6331
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006332/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006333/// ParenRange in parentheses.
6334static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006335 const PartialDiagnostic &Note,
6336 SourceRange ParenRange) {
6337 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6338 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6339 EndLoc.isValid()) {
6340 Self.Diag(Loc, Note)
6341 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6342 << FixItHint::CreateInsertion(EndLoc, ")");
6343 } else {
6344 // We can't display the parentheses, so just show the bare note.
6345 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006346 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006347}
6348
6349static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6350 return Opc >= BO_Mul && Opc <= BO_Shr;
6351}
6352
Hans Wennborg2f072b42011-06-09 17:06:51 +00006353/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6354/// expression, either using a built-in or overloaded operator,
Richard Trieu33fc7572011-09-06 20:06:39 +00006355/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6356/// expression.
Hans Wennborg2f072b42011-06-09 17:06:51 +00006357static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieu33fc7572011-09-06 20:06:39 +00006358 Expr **RHSExprs) {
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00006359 // Don't strip parenthesis: we should not warn if E is in parenthesis.
6360 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00006361 E = E->IgnoreConversionOperator();
Hans Wennborgcb4d7c22011-09-12 12:07:30 +00006362 E = E->IgnoreImpCasts();
Hans Wennborg2f072b42011-06-09 17:06:51 +00006363
6364 // Built-in binary operator.
6365 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6366 if (IsArithmeticOp(OP->getOpcode())) {
6367 *Opcode = OP->getOpcode();
Richard Trieu33fc7572011-09-06 20:06:39 +00006368 *RHSExprs = OP->getRHS();
Hans Wennborg2f072b42011-06-09 17:06:51 +00006369 return true;
6370 }
6371 }
6372
6373 // Overloaded operator.
6374 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6375 if (Call->getNumArgs() != 2)
6376 return false;
6377
6378 // Make sure this is really a binary operator that is safe to pass into
6379 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6380 OverloadedOperatorKind OO = Call->getOperator();
Benjamin Kramer66dca6e2013-03-30 11:56:00 +00006381 if (OO < OO_Plus || OO > OO_Arrow ||
6382 OO == OO_PlusPlus || OO == OO_MinusMinus)
Hans Wennborg2f072b42011-06-09 17:06:51 +00006383 return false;
6384
6385 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6386 if (IsArithmeticOp(OpKind)) {
6387 *Opcode = OpKind;
Richard Trieu33fc7572011-09-06 20:06:39 +00006388 *RHSExprs = Call->getArg(1);
Hans Wennborg2f072b42011-06-09 17:06:51 +00006389 return true;
6390 }
6391 }
6392
6393 return false;
6394}
6395
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006396static bool IsLogicOp(BinaryOperatorKind Opc) {
6397 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6398}
6399
Hans Wennborg2f072b42011-06-09 17:06:51 +00006400/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6401/// or is a logical expression such as (x==y) which has int type, but is
6402/// commonly interpreted as boolean.
6403static bool ExprLooksBoolean(Expr *E) {
6404 E = E->IgnoreParenImpCasts();
6405
6406 if (E->getType()->isBooleanType())
6407 return true;
6408 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6409 return IsLogicOp(OP->getOpcode());
6410 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6411 return OP->getOpcode() == UO_LNot;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006412 if (E->getType()->isPointerType())
6413 return true;
Hans Wennborg2f072b42011-06-09 17:06:51 +00006414
6415 return false;
6416}
6417
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006418/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6419/// and binary operator are mixed in a way that suggests the programmer assumed
6420/// the conditional operator has higher precedence, for example:
6421/// "int x = a + someBinaryCondition ? 1 : 2".
6422static void DiagnoseConditionalPrecedence(Sema &Self,
6423 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006424 Expr *Condition,
Richard Trieu33fc7572011-09-06 20:06:39 +00006425 Expr *LHSExpr,
6426 Expr *RHSExpr) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00006427 BinaryOperatorKind CondOpcode;
6428 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006429
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006430 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00006431 return;
6432 if (!ExprLooksBoolean(CondRHS))
6433 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006434
Hans Wennborg2f072b42011-06-09 17:06:51 +00006435 // The condition is an arithmetic binary expression, with a right-
6436 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006437
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006438 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006439 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00006440 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006441
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006442 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +00006443 Self.PDiag(diag::note_precedence_silence)
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006444 << BinaryOperator::getOpcodeStr(CondOpcode),
6445 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00006446
6447 SuggestParentheses(Self, OpLoc,
6448 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieu33fc7572011-09-06 20:06:39 +00006449 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006450}
6451
Steve Narofff69936d2007-09-16 03:34:24 +00006452/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006453/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006454ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006455 SourceLocation ColonLoc,
6456 Expr *CondExpr, Expr *LHSExpr,
6457 Expr *RHSExpr) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006458 if (!getLangOpts().CPlusPlus) {
6459 // C cannot handle TypoExpr nodes in the condition because it
6460 // doesn't handle dependent types properly, so make sure any TypoExprs have
6461 // been dealt with before checking the operands.
6462 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6463 if (!CondResult.isUsable()) return ExprError();
6464 CondExpr = CondResult.get();
6465 }
6466
Chris Lattnera21ddb32007-11-26 01:40:58 +00006467 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6468 // was the condition.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006469 OpaqueValueExpr *opaqueValue = nullptr;
6470 Expr *commonExpr = nullptr;
6471 if (!LHSExpr) {
John McCall56ca35d2011-02-17 10:25:35 +00006472 commonExpr = CondExpr;
Fariborz Jahanian2521dfa2013-05-17 16:29:36 +00006473 // Lower out placeholder types first. This is important so that we don't
6474 // try to capture a placeholder. This happens in few cases in C++; such
6475 // as Objective-C++'s dictionary subscripting syntax.
6476 if (commonExpr->hasPlaceholderType()) {
6477 ExprResult result = CheckPlaceholderExpr(commonExpr);
6478 if (!result.isUsable()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006479 commonExpr = result.get();
Fariborz Jahanian2521dfa2013-05-17 16:29:36 +00006480 }
John McCall56ca35d2011-02-17 10:25:35 +00006481 // We usually want to apply unary conversions *before* saving, except
6482 // in the special case of a C++ l-value conditional.
David Blaikie4e4d0842012-03-11 07:00:24 +00006483 if (!(getLangOpts().CPlusPlus
John McCall56ca35d2011-02-17 10:25:35 +00006484 && !commonExpr->isTypeDependent()
6485 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6486 && commonExpr->isGLValue()
6487 && commonExpr->isOrdinaryOrBitFieldObject()
6488 && RHSExpr->isOrdinaryOrBitFieldObject()
6489 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006490 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6491 if (commonRes.isInvalid())
6492 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006493 commonExpr = commonRes.get();
John McCall56ca35d2011-02-17 10:25:35 +00006494 }
6495
6496 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6497 commonExpr->getType(),
6498 commonExpr->getValueKind(),
Douglas Gregor97df54e2012-02-23 22:17:26 +00006499 commonExpr->getObjectKind(),
6500 commonExpr);
John McCall56ca35d2011-02-17 10:25:35 +00006501 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006502 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006503
John McCallf89e55a2010-11-18 06:31:45 +00006504 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006505 ExprObjectKind OK = OK_Ordinary;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006506 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
John Wiegley429bb272011-04-08 18:41:53 +00006507 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006508 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006509 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6510 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006511 return ExprError();
6512
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006513 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6514 RHS.get());
6515
John McCall56ca35d2011-02-17 10:25:35 +00006516 if (!commonExpr)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006517 return new (Context)
6518 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6519 RHS.get(), result, VK, OK);
John McCall56ca35d2011-02-17 10:25:35 +00006520
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006521 return new (Context) BinaryConditionalOperator(
6522 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6523 ColonLoc, result, VK, OK);
Reid Spencer5f016e22007-07-11 17:01:13 +00006524}
6525
John McCalle4be87e2011-01-31 23:13:11 +00006526// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006527// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006528// routine is it effectively iqnores the qualifiers on the top level pointee.
6529// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6530// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006531static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00006532checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6533 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6534 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006535
Reid Spencer5f016e22007-07-11 17:01:13 +00006536 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006537 const Type *lhptee, *rhptee;
6538 Qualifiers lhq, rhq;
Stephen Hines651f13c2014-04-23 16:59:28 -07006539 std::tie(lhptee, lhq) =
6540 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6541 std::tie(rhptee, rhq) =
6542 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006543
John McCalle4be87e2011-01-31 23:13:11 +00006544 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006545
6546 // C99 6.5.16.1p1: This following citation is common to constraints
6547 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6548 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006549
John McCallf85e1932011-06-15 23:02:42 +00006550 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6551 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6552 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6553 // Ignore lifetime for further calculation.
6554 lhq.removeObjCLifetime();
6555 rhq.removeObjCLifetime();
6556 }
6557
John McCall86c05f32011-02-01 00:10:29 +00006558 if (!lhq.compatiblyIncludes(rhq)) {
6559 // Treat address-space mismatches as fatal. TODO: address subspaces
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006560 if (!lhq.isAddressSpaceSupersetOf(rhq))
John McCall86c05f32011-02-01 00:10:29 +00006561 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6562
John McCallf85e1932011-06-15 23:02:42 +00006563 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00006564 // and from void*.
John McCall200fa532012-02-08 00:46:36 +00006565 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCallf85e1932011-06-15 23:02:42 +00006566 .compatiblyIncludes(
John McCall200fa532012-02-08 00:46:36 +00006567 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall22348732011-03-26 02:56:45 +00006568 && (lhptee->isVoidType() || rhptee->isVoidType()))
6569 ; // keep old
6570
John McCallf85e1932011-06-15 23:02:42 +00006571 // Treat lifetime mismatches as fatal.
6572 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6573 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6574
John McCall86c05f32011-02-01 00:10:29 +00006575 // For GCC compatibility, other qualifier mismatches are treated
6576 // as still compatible in C.
6577 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6578 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006579
Mike Stumpeed9cac2009-02-19 03:04:26 +00006580 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6581 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006582 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006583 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006584 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006585 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006586
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006587 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006588 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006589 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006590 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006591
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006592 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006593 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006594 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006595
6596 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006597 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006598 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006599 }
John McCall86c05f32011-02-01 00:10:29 +00006600
Mike Stumpeed9cac2009-02-19 03:04:26 +00006601 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006602 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006603 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6604 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006605 // Check if the pointee types are compatible ignoring the sign.
6606 // We explicitly check for char so that we catch "char" vs
6607 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006608 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006609 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006610 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006611 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006612
Chris Lattner6a2b9262009-10-17 20:33:28 +00006613 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006614 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006615 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006616 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006617
John McCall86c05f32011-02-01 00:10:29 +00006618 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006619 // Types are compatible ignoring the sign. Qualifier incompatibility
6620 // takes priority over sign incompatibility because the sign
6621 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006622 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006623 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006624
John McCalle4be87e2011-01-31 23:13:11 +00006625 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006626 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006627
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006628 // If we are a multi-level pointer, it's possible that our issue is simply
6629 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6630 // the eventual target type is the same and the pointers have the same
6631 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006632 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006633 do {
John McCall86c05f32011-02-01 00:10:29 +00006634 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6635 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006636 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006637
John McCall86c05f32011-02-01 00:10:29 +00006638 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006639 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006640 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006641
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006642 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006643 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006644 }
David Blaikie4e4d0842012-03-11 07:00:24 +00006645 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian53c81672011-10-05 00:05:34 +00006646 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6647 return Sema::IncompatiblePointer;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006648 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006649}
6650
John McCalle4be87e2011-01-31 23:13:11 +00006651/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006652/// block pointer types are compatible or whether a block and normal pointer
6653/// are compatible. It is more restrict than comparing two function pointer
6654// types.
John McCalle4be87e2011-01-31 23:13:11 +00006655static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00006656checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6657 QualType RHSType) {
6658 assert(LHSType.isCanonical() && "LHS not canonicalized!");
6659 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00006660
Steve Naroff1c7d0672008-09-04 15:10:53 +00006661 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006662
Steve Naroff1c7d0672008-09-04 15:10:53 +00006663 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieu1da27a12011-09-06 20:21:22 +00006664 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6665 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006666
John McCalle4be87e2011-01-31 23:13:11 +00006667 // In C++, the types have to match exactly.
David Blaikie4e4d0842012-03-11 07:00:24 +00006668 if (S.getLangOpts().CPlusPlus)
John McCalle4be87e2011-01-31 23:13:11 +00006669 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006670
John McCalle4be87e2011-01-31 23:13:11 +00006671 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006672
Steve Naroff1c7d0672008-09-04 15:10:53 +00006673 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006674 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6675 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006676
Richard Trieu1da27a12011-09-06 20:21:22 +00006677 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00006678 return Sema::IncompatibleBlockPointer;
6679
Steve Naroff1c7d0672008-09-04 15:10:53 +00006680 return ConvTy;
6681}
6682
John McCalle4be87e2011-01-31 23:13:11 +00006683/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006684/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006685static Sema::AssignConvertType
Richard Trieu1da27a12011-09-06 20:21:22 +00006686checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6687 QualType RHSType) {
6688 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6689 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCalle4be87e2011-01-31 23:13:11 +00006690
Richard Trieu1da27a12011-09-06 20:21:22 +00006691 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006692 // Class is not compatible with ObjC object pointers.
Richard Trieu1da27a12011-09-06 20:21:22 +00006693 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6694 !RHSType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006695 return Sema::IncompatiblePointer;
6696 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006697 }
Richard Trieu1da27a12011-09-06 20:21:22 +00006698 if (RHSType->isObjCBuiltinType()) {
Richard Trieu1da27a12011-09-06 20:21:22 +00006699 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6700 !LHSType->isObjCQualifiedClassType())
Fariborz Jahanian412a4962011-09-15 20:40:18 +00006701 return Sema::IncompatiblePointer;
John McCalle4be87e2011-01-31 23:13:11 +00006702 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006703 }
Richard Trieu1da27a12011-09-06 20:21:22 +00006704 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6705 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006706
Fariborz Jahanianf2b4f7b2012-01-12 22:12:08 +00006707 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6708 // make an exception for id<P>
6709 !LHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006710 return Sema::CompatiblePointerDiscardsQualifiers;
6711
Richard Trieu1da27a12011-09-06 20:21:22 +00006712 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCalle4be87e2011-01-31 23:13:11 +00006713 return Sema::Compatible;
Richard Trieu1da27a12011-09-06 20:21:22 +00006714 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006715 return Sema::IncompatibleObjCQualifiedId;
6716 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006717}
6718
John McCall1c23e912010-11-16 02:32:08 +00006719Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006720Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieu1da27a12011-09-06 20:21:22 +00006721 QualType LHSType, QualType RHSType) {
John McCall1c23e912010-11-16 02:32:08 +00006722 // Fake up an opaque expression. We don't actually care about what
6723 // cast operations are required, so if CheckAssignmentConstraints
6724 // adds casts to this they'll be wasted, but fortunately that doesn't
6725 // usually happen on valid code.
Richard Trieu1da27a12011-09-06 20:21:22 +00006726 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6727 ExprResult RHSPtr = &RHSExpr;
John McCall1c23e912010-11-16 02:32:08 +00006728 CastKind K = CK_Invalid;
6729
Richard Trieu1da27a12011-09-06 20:21:22 +00006730 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall1c23e912010-11-16 02:32:08 +00006731}
6732
Mike Stumpeed9cac2009-02-19 03:04:26 +00006733/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6734/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006735/// pointers. Here are some objectionable examples that GCC considers warnings:
6736///
6737/// int a, *pint;
6738/// short *pshort;
6739/// struct foo *pfoo;
6740///
6741/// pint = pshort; // warning: assignment from incompatible pointer type
6742/// a = pint; // warning: assignment makes integer from pointer without a cast
6743/// pint = a; // warning: assignment makes pointer from integer without a cast
6744/// pint = pfoo; // warning: assignment from incompatible pointer type
6745///
6746/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006747/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006748///
John McCalldaa8e4e2010-11-15 09:13:47 +00006749/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006750Sema::AssignConvertType
Richard Trieufacef2e2011-09-06 20:30:53 +00006751Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCalldaa8e4e2010-11-15 09:13:47 +00006752 CastKind &Kind) {
Richard Trieufacef2e2011-09-06 20:30:53 +00006753 QualType RHSType = RHS.get()->getType();
6754 QualType OrigLHSType = LHSType;
John McCall1c23e912010-11-16 02:32:08 +00006755
Chris Lattnerfc144e22008-01-04 23:18:45 +00006756 // Get canonical types. We're not formatting these types, just comparing
6757 // them.
Richard Trieufacef2e2011-09-06 20:30:53 +00006758 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6759 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006760
John McCallb6cfa242011-01-31 22:28:28 +00006761 // Common case: no conversion required.
Richard Trieufacef2e2011-09-06 20:30:53 +00006762 if (LHSType == RHSType) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006763 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006764 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006765 }
6766
Eli Friedman860a3192012-06-16 02:19:17 +00006767 // If we have an atomic type, try a non-atomic assignment, then just add an
6768 // atomic qualification step.
David Chisnall7a7ee302012-01-16 17:27:18 +00006769 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman860a3192012-06-16 02:19:17 +00006770 Sema::AssignConvertType result =
6771 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6772 if (result != Compatible)
6773 return result;
6774 if (Kind != CK_NoOp)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006775 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
Eli Friedman860a3192012-06-16 02:19:17 +00006776 Kind = CK_NonAtomicToAtomic;
6777 return Compatible;
David Chisnall7a7ee302012-01-16 17:27:18 +00006778 }
6779
Douglas Gregor9d293df2008-10-28 00:22:11 +00006780 // If the left-hand side is a reference type, then we are in a
6781 // (rare!) case where we've allowed the use of references in C,
6782 // e.g., as a parameter type in a built-in function. In this case,
6783 // just make sure that the type referenced is compatible with the
6784 // right-hand side type. The caller is responsible for adjusting
Richard Trieufacef2e2011-09-06 20:30:53 +00006785 // LHSType so that the resulting expression does not have reference
Douglas Gregor9d293df2008-10-28 00:22:11 +00006786 // type.
Richard Trieufacef2e2011-09-06 20:30:53 +00006787 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6788 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006789 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006790 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006791 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006792 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006793 }
John McCallb6cfa242011-01-31 22:28:28 +00006794
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006795 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6796 // to the same ExtVector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00006797 if (LHSType->isExtVectorType()) {
6798 if (RHSType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006799 return Incompatible;
Richard Trieufacef2e2011-09-06 20:30:53 +00006800 if (RHSType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006801 // CK_VectorSplat does T -> vector T, so first cast to the
6802 // element type.
Richard Trieufacef2e2011-09-06 20:30:53 +00006803 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6804 if (elType != RHSType) {
John McCalla180f042011-10-06 23:25:11 +00006805 Kind = PrepareScalarCast(RHS, elType);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006806 RHS = ImpCastExprToType(RHS.get(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006807 }
6808 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006809 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006810 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006811 }
Mike Stump1eb44332009-09-09 15:08:12 +00006812
John McCallb6cfa242011-01-31 22:28:28 +00006813 // Conversions to or from vector type.
Richard Trieufacef2e2011-09-06 20:30:53 +00006814 if (LHSType->isVectorType() || RHSType->isVectorType()) {
6815 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006816 // Allow assignments of an AltiVec vector type to an equivalent GCC
6817 // vector type and vice versa
Richard Trieufacef2e2011-09-06 20:30:53 +00006818 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006819 Kind = CK_BitCast;
6820 return Compatible;
6821 }
6822
Douglas Gregor255210e2010-08-06 10:14:59 +00006823 // If we are allowing lax vector conversions, and LHS and RHS are both
6824 // vectors, the total size only needs to be the same. This is a bitcast;
6825 // no bits are changed but the result type is different.
Stephen Hines651f13c2014-04-23 16:59:28 -07006826 if (isLaxVectorConversion(RHSType, LHSType)) {
John McCall0c6d28d2010-11-15 10:08:00 +00006827 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006828 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006829 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006830 }
6831 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006832 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006833
John McCallb6cfa242011-01-31 22:28:28 +00006834 // Arithmetic conversions.
Richard Trieufacef2e2011-09-06 20:30:53 +00006835 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006836 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCalla180f042011-10-06 23:25:11 +00006837 Kind = PrepareScalarCast(RHS, LHSType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006838 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006839 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006840
John McCallb6cfa242011-01-31 22:28:28 +00006841 // Conversions to normal pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00006842 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006843 // U* -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00006844 if (isa<PointerType>(RHSType)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006845 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
6846 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
6847 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00006848 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006849 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006850
John McCallb6cfa242011-01-31 22:28:28 +00006851 // int -> T*
Richard Trieufacef2e2011-09-06 20:30:53 +00006852 if (RHSType->isIntegerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006853 Kind = CK_IntegralToPointer; // FIXME: null?
6854 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006855 }
John McCallb6cfa242011-01-31 22:28:28 +00006856
6857 // C pointers are not compatible with ObjC object pointers,
6858 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00006859 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006860 // - conversions to void*
Richard Trieufacef2e2011-09-06 20:30:53 +00006861 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006862 Kind = CK_BitCast;
John McCallb6cfa242011-01-31 22:28:28 +00006863 return Compatible;
6864 }
6865
6866 // - conversions from 'Class' to the redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00006867 if (RHSType->isObjCClassType() &&
6868 Context.hasSameType(LHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006869 Context.getObjCClassRedefinitionType())) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006870 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006871 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006872 }
Douglas Gregorc737acb2011-09-27 16:10:05 +00006873
John McCallb6cfa242011-01-31 22:28:28 +00006874 Kind = CK_BitCast;
6875 return IncompatiblePointer;
6876 }
6877
6878 // U^ -> void*
Richard Trieufacef2e2011-09-06 20:30:53 +00006879 if (RHSType->getAs<BlockPointerType>()) {
6880 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006881 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006882 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006883 }
Steve Naroffb4406862008-09-29 18:10:17 +00006884 }
John McCallb6cfa242011-01-31 22:28:28 +00006885
Steve Naroff1c7d0672008-09-04 15:10:53 +00006886 return Incompatible;
6887 }
6888
John McCallb6cfa242011-01-31 22:28:28 +00006889 // Conversions to block pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00006890 if (isa<BlockPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006891 // U^ -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00006892 if (RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00006893 Kind = CK_BitCast;
Richard Trieufacef2e2011-09-06 20:30:53 +00006894 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCallb6cfa242011-01-31 22:28:28 +00006895 }
6896
6897 // int or null -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00006898 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006899 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006900 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006901 }
6902
John McCallb6cfa242011-01-31 22:28:28 +00006903 // id -> T^
David Blaikie4e4d0842012-03-11 07:00:24 +00006904 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006905 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006906 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006907 }
Steve Naroffb4406862008-09-29 18:10:17 +00006908
John McCallb6cfa242011-01-31 22:28:28 +00006909 // void* -> T^
Richard Trieufacef2e2011-09-06 20:30:53 +00006910 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006911 if (RHSPT->getPointeeType()->isVoidType()) {
6912 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006913 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006914 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006915
Chris Lattnerfc144e22008-01-04 23:18:45 +00006916 return Incompatible;
6917 }
6918
John McCallb6cfa242011-01-31 22:28:28 +00006919 // Conversions to Objective-C pointers.
Richard Trieufacef2e2011-09-06 20:30:53 +00006920 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006921 // A* -> B*
Richard Trieufacef2e2011-09-06 20:30:53 +00006922 if (RHSType->isObjCObjectPointerType()) {
John McCallb6cfa242011-01-31 22:28:28 +00006923 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00006924 Sema::AssignConvertType result =
Richard Trieufacef2e2011-09-06 20:30:53 +00006925 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikie4e4d0842012-03-11 07:00:24 +00006926 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00006927 result == Compatible &&
Richard Trieufacef2e2011-09-06 20:30:53 +00006928 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00006929 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00006930 return result;
John McCallb6cfa242011-01-31 22:28:28 +00006931 }
6932
6933 // int or null -> A*
Richard Trieufacef2e2011-09-06 20:30:53 +00006934 if (RHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006935 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006936 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006937 }
6938
John McCallb6cfa242011-01-31 22:28:28 +00006939 // In general, C pointers are not compatible with ObjC object pointers,
6940 // with two exceptions:
Richard Trieufacef2e2011-09-06 20:30:53 +00006941 if (isa<PointerType>(RHSType)) {
John McCall1d9b3b22011-09-09 05:25:32 +00006942 Kind = CK_CPointerToObjCPointerCast;
6943
John McCallb6cfa242011-01-31 22:28:28 +00006944 // - conversions from 'void*'
Richard Trieufacef2e2011-09-06 20:30:53 +00006945 if (RHSType->isVoidPointerType()) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006946 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006947 }
6948
6949 // - conversions to 'Class' from its redefinition type
Richard Trieufacef2e2011-09-06 20:30:53 +00006950 if (LHSType->isObjCClassType() &&
6951 Context.hasSameType(RHSType,
Douglas Gregor01a4cf12011-08-11 20:58:55 +00006952 Context.getObjCClassRedefinitionType())) {
John McCallb6cfa242011-01-31 22:28:28 +00006953 return Compatible;
6954 }
6955
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006956 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006957 }
John McCallb6cfa242011-01-31 22:28:28 +00006958
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006959 // Only under strict condition T^ is compatible with an Objective-C pointer.
6960 if (RHSType->isBlockPointerType() &&
6961 isObjCPtrBlockCompatible(*this, Context, LHSType)) {
John McCalldc05b112011-09-10 01:16:55 +00006962 maybeExtendBlockObject(*this, RHS);
John McCall1d9b3b22011-09-09 05:25:32 +00006963 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006964 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006965 }
6966
Steve Naroff14108da2009-07-10 23:34:53 +00006967 return Incompatible;
6968 }
John McCallb6cfa242011-01-31 22:28:28 +00006969
6970 // Conversions from pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00006971 if (isa<PointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006972 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00006973 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006974 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006975 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006976 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006977
John McCallb6cfa242011-01-31 22:28:28 +00006978 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00006979 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006980 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006981 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006982 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006983
Chris Lattnerfc144e22008-01-04 23:18:45 +00006984 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006985 }
John McCallb6cfa242011-01-31 22:28:28 +00006986
6987 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieufacef2e2011-09-06 20:30:53 +00006988 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006989 // T* -> _Bool
Richard Trieufacef2e2011-09-06 20:30:53 +00006990 if (LHSType == Context.BoolTy) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006991 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006992 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006993 }
Steve Naroff14108da2009-07-10 23:34:53 +00006994
John McCallb6cfa242011-01-31 22:28:28 +00006995 // T* -> int
Richard Trieufacef2e2011-09-06 20:30:53 +00006996 if (LHSType->isIntegerType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006997 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006998 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006999 }
7000
Steve Naroff14108da2009-07-10 23:34:53 +00007001 return Incompatible;
7002 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00007003
John McCallb6cfa242011-01-31 22:28:28 +00007004 // struct A -> struct B
Richard Trieufacef2e2011-09-06 20:30:53 +00007005 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7006 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00007007 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00007008 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00007009 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007010 }
John McCallb6cfa242011-01-31 22:28:28 +00007011
Reid Spencer5f016e22007-07-11 17:01:13 +00007012 return Incompatible;
7013}
7014
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007015/// \brief Constructs a transparent union from an expression that is
7016/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00007017static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7018 ExprResult &EResult, QualType UnionType,
7019 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007020 // Build an initializer list that designates the appropriate member
7021 // of the transparent union.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007022 Expr *E = EResult.get();
Ted Kremenek709210f2010-04-13 23:39:13 +00007023 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00007024 E, SourceLocation());
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007025 Initializer->setType(UnionType);
7026 Initializer->setInitializedFieldInUnion(Field);
7027
7028 // Build a compound literal constructing a value of the transparent
7029 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00007030 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007031 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7032 VK_RValue, Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007033}
7034
7035Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00007036Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieuf7720da2011-09-06 20:40:12 +00007037 ExprResult &RHS) {
7038 QualType RHSType = RHS.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007039
Mike Stump1eb44332009-09-09 15:08:12 +00007040 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007041 // transparent_union GCC extension.
7042 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00007043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007044 return Incompatible;
7045
7046 // The field to initialize within the transparent union.
7047 RecordDecl *UD = UT->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007048 FieldDecl *InitField = nullptr;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007049 // It's compatible if the expression matches any of the fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07007050 for (auto *it : UD->fields()) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007051 if (it->getType()->isPointerType()) {
7052 // If the transparent union contains a pointer type, we allow:
7053 // 1) void pointer
7054 // 2) null pointer constant
Richard Trieuf7720da2011-09-06 20:40:12 +00007055 if (RHSType->isPointerType())
John McCall1d9b3b22011-09-09 05:25:32 +00007056 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007057 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
Stephen Hines651f13c2014-04-23 16:59:28 -07007058 InitField = it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007059 break;
7060 }
Mike Stump1eb44332009-09-09 15:08:12 +00007061
Richard Trieuf7720da2011-09-06 20:40:12 +00007062 if (RHS.get()->isNullPointerConstant(Context,
7063 Expr::NPC_ValueDependentIsNull)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007064 RHS = ImpCastExprToType(RHS.get(), it->getType(),
Richard Trieuf7720da2011-09-06 20:40:12 +00007065 CK_NullToPointer);
Stephen Hines651f13c2014-04-23 16:59:28 -07007066 InitField = it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007067 break;
7068 }
7069 }
7070
John McCalldaa8e4e2010-11-15 09:13:47 +00007071 CastKind Kind = CK_Invalid;
Richard Trieuf7720da2011-09-06 20:40:12 +00007072 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007073 == Compatible) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007074 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
Stephen Hines651f13c2014-04-23 16:59:28 -07007075 InitField = it;
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007076 break;
7077 }
7078 }
7079
7080 if (!InitField)
7081 return Incompatible;
7082
Richard Trieuf7720da2011-09-06 20:40:12 +00007083 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00007084 return Compatible;
7085}
7086
Chris Lattner5cf216b2008-01-04 18:04:52 +00007087Sema::AssignConvertType
Sebastian Redl14b0c192011-09-24 17:48:00 +00007088Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00007089 bool Diagnose,
7090 bool DiagnoseCFAudited) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007091 if (getLangOpts().CPlusPlus) {
Eli Friedmanb001de72011-10-06 23:00:33 +00007092 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00007093 // C++ 5.17p3: If the left operand is not of class type, the
7094 // expression is implicitly converted (C++ 4) to the
7095 // cv-unqualified type of the left operand.
Sebastian Redl091fffe2011-10-16 18:19:06 +00007096 ExprResult Res;
7097 if (Diagnose) {
7098 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7099 AA_Assigning);
7100 } else {
7101 ImplicitConversionSequence ICS =
7102 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7103 /*SuppressUserConversions=*/false,
7104 /*AllowExplicit=*/false,
7105 /*InOverloadResolution=*/false,
7106 /*CStyle=*/false,
7107 /*AllowObjCWritebackConversion=*/false);
7108 if (ICS.isFailure())
7109 return Incompatible;
7110 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7111 ICS, AA_Assigning);
7112 }
John Wiegley429bb272011-04-08 18:41:53 +00007113 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00007114 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00007115 Sema::AssignConvertType result = Compatible;
David Blaikie4e4d0842012-03-11 07:00:24 +00007116 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieuf7720da2011-09-06 20:40:12 +00007117 !CheckObjCARCUnavailableWeakConversion(LHSType,
7118 RHS.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00007119 result = IncompatibleObjCWeakRef;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007120 RHS = Res;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00007121 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00007122 }
7123
7124 // FIXME: Currently, we fall through and treat C++ classes like C
7125 // structures.
Eli Friedmanb001de72011-10-06 23:00:33 +00007126 // FIXME: We also fall through for atomics; not sure what should
7127 // happen there, though.
Sebastian Redl14b0c192011-09-24 17:48:00 +00007128 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00007129
Steve Naroff529a4ad2007-11-27 17:58:44 +00007130 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7131 // a null pointer constant.
Bill Wendling45c2eed2013-11-27 05:27:22 +00007132 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7133 LHSType->isBlockPointerType()) &&
7134 RHS.get()->isNullPointerConstant(Context,
7135 Expr::NPC_ValueDependentIsNull)) {
7136 CastKind Kind;
7137 CXXCastPath Path;
7138 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007139 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
Steve Naroff529a4ad2007-11-27 17:58:44 +00007140 return Compatible;
7141 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007142
Chris Lattner943140e2007-10-16 02:55:40 +00007143 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00007144 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00007145 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00007146 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00007147 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00007148 // Suppress this for references: C++ 8.5.3p5.
Richard Trieuf7720da2011-09-06 20:40:12 +00007149 if (!LHSType->isReferenceType()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007150 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
Richard Trieuf7720da2011-09-06 20:40:12 +00007151 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007152 return Incompatible;
7153 }
Steve Narofff1120de2007-08-24 22:33:52 +00007154
Stephen Hines176edba2014-12-01 14:53:08 -08007155 Expr *PRE = RHS.get()->IgnoreParenCasts();
7156 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7157 ObjCProtocolDecl *PDecl = OPE->getProtocol();
7158 if (PDecl && !PDecl->hasDefinition()) {
7159 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7160 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7161 }
7162 }
7163
John McCalldaa8e4e2010-11-15 09:13:47 +00007164 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007165 Sema::AssignConvertType result =
Richard Trieuf7720da2011-09-06 20:40:12 +00007166 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007167
Steve Narofff1120de2007-08-24 22:33:52 +00007168 // C99 6.5.16.1p2: The value of the right operand is converted to the
7169 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00007170 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7171 // so that we can use references in built-in functions even in C.
7172 // The getNonReferenceType() call makes sure that the resulting expression
7173 // does not have reference type.
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00007174 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7175 QualType Ty = LHSType.getNonLValueExprType(Context);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007176 Expr *E = RHS.get();
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00007177 if (getLangOpts().ObjCAutoRefCount)
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00007178 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7179 DiagnoseCFAudited);
Stephen Hines651f13c2014-04-23 16:59:28 -07007180 if (getLangOpts().ObjC1 &&
7181 (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7182 LHSType, E->getType(), E) ||
7183 ConversionToObjCStringLiteralCheck(LHSType, E))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007184 RHS = E;
Stephen Hines651f13c2014-04-23 16:59:28 -07007185 return Compatible;
7186 }
7187
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00007188 RHS = ImpCastExprToType(E, Ty, Kind);
7189 }
Steve Narofff1120de2007-08-24 22:33:52 +00007190 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00007191}
7192
Richard Trieuf7720da2011-09-06 20:40:12 +00007193QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7194 ExprResult &RHS) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007195 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieuf7720da2011-09-06 20:40:12 +00007196 << LHS.get()->getType() << RHS.get()->getType()
7197 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00007198 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007199}
7200
Stephen Hines651f13c2014-04-23 16:59:28 -07007201/// Try to convert a value of non-vector type to a vector type by converting
7202/// the type to the element type of the vector and then performing a splat.
7203/// If the language is OpenCL, we only use conversions that promote scalar
7204/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7205/// for float->int.
7206///
7207/// \param scalar - if non-null, actually perform the conversions
7208/// \return true if the operation fails (but without diagnosing the failure)
7209static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7210 QualType scalarTy,
7211 QualType vectorEltTy,
7212 QualType vectorTy) {
7213 // The conversion to apply to the scalar before splatting it,
7214 // if necessary.
7215 CastKind scalarCast = CK_Invalid;
7216
7217 if (vectorEltTy->isIntegralType(S.Context)) {
7218 if (!scalarTy->isIntegralType(S.Context))
7219 return true;
7220 if (S.getLangOpts().OpenCL &&
7221 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7222 return true;
7223 scalarCast = CK_IntegralCast;
7224 } else if (vectorEltTy->isRealFloatingType()) {
7225 if (scalarTy->isRealFloatingType()) {
7226 if (S.getLangOpts().OpenCL &&
7227 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7228 return true;
7229 scalarCast = CK_FloatingCast;
7230 }
7231 else if (scalarTy->isIntegralType(S.Context))
7232 scalarCast = CK_IntegralToFloating;
7233 else
7234 return true;
7235 } else {
7236 return true;
7237 }
7238
7239 // Adjust scalar if desired.
7240 if (scalar) {
7241 if (scalarCast != CK_Invalid)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007242 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7243 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
Stephen Hines651f13c2014-04-23 16:59:28 -07007244 }
7245 return false;
7246}
7247
Richard Trieu08062aa2011-09-06 21:01:04 +00007248QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00007249 SourceLocation Loc, bool IsCompAssign) {
Richard Smith9c129f82011-10-28 03:31:48 +00007250 if (!IsCompAssign) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007251 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
Richard Smith9c129f82011-10-28 03:31:48 +00007252 if (LHS.isInvalid())
7253 return QualType();
7254 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007255 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
Richard Smith9c129f82011-10-28 03:31:48 +00007256 if (RHS.isInvalid())
7257 return QualType();
7258
Mike Stumpeed9cac2009-02-19 03:04:26 +00007259 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00007260 // For example, "const float" and "float" are equivalent.
Stephen Hines651f13c2014-04-23 16:59:28 -07007261 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7262 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007263
Nate Begemanbe2341d2008-07-14 18:02:46 +00007264 // If the vector types are identical, return.
Stephen Hines651f13c2014-04-23 16:59:28 -07007265 if (Context.hasSameType(LHSType, RHSType))
Richard Trieu08062aa2011-09-06 21:01:04 +00007266 return LHSType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00007267
Stephen Hines651f13c2014-04-23 16:59:28 -07007268 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7269 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7270 assert(LHSVecType || RHSVecType);
7271
7272 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7273 if (LHSVecType && RHSVecType &&
Richard Trieu08062aa2011-09-06 21:01:04 +00007274 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007275 if (isa<ExtVectorType>(LHSVecType)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007276 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Richard Trieu08062aa2011-09-06 21:01:04 +00007277 return LHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00007278 }
7279
Richard Trieuccd891a2011-09-09 01:45:06 +00007280 if (!IsCompAssign)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007281 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
Richard Trieu08062aa2011-09-06 21:01:04 +00007282 return RHSType;
Douglas Gregor255210e2010-08-06 10:14:59 +00007283 }
7284
Stephen Hines651f13c2014-04-23 16:59:28 -07007285 // If there's an ext-vector type and a scalar, try to convert the scalar to
7286 // the vector element type and splat.
7287 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7288 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7289 LHSVecType->getElementType(), LHSType))
7290 return LHSType;
7291 }
7292 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007293 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7294 LHSType, RHSVecType->getElementType(),
7295 RHSType))
Stephen Hines651f13c2014-04-23 16:59:28 -07007296 return RHSType;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00007297 }
7298
Stephen Hines651f13c2014-04-23 16:59:28 -07007299 // If we're allowing lax vector conversions, only the total (data) size
7300 // needs to be the same.
7301 // FIXME: Should we really be allowing this?
7302 // FIXME: We really just pick the LHS type arbitrarily?
7303 if (isLaxVectorConversion(RHSType, LHSType)) {
7304 QualType resultType = LHSType;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007305 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
Stephen Hines651f13c2014-04-23 16:59:28 -07007306 return resultType;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007307 }
Mike Stump1eb44332009-09-09 15:08:12 +00007308
Stephen Hines651f13c2014-04-23 16:59:28 -07007309 // Okay, the expression is invalid.
7310
7311 // If there's a non-vector, non-real operand, diagnose that.
7312 if ((!RHSVecType && !RHSType->isRealType()) ||
7313 (!LHSVecType && !LHSType->isRealType())) {
7314 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7315 << LHSType << RHSType
7316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7317 return QualType();
Nate Begeman4119d1a2007-12-30 02:59:45 +00007318 }
Mike Stump1eb44332009-09-09 15:08:12 +00007319
Stephen Hines651f13c2014-04-23 16:59:28 -07007320 // Otherwise, use the generic diagnostic.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007321 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Stephen Hines651f13c2014-04-23 16:59:28 -07007322 << LHSType << RHSType
Richard Trieu08062aa2011-09-06 21:01:04 +00007323 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007324 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00007325}
7326
Richard Trieu481037f2011-09-16 00:53:10 +00007327// checkArithmeticNull - Detect when a NULL constant is used improperly in an
7328// expression. These are mainly cases where the null pointer is used as an
7329// integer instead of a pointer.
7330static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7331 SourceLocation Loc, bool IsCompare) {
7332 // The canonical way to check for a GNU null is with isNullPointerConstant,
7333 // but we use a bit of a hack here for speed; this is a relatively
7334 // hot path, and isNullPointerConstant is slow.
7335 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7336 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7337
7338 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7339
7340 // Avoid analyzing cases where the result will either be invalid (and
7341 // diagnosed as such) or entirely valid and not something to warn about.
7342 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7343 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7344 return;
7345
7346 // Comparison operations would not make sense with a null pointer no matter
7347 // what the other expression is.
7348 if (!IsCompare) {
7349 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7350 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7351 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7352 return;
7353 }
7354
7355 // The rest of the operations only make sense with a null pointer
7356 // if the other expression is a pointer.
7357 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7358 NonNullType->canDecayToPointerType())
7359 return;
7360
7361 S.Diag(Loc, diag::warn_null_in_comparison_operation)
7362 << LHSNull /* LHS is NULL */ << NonNullType
7363 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7364}
7365
Richard Trieu08062aa2011-09-06 21:01:04 +00007366QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00007367 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007368 bool IsCompAssign, bool IsDiv) {
Richard Trieu481037f2011-09-16 00:53:10 +00007369 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7370
Richard Trieu08062aa2011-09-06 21:01:04 +00007371 if (LHS.get()->getType()->isVectorType() ||
7372 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00007373 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007374
Richard Trieuccd891a2011-09-09 01:45:06 +00007375 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00007376 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007377 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007378
David Chisnall7a7ee302012-01-16 17:27:18 +00007379
Eli Friedman860a3192012-06-16 02:19:17 +00007380 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu08062aa2011-09-06 21:01:04 +00007381 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007382
Chris Lattner7ef655a2010-01-12 21:23:57 +00007383 // Check for division by zero.
Chandler Carruth93f32da2013-06-14 08:57:18 +00007384 llvm::APSInt RHSValue;
7385 if (IsDiv && !RHS.get()->isValueDependent() &&
7386 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7387 DiagRuntimeBehavior(Loc, RHS.get(),
7388 PDiag(diag::warn_division_by_zero)
7389 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007390
Chris Lattner7ef655a2010-01-12 21:23:57 +00007391 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00007392}
7393
Chris Lattner7ef655a2010-01-12 21:23:57 +00007394QualType Sema::CheckRemainderOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00007395 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007396 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7397
Richard Trieu08062aa2011-09-06 21:01:04 +00007398 if (LHS.get()->getType()->isVectorType() ||
7399 RHS.get()->getType()->isVectorType()) {
7400 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7401 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00007402 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00007403 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar523aa602009-01-05 22:55:36 +00007404 }
Steve Naroff90045e82007-07-13 23:32:42 +00007405
Richard Trieuccd891a2011-09-09 01:45:06 +00007406 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu08062aa2011-09-06 21:01:04 +00007407 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007408 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007409
Eli Friedman860a3192012-06-16 02:19:17 +00007410 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu08062aa2011-09-06 21:01:04 +00007411 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007412
Chris Lattner7ef655a2010-01-12 21:23:57 +00007413 // Check for remainder by zero.
Chandler Carruth93f32da2013-06-14 08:57:18 +00007414 llvm::APSInt RHSValue;
7415 if (!RHS.get()->isValueDependent() &&
7416 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7417 DiagRuntimeBehavior(Loc, RHS.get(),
7418 PDiag(diag::warn_remainder_by_zero)
7419 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007420
Chris Lattner7ef655a2010-01-12 21:23:57 +00007421 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00007422}
7423
Chandler Carruth13b21be2011-06-27 08:02:19 +00007424/// \brief Diagnose invalid arithmetic on two void pointers.
7425static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00007426 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007427 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00007428 ? diag::err_typecheck_pointer_arith_void_type
7429 : diag::ext_gnu_void_ptr)
Richard Trieudef75842011-09-06 21:13:51 +00007430 << 1 /* two pointers */ << LHSExpr->getSourceRange()
7431 << RHSExpr->getSourceRange();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007432}
7433
7434/// \brief Diagnose invalid arithmetic on a void pointer.
7435static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7436 Expr *Pointer) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007437 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00007438 ? diag::err_typecheck_pointer_arith_void_type
7439 : diag::ext_gnu_void_ptr)
7440 << 0 /* one pointer */ << Pointer->getSourceRange();
7441}
7442
7443/// \brief Diagnose invalid arithmetic on two function pointers.
7444static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7445 Expr *LHS, Expr *RHS) {
7446 assert(LHS->getType()->isAnyPointerType());
7447 assert(RHS->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00007448 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00007449 ? diag::err_typecheck_pointer_arith_function_type
7450 : diag::ext_gnu_ptr_func_arith)
7451 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7452 // We only show the second type if it differs from the first.
7453 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7454 RHS->getType())
7455 << RHS->getType()->getPointeeType()
7456 << LHS->getSourceRange() << RHS->getSourceRange();
7457}
7458
7459/// \brief Diagnose invalid arithmetic on a function pointer.
7460static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7461 Expr *Pointer) {
7462 assert(Pointer->getType()->isAnyPointerType());
David Blaikie4e4d0842012-03-11 07:00:24 +00007463 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruth13b21be2011-06-27 08:02:19 +00007464 ? diag::err_typecheck_pointer_arith_function_type
7465 : diag::ext_gnu_ptr_func_arith)
7466 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7467 << 0 /* one pointer, so only one type */
7468 << Pointer->getSourceRange();
7469}
7470
Richard Trieud9f19342011-09-12 18:08:02 +00007471/// \brief Emit error if Operand is incomplete pointer type
Richard Trieu097ecd22011-09-02 02:15:37 +00007472///
7473/// \returns True if pointer has incomplete type
7474static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7475 Expr *Operand) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007476 QualType ResType = Operand->getType();
7477 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7478 ResType = ResAtomicType->getValueType();
7479
7480 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7481 QualType PointeeTy = ResType->getPointeeType();
John McCall1503f0d2012-07-31 05:14:30 +00007482 return S.RequireCompleteType(Loc, PointeeTy,
7483 diag::err_typecheck_arithmetic_incomplete_type,
7484 PointeeTy, Operand->getSourceRange());
Richard Trieu097ecd22011-09-02 02:15:37 +00007485}
7486
Chandler Carruth13b21be2011-06-27 08:02:19 +00007487/// \brief Check the validity of an arithmetic pointer operand.
7488///
7489/// If the operand has pointer type, this code will check for pointer types
7490/// which are invalid in arithmetic operations. These will be diagnosed
7491/// appropriately, including whether or not the use is supported as an
7492/// extension.
7493///
7494/// \returns True when the operand is valid to use (even if as an extension).
7495static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7496 Expr *Operand) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007497 QualType ResType = Operand->getType();
7498 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7499 ResType = ResAtomicType->getValueType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007500
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007501 if (!ResType->isAnyPointerType()) return true;
7502
7503 QualType PointeeTy = ResType->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007504 if (PointeeTy->isVoidType()) {
7505 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00007506 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00007507 }
7508 if (PointeeTy->isFunctionType()) {
7509 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikie4e4d0842012-03-11 07:00:24 +00007510 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00007511 }
7512
Richard Trieu097ecd22011-09-02 02:15:37 +00007513 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruth13b21be2011-06-27 08:02:19 +00007514
7515 return true;
7516}
7517
7518/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7519/// operands.
7520///
7521/// This routine will diagnose any invalid arithmetic on pointer operands much
7522/// like \see checkArithmeticOpPointerOperand. However, it has special logic
7523/// for emitting a single diagnostic even for operations where both LHS and RHS
7524/// are (potentially problematic) pointers.
7525///
7526/// \returns True when the operand is valid to use (even if as an extension).
7527static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00007528 Expr *LHSExpr, Expr *RHSExpr) {
7529 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7530 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007531 if (!isLHSPointer && !isRHSPointer) return true;
7532
7533 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieudef75842011-09-06 21:13:51 +00007534 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7535 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007536
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007537 // if both are pointers check if operation is valid wrt address spaces
7538 if (isLHSPointer && isRHSPointer) {
7539 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7540 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7541 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7542 S.Diag(Loc,
7543 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7544 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7545 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7546 return false;
7547 }
7548 }
7549
Chandler Carruth13b21be2011-06-27 08:02:19 +00007550 // Check for arithmetic on pointers to incomplete types.
7551 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7552 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7553 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00007554 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7555 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7556 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00007557
David Blaikie4e4d0842012-03-11 07:00:24 +00007558 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00007559 }
7560
7561 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7562 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7563 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieudef75842011-09-06 21:13:51 +00007564 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7565 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7566 RHSExpr);
7567 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruth13b21be2011-06-27 08:02:19 +00007568
David Blaikie4e4d0842012-03-11 07:00:24 +00007569 return !S.getLangOpts().CPlusPlus;
Chandler Carruth13b21be2011-06-27 08:02:19 +00007570 }
7571
John McCall1503f0d2012-07-31 05:14:30 +00007572 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7573 return false;
7574 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7575 return false;
Richard Trieu097ecd22011-09-02 02:15:37 +00007576
Chandler Carruth13b21be2011-06-27 08:02:19 +00007577 return true;
7578}
7579
Nico Weber1cb2d742012-03-02 22:01:22 +00007580/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7581/// literal.
7582static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7583 Expr *LHSExpr, Expr *RHSExpr) {
7584 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7585 Expr* IndexExpr = RHSExpr;
7586 if (!StrExpr) {
7587 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7588 IndexExpr = LHSExpr;
7589 }
7590
7591 bool IsStringPlusInt = StrExpr &&
7592 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007593 if (!IsStringPlusInt || IndexExpr->isValueDependent())
Nico Weber1cb2d742012-03-02 22:01:22 +00007594 return;
7595
7596 llvm::APSInt index;
7597 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7598 unsigned StrLenWithNull = StrExpr->getLength() + 1;
7599 if (index.isNonNegative() &&
7600 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7601 index.isUnsigned()))
7602 return;
7603 }
7604
7605 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7606 Self.Diag(OpLoc, diag::warn_string_plus_int)
7607 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7608
7609 // Only print a fixit for "str" + int, not for int + "str".
7610 if (IndexExpr == RHSExpr) {
7611 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
Jordan Rose02debf62013-10-25 16:52:00 +00007612 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
Nico Weber1cb2d742012-03-02 22:01:22 +00007613 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7614 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7615 << FixItHint::CreateInsertion(EndLoc, "]");
7616 } else
Jordan Rose02debf62013-10-25 16:52:00 +00007617 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7618}
7619
7620/// \brief Emit a warning when adding a char literal to a string.
7621static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7622 Expr *LHSExpr, Expr *RHSExpr) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007623 const Expr *StringRefExpr = LHSExpr;
Jordan Rose02debf62013-10-25 16:52:00 +00007624 const CharacterLiteral *CharExpr =
7625 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007626
7627 if (!CharExpr) {
Jordan Rose02debf62013-10-25 16:52:00 +00007628 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007629 StringRefExpr = RHSExpr;
Jordan Rose02debf62013-10-25 16:52:00 +00007630 }
7631
7632 if (!CharExpr || !StringRefExpr)
7633 return;
7634
7635 const QualType StringType = StringRefExpr->getType();
7636
7637 // Return if not a PointerType.
7638 if (!StringType->isAnyPointerType())
7639 return;
7640
7641 // Return if not a CharacterType.
7642 if (!StringType->getPointeeType()->isAnyCharacterType())
7643 return;
7644
7645 ASTContext &Ctx = Self.getASTContext();
7646 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7647
7648 const QualType CharType = CharExpr->getType();
7649 if (!CharType->isAnyCharacterType() &&
7650 CharType->isIntegerType() &&
7651 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7652 Self.Diag(OpLoc, diag::warn_string_plus_char)
7653 << DiagRange << Ctx.CharTy;
7654 } else {
7655 Self.Diag(OpLoc, diag::warn_string_plus_char)
7656 << DiagRange << CharExpr->getType();
7657 }
7658
7659 // Only print a fixit for str + char, not for char + str.
7660 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7661 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7662 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7663 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7664 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7665 << FixItHint::CreateInsertion(EndLoc, "]");
7666 } else {
7667 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7668 }
Nico Weber1cb2d742012-03-02 22:01:22 +00007669}
7670
Richard Trieud9f19342011-09-12 18:08:02 +00007671/// \brief Emit error when two pointers are incompatible.
Richard Trieudb44a6b2011-09-01 22:53:23 +00007672static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieudef75842011-09-06 21:13:51 +00007673 Expr *LHSExpr, Expr *RHSExpr) {
7674 assert(LHSExpr->getType()->isAnyPointerType());
7675 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieudb44a6b2011-09-01 22:53:23 +00007676 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieudef75842011-09-06 21:13:51 +00007677 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7678 << RHSExpr->getSourceRange();
Richard Trieudb44a6b2011-09-01 22:53:23 +00007679}
7680
Chris Lattner7ef655a2010-01-12 21:23:57 +00007681QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weber1cb2d742012-03-02 22:01:22 +00007682 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7683 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00007684 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7685
Richard Trieudef75842011-09-06 21:13:51 +00007686 if (LHS.get()->getType()->isVectorType() ||
7687 RHS.get()->getType()->isVectorType()) {
7688 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007689 if (CompLHSTy) *CompLHSTy = compType;
7690 return compType;
7691 }
Steve Naroff49b45262007-07-13 16:58:59 +00007692
Richard Trieudef75842011-09-06 21:13:51 +00007693 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7694 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007695 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00007696
Jordan Rose02debf62013-10-25 16:52:00 +00007697 // Diagnose "string literal" '+' int and string '+' "char literal".
7698 if (Opc == BO_Add) {
Nico Weber1cb2d742012-03-02 22:01:22 +00007699 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
Jordan Rose02debf62013-10-25 16:52:00 +00007700 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7701 }
Nico Weber1cb2d742012-03-02 22:01:22 +00007702
Reid Spencer5f016e22007-07-11 17:01:13 +00007703 // handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00007704 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007705 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007706 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007707 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007708
John McCall1503f0d2012-07-31 05:14:30 +00007709 // Type-checking. Ultimately the pointer's going to be in PExp;
7710 // note that we bias towards the LHS being the pointer.
7711 Expr *PExp = LHS.get(), *IExp = RHS.get();
Eli Friedmand72d16e2008-05-18 18:08:51 +00007712
John McCall1503f0d2012-07-31 05:14:30 +00007713 bool isObjCPointer;
7714 if (PExp->getType()->isPointerType()) {
7715 isObjCPointer = false;
7716 } else if (PExp->getType()->isObjCObjectPointerType()) {
7717 isObjCPointer = true;
7718 } else {
7719 std::swap(PExp, IExp);
7720 if (PExp->getType()->isPointerType()) {
7721 isObjCPointer = false;
7722 } else if (PExp->getType()->isObjCObjectPointerType()) {
7723 isObjCPointer = true;
7724 } else {
7725 return InvalidOperands(Loc, LHS, RHS);
7726 }
7727 }
7728 assert(PExp->getType()->isAnyPointerType());
Chandler Carruth13b21be2011-06-27 08:02:19 +00007729
Richard Trieu6eef9fb2011-09-12 18:37:54 +00007730 if (!IExp->getType()->isIntegerType())
7731 return InvalidOperands(Loc, LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00007732
Richard Trieu6eef9fb2011-09-12 18:37:54 +00007733 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7734 return QualType();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007735
John McCall1503f0d2012-07-31 05:14:30 +00007736 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
Richard Trieu6eef9fb2011-09-12 18:37:54 +00007737 return QualType();
7738
7739 // Check array bounds for pointer arithemtic
7740 CheckArrayAccess(PExp, IExp);
7741
7742 if (CompLHSTy) {
7743 QualType LHSTy = Context.isPromotableBitField(LHS.get());
7744 if (LHSTy.isNull()) {
7745 LHSTy = LHS.get()->getType();
7746 if (LHSTy->isPromotableIntegerType())
7747 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00007748 }
Richard Trieu6eef9fb2011-09-12 18:37:54 +00007749 *CompLHSTy = LHSTy;
Eli Friedmand72d16e2008-05-18 18:08:51 +00007750 }
7751
Richard Trieu6eef9fb2011-09-12 18:37:54 +00007752 return PExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007753}
7754
Chris Lattnereca7be62008-04-07 05:30:13 +00007755// C99 6.5.6
Richard Trieudef75842011-09-06 21:13:51 +00007756QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00007757 SourceLocation Loc,
7758 QualType* CompLHSTy) {
Richard Trieu481037f2011-09-16 00:53:10 +00007759 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7760
Richard Trieudef75842011-09-06 21:13:51 +00007761 if (LHS.get()->getType()->isVectorType() ||
7762 RHS.get()->getType()->isVectorType()) {
7763 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007764 if (CompLHSTy) *CompLHSTy = compType;
7765 return compType;
7766 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007767
Richard Trieudef75842011-09-06 21:13:51 +00007768 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7769 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00007770 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007771
Chris Lattner6e4ab612007-12-09 21:53:25 +00007772 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007773
Chris Lattner6e4ab612007-12-09 21:53:25 +00007774 // Handle the common case first (both operands are arithmetic).
Eli Friedman860a3192012-06-16 02:19:17 +00007775 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007776 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007777 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007778 }
Mike Stump1eb44332009-09-09 15:08:12 +00007779
Chris Lattner6e4ab612007-12-09 21:53:25 +00007780 // Either ptr - int or ptr - ptr.
Richard Trieudef75842011-09-06 21:13:51 +00007781 if (LHS.get()->getType()->isAnyPointerType()) {
7782 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007783
Chris Lattnerb5f15622009-04-24 23:50:08 +00007784 // Diagnose bad cases where we step over interface counts.
John McCall1503f0d2012-07-31 05:14:30 +00007785 if (LHS.get()->getType()->isObjCObjectPointerType() &&
7786 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
Chris Lattnerb5f15622009-04-24 23:50:08 +00007787 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00007788
Chris Lattner6e4ab612007-12-09 21:53:25 +00007789 // The result type of a pointer-int computation is the pointer type.
Richard Trieudef75842011-09-06 21:13:51 +00007790 if (RHS.get()->getType()->isIntegerType()) {
7791 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00007792 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007793
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007794 // Check array bounds for pointer arithemtic
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007795 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
Richard Smith25b009a2011-12-16 19:31:14 +00007796 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007797
Richard Trieudef75842011-09-06 21:13:51 +00007798 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7799 return LHS.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007800 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007801
Chris Lattner6e4ab612007-12-09 21:53:25 +00007802 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00007803 if (const PointerType *RHSPTy
Richard Trieudef75842011-09-06 21:13:51 +00007804 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007805 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007806
David Blaikie4e4d0842012-03-11 07:00:24 +00007807 if (getLangOpts().CPlusPlus) {
Eli Friedman88d936b2009-05-16 13:54:38 +00007808 // Pointee types must be the same: C++ [expr.add]
7809 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieudef75842011-09-06 21:13:51 +00007810 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00007811 }
7812 } else {
7813 // Pointee types must be compatible C99 6.5.6p3
7814 if (!Context.typesAreCompatible(
7815 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7816 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieudef75842011-09-06 21:13:51 +00007817 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman88d936b2009-05-16 13:54:38 +00007818 return QualType();
7819 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007820 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007821
Chandler Carruth13b21be2011-06-27 08:02:19 +00007822 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieudef75842011-09-06 21:13:51 +00007823 LHS.get(), RHS.get()))
Chandler Carruth13b21be2011-06-27 08:02:19 +00007824 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007825
Richard Smith812d6bc2013-09-10 21:34:14 +00007826 // The pointee type may have zero size. As an extension, a structure or
7827 // union may have zero size or an array may have zero length. In this
7828 // case subtraction does not make sense.
7829 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7830 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7831 if (ElementSize.isZero()) {
7832 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7833 << rpointee.getUnqualifiedType()
7834 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7835 }
7836 }
7837
Richard Trieudef75842011-09-06 21:13:51 +00007838 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007839 return Context.getPointerDiffType();
7840 }
7841 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007842
Richard Trieudef75842011-09-06 21:13:51 +00007843 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00007844}
7845
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007846static bool isScopedEnumerationType(QualType T) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007847 if (const EnumType *ET = T->getAs<EnumType>())
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007848 return ET->getDecl()->isScoped();
7849 return false;
7850}
7851
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007852static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth21206d52011-02-23 23:34:11 +00007853 SourceLocation Loc, unsigned Opc,
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007854 QualType LHSType) {
David Tweed7a834212013-01-07 16:43:27 +00007855 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7856 // so skip remaining warnings as we don't want to modify values within Sema.
7857 if (S.getLangOpts().OpenCL)
7858 return;
7859
Chandler Carruth21206d52011-02-23 23:34:11 +00007860 llvm::APSInt Right;
7861 // Check right/shifter operand
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007862 if (RHS.get()->isValueDependent() ||
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07007863 !RHS.get()->EvaluateAsInt(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007864 return;
7865
7866 if (Right.isNegative()) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007867 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007868 S.PDiag(diag::warn_shift_negative)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007869 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007870 return;
7871 }
7872 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007873 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007874 if (Right.uge(LeftBits)) {
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007875 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007876 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007877 << RHS.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007878 return;
7879 }
7880 if (Opc != BO_Shl)
7881 return;
7882
7883 // When left shifting an ICE which is signed, we can check for overflow which
7884 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7885 // integers have defined behavior modulo one more than the maximum value
7886 // representable in the result type, so never warn for those.
7887 llvm::APSInt Left;
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007888 if (LHS.get()->isValueDependent() ||
7889 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7890 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth21206d52011-02-23 23:34:11 +00007891 return;
7892 llvm::APInt ResultBits =
7893 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7894 if (LeftBits.uge(ResultBits))
7895 return;
7896 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7897 Result = Result.shl(Right);
7898
Ted Kremenekfa821382011-06-15 00:54:52 +00007899 // Print the bit representation of the signed integer as an unsigned
7900 // hexadecimal number.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007901 SmallString<40> HexResult;
Ted Kremenekfa821382011-06-15 00:54:52 +00007902 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7903
Chandler Carruth21206d52011-02-23 23:34:11 +00007904 // If we are only missing a sign bit, this is less likely to result in actual
7905 // bugs -- if the result is cast back to an unsigned type, it will have the
7906 // expected value. Thus we place this behind a different warning that can be
7907 // turned off separately if needed.
7908 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00007909 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07007910 << HexResult << LHSType
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007911 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007912 return;
7913 }
7914
7915 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007916 << HexResult.str() << Result.getMinSignedBits() << LHSType
7917 << Left.getBitWidth() << LHS.get()->getSourceRange()
7918 << RHS.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007919}
7920
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007921/// \brief Return the resulting type when an OpenCL vector is shifted
7922/// by a scalar or vector shift amount.
7923static QualType checkOpenCLVectorShift(Sema &S,
7924 ExprResult &LHS, ExprResult &RHS,
7925 SourceLocation Loc, bool IsCompAssign) {
7926 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
7927 if (!LHS.get()->getType()->isVectorType()) {
7928 S.Diag(Loc, diag::err_shift_rhs_only_vector)
7929 << RHS.get()->getType() << LHS.get()->getType()
7930 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7931 return QualType();
7932 }
7933
7934 if (!IsCompAssign) {
7935 LHS = S.UsualUnaryConversions(LHS.get());
7936 if (LHS.isInvalid()) return QualType();
7937 }
7938
7939 RHS = S.UsualUnaryConversions(RHS.get());
7940 if (RHS.isInvalid()) return QualType();
7941
7942 QualType LHSType = LHS.get()->getType();
7943 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
7944 QualType LHSEleType = LHSVecTy->getElementType();
7945
7946 // Note that RHS might not be a vector.
7947 QualType RHSType = RHS.get()->getType();
7948 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
7949 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
7950
7951 // OpenCL v1.1 s6.3.j says that the operands need to be integers.
7952 if (!LHSEleType->isIntegerType()) {
7953 S.Diag(Loc, diag::err_typecheck_expect_int)
7954 << LHS.get()->getType() << LHS.get()->getSourceRange();
7955 return QualType();
7956 }
7957
7958 if (!RHSEleType->isIntegerType()) {
7959 S.Diag(Loc, diag::err_typecheck_expect_int)
7960 << RHS.get()->getType() << RHS.get()->getSourceRange();
7961 return QualType();
7962 }
7963
7964 if (RHSVecTy) {
7965 // OpenCL v1.1 s6.3.j says that for vector types, the operators
7966 // are applied component-wise. So if RHS is a vector, then ensure
7967 // that the number of elements is the same as LHS...
7968 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
7969 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
7970 << LHS.get()->getType() << RHS.get()->getType()
7971 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7972 return QualType();
7973 }
7974 } else {
7975 // ...else expand RHS to match the number of elements in LHS.
7976 QualType VecTy =
7977 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
7978 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
7979 }
7980
7981 return LHSType;
7982}
7983
Chris Lattnereca7be62008-04-07 05:30:13 +00007984// C99 6.5.7
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007985QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00007986 SourceLocation Loc, unsigned Opc,
Richard Trieuccd891a2011-09-09 01:45:06 +00007987 bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00007988 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7989
Nate Begeman2207d792009-10-25 02:26:48 +00007990 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00007991 if (LHS.get()->getType()->isVectorType() ||
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007992 RHS.get()->getType()->isVectorType()) {
7993 if (LangOpts.OpenCL)
7994 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
Richard Trieuccd891a2011-09-09 01:45:06 +00007995 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007996 }
Nate Begeman2207d792009-10-25 02:26:48 +00007997
Chris Lattnerca5eede2007-12-12 05:47:28 +00007998 // Shifts don't perform usual arithmetic conversions, they just do integer
7999 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00008000
John McCall1bc80af2010-12-16 19:28:59 +00008001 // For the LHS, do usual unary conversions, but then reset them away
8002 // if this is a compound assignment.
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00008003 ExprResult OldLHS = LHS;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008004 LHS = UsualUnaryConversions(LHS.get());
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00008005 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008006 return QualType();
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00008007 QualType LHSType = LHS.get()->getType();
Richard Trieuccd891a2011-09-09 01:45:06 +00008008 if (IsCompAssign) LHS = OldLHS;
John McCall1bc80af2010-12-16 19:28:59 +00008009
8010 // The RHS is simpler.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008011 RHS = UsualUnaryConversions(RHS.get());
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00008012 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008013 return QualType();
Douglas Gregor236d9d162013-04-16 15:41:08 +00008014 QualType RHSType = RHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008015
Douglas Gregor236d9d162013-04-16 15:41:08 +00008016 // C99 6.5.7p2: Each of the operands shall have integer type.
8017 if (!LHSType->hasIntegerRepresentation() ||
8018 !RHSType->hasIntegerRepresentation())
8019 return InvalidOperands(Loc, LHS, RHS);
8020
8021 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8022 // hasIntegerRepresentation() above instead of this.
8023 if (isScopedEnumerationType(LHSType) ||
8024 isScopedEnumerationType(RHSType)) {
8025 return InvalidOperands(Loc, LHS, RHS);
8026 }
Ryan Flynnd0439682009-08-07 16:20:20 +00008027 // Sanity-check shift operands
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00008028 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnd0439682009-08-07 16:20:20 +00008029
Chris Lattnerca5eede2007-12-12 05:47:28 +00008030 // "The type of the result is that of the promoted left operand."
Richard Trieu1c8cfbf2011-09-06 21:21:28 +00008031 return LHSType;
Reid Spencer5f016e22007-07-11 17:01:13 +00008032}
8033
Chandler Carruth99919472010-07-10 12:30:03 +00008034static bool IsWithinTemplateSpecialization(Decl *D) {
8035 if (DeclContext *DC = D->getDeclContext()) {
8036 if (isa<ClassTemplateSpecializationDecl>(DC))
8037 return true;
8038 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8039 return FD->isFunctionTemplateSpecialization();
8040 }
8041 return false;
8042}
8043
Richard Trieue648ac32011-09-02 03:48:46 +00008044/// If two different enums are compared, raise a warning.
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00008045static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8046 Expr *RHS) {
8047 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8048 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
Richard Trieue648ac32011-09-02 03:48:46 +00008049
8050 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8051 if (!LHSEnumType)
8052 return;
8053 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8054 if (!RHSEnumType)
8055 return;
8056
8057 // Ignore anonymous enums.
8058 if (!LHSEnumType->getDecl()->getIdentifier())
8059 return;
8060 if (!RHSEnumType->getDecl()->getIdentifier())
8061 return;
8062
8063 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8064 return;
8065
8066 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8067 << LHSStrippedType << RHSStrippedType
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00008068 << LHS->getSourceRange() << RHS->getSourceRange();
Richard Trieue648ac32011-09-02 03:48:46 +00008069}
8070
Richard Trieu7be1be02011-09-02 02:55:45 +00008071/// \brief Diagnose bad pointer comparisons.
8072static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00008073 ExprResult &LHS, ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00008074 bool IsError) {
8075 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieu7be1be02011-09-02 02:55:45 +00008076 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieuba261492011-09-06 21:27:33 +00008077 << LHS.get()->getType() << RHS.get()->getType()
8078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00008079}
8080
8081/// \brief Returns false if the pointers are converted to a composite type,
8082/// true otherwise.
8083static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00008084 ExprResult &LHS, ExprResult &RHS) {
Richard Trieu7be1be02011-09-02 02:55:45 +00008085 // C++ [expr.rel]p2:
8086 // [...] Pointer conversions (4.10) and qualification
8087 // conversions (4.4) are performed on pointer operands (or on
8088 // a pointer operand and a null pointer constant) to bring
8089 // them to their composite pointer type. [...]
8090 //
8091 // C++ [expr.eq]p1 uses the same notion for (in)equality
8092 // comparisons of pointers.
8093
8094 // C++ [expr.eq]p2:
8095 // In addition, pointers to members can be compared, or a pointer to
8096 // member and a null pointer constant. Pointer to member conversions
8097 // (4.11) and qualification conversions (4.4) are performed to bring
8098 // them to a common type. If one operand is a null pointer constant,
8099 // the common type is the type of the other operand. Otherwise, the
8100 // common type is a pointer to member type similar (4.4) to the type
8101 // of one of the operands, with a cv-qualification signature (4.4)
8102 // that is the union of the cv-qualification signatures of the operand
8103 // types.
8104
Richard Trieuba261492011-09-06 21:27:33 +00008105 QualType LHSType = LHS.get()->getType();
8106 QualType RHSType = RHS.get()->getType();
8107 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8108 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieu7be1be02011-09-02 02:55:45 +00008109
8110 bool NonStandardCompositeType = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008111 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
Richard Trieuba261492011-09-06 21:27:33 +00008112 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieu7be1be02011-09-02 02:55:45 +00008113 if (T.isNull()) {
Richard Trieuba261492011-09-06 21:27:33 +00008114 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieu7be1be02011-09-02 02:55:45 +00008115 return true;
8116 }
8117
8118 if (NonStandardCompositeType)
8119 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieuba261492011-09-06 21:27:33 +00008120 << LHSType << RHSType << T << LHS.get()->getSourceRange()
8121 << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00008122
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008123 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8124 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
Richard Trieu7be1be02011-09-02 02:55:45 +00008125 return false;
8126}
8127
8128static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieuba261492011-09-06 21:27:33 +00008129 ExprResult &LHS,
8130 ExprResult &RHS,
Richard Trieuccd891a2011-09-09 01:45:06 +00008131 bool IsError) {
8132 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8133 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieuba261492011-09-06 21:27:33 +00008134 << LHS.get()->getType() << RHS.get()->getType()
8135 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieu7be1be02011-09-02 02:55:45 +00008136}
8137
Jordan Rose9f63a452012-06-08 21:14:25 +00008138static bool isObjCObjectLiteral(ExprResult &E) {
Jordan Rose87da0b72012-11-09 23:55:21 +00008139 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
Jordan Rose9f63a452012-06-08 21:14:25 +00008140 case Stmt::ObjCArrayLiteralClass:
8141 case Stmt::ObjCDictionaryLiteralClass:
8142 case Stmt::ObjCStringLiteralClass:
8143 case Stmt::ObjCBoxedExprClass:
8144 return true;
8145 default:
8146 // Note that ObjCBoolLiteral is NOT an object literal!
8147 return false;
8148 }
8149}
8150
Jordan Rose8d872ca2012-07-17 17:46:40 +00008151static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
Benjamin Kramer2e85e742013-02-15 15:17:50 +00008152 const ObjCObjectPointerType *Type =
8153 LHS->getType()->getAs<ObjCObjectPointerType>();
8154
8155 // If this is not actually an Objective-C object, bail out.
8156 if (!Type)
Jordan Rose8d872ca2012-07-17 17:46:40 +00008157 return false;
Benjamin Kramer2e85e742013-02-15 15:17:50 +00008158
8159 // Get the LHS object's interface type.
8160 QualType InterfaceType = Type->getPointeeType();
8161 if (const ObjCObjectType *iQFaceTy =
8162 InterfaceType->getAsObjCQualifiedInterfaceType())
8163 InterfaceType = iQFaceTy->getBaseType();
Jordan Rose8d872ca2012-07-17 17:46:40 +00008164
8165 // If the RHS isn't an Objective-C object, bail out.
8166 if (!RHS->getType()->isObjCObjectPointerType())
8167 return false;
8168
8169 // Try to find the -isEqual: method.
8170 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8171 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8172 InterfaceType,
8173 /*instance=*/true);
8174 if (!Method) {
8175 if (Type->isObjCIdType()) {
8176 // For 'id', just check the global pool.
8177 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07008178 /*receiverId=*/true);
Jordan Rose8d872ca2012-07-17 17:46:40 +00008179 } else {
8180 // Check protocols.
Benjamin Kramer2e85e742013-02-15 15:17:50 +00008181 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
Jordan Rose8d872ca2012-07-17 17:46:40 +00008182 /*instance=*/true);
8183 }
8184 }
8185
8186 if (!Method)
8187 return false;
8188
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008189 QualType T = Method->parameters()[0]->getType();
Jordan Rose8d872ca2012-07-17 17:46:40 +00008190 if (!T->isObjCObjectPointerType())
8191 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -07008192
8193 QualType R = Method->getReturnType();
Jordan Rose8d872ca2012-07-17 17:46:40 +00008194 if (!R->isScalarType())
8195 return false;
8196
8197 return true;
8198}
8199
Ted Kremenek3ee069b2012-12-21 21:59:36 +00008200Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8201 FromE = FromE->IgnoreParenImpCasts();
8202 switch (FromE->getStmtClass()) {
8203 default:
8204 break;
8205 case Stmt::ObjCStringLiteralClass:
8206 // "string literal"
8207 return LK_String;
8208 case Stmt::ObjCArrayLiteralClass:
8209 // "array literal"
8210 return LK_Array;
8211 case Stmt::ObjCDictionaryLiteralClass:
8212 // "dictionary literal"
8213 return LK_Dictionary;
Ted Kremenekd3292c82012-12-21 22:46:35 +00008214 case Stmt::BlockExprClass:
8215 return LK_Block;
Ted Kremenek3ee069b2012-12-21 21:59:36 +00008216 case Stmt::ObjCBoxedExprClass: {
Ted Kremenekf530ff72012-12-21 21:59:39 +00008217 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
Ted Kremenek3ee069b2012-12-21 21:59:36 +00008218 switch (Inner->getStmtClass()) {
8219 case Stmt::IntegerLiteralClass:
8220 case Stmt::FloatingLiteralClass:
8221 case Stmt::CharacterLiteralClass:
8222 case Stmt::ObjCBoolLiteralExprClass:
8223 case Stmt::CXXBoolLiteralExprClass:
8224 // "numeric literal"
8225 return LK_Numeric;
8226 case Stmt::ImplicitCastExprClass: {
8227 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8228 // Boolean literals can be represented by implicit casts.
8229 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8230 return LK_Numeric;
8231 break;
8232 }
8233 default:
8234 break;
8235 }
8236 return LK_Boxed;
8237 }
8238 }
8239 return LK_None;
8240}
8241
Jordan Rose8d872ca2012-07-17 17:46:40 +00008242static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8243 ExprResult &LHS, ExprResult &RHS,
8244 BinaryOperator::Opcode Opc){
Jordan Rosed5209ae2012-07-17 17:46:48 +00008245 Expr *Literal;
8246 Expr *Other;
8247 if (isObjCObjectLiteral(LHS)) {
8248 Literal = LHS.get();
8249 Other = RHS.get();
8250 } else {
8251 Literal = RHS.get();
8252 Other = LHS.get();
8253 }
8254
8255 // Don't warn on comparisons against nil.
8256 Other = Other->IgnoreParenCasts();
8257 if (Other->isNullPointerConstant(S.getASTContext(),
8258 Expr::NPC_ValueDependentIsNotNull))
8259 return;
Jordan Rose9f63a452012-06-08 21:14:25 +00008260
Jordan Roseeec207f2012-07-17 17:46:44 +00008261 // This should be kept in sync with warn_objc_literal_comparison.
Ted Kremenek3ee069b2012-12-21 21:59:36 +00008262 // LK_String should always be after the other literals, since it has its own
8263 // warning flag.
8264 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
Ted Kremenekd3292c82012-12-21 22:46:35 +00008265 assert(LiteralKind != Sema::LK_Block);
Ted Kremenek3ee069b2012-12-21 21:59:36 +00008266 if (LiteralKind == Sema::LK_None) {
Jordan Rose9f63a452012-06-08 21:14:25 +00008267 llvm_unreachable("Unknown Objective-C object literal kind");
8268 }
8269
Ted Kremenek3ee069b2012-12-21 21:59:36 +00008270 if (LiteralKind == Sema::LK_String)
Jordan Roseeec207f2012-07-17 17:46:44 +00008271 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8272 << Literal->getSourceRange();
8273 else
8274 S.Diag(Loc, diag::warn_objc_literal_comparison)
8275 << LiteralKind << Literal->getSourceRange();
Jordan Rose9f63a452012-06-08 21:14:25 +00008276
Jordan Rose8d872ca2012-07-17 17:46:40 +00008277 if (BinaryOperator::isEqualityOp(Opc) &&
8278 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8279 SourceLocation Start = LHS.get()->getLocStart();
8280 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
Fariborz Jahanian41f7b1a2013-02-01 20:04:49 +00008281 CharSourceRange OpRange =
8282 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
Jordan Rose6deae7c2012-07-09 16:54:44 +00008283
Jordan Rose8d872ca2012-07-17 17:46:40 +00008284 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8285 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
Fariborz Jahanian41f7b1a2013-02-01 20:04:49 +00008286 << FixItHint::CreateReplacement(OpRange, " isEqual:")
Jordan Rose8d872ca2012-07-17 17:46:40 +00008287 << FixItHint::CreateInsertion(End, "]");
Jordan Rose9f63a452012-06-08 21:14:25 +00008288 }
Jordan Rose9f63a452012-06-08 21:14:25 +00008289}
8290
Richard Trieuef0e4e62013-06-10 18:52:07 +00008291static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8292 ExprResult &RHS,
8293 SourceLocation Loc,
8294 unsigned OpaqueOpc) {
8295 // This checking requires bools.
8296 if (!S.getLangOpts().Bool) return;
8297
8298 // Check that left hand side is !something.
Richard Trieu14b7673b2013-07-04 00:50:18 +00008299 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
Richard Trieuef0e4e62013-06-10 18:52:07 +00008300 if (!UO || UO->getOpcode() != UO_LNot) return;
8301
8302 // Only check if the right hand side is non-bool arithmetic type.
8303 if (RHS.get()->getType()->isBooleanType()) return;
8304
8305 // Make sure that the something in !something is not bool.
8306 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8307 if (SubExpr->getType()->isBooleanType()) return;
8308
8309 // Emit warning.
8310 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8311 << Loc;
8312
8313 // First note suggest !(x < y)
8314 SourceLocation FirstOpen = SubExpr->getLocStart();
8315 SourceLocation FirstClose = RHS.get()->getLocEnd();
8316 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
Eli Friedman4e16bf22013-07-22 23:09:39 +00008317 if (FirstClose.isInvalid())
8318 FirstOpen = SourceLocation();
Richard Trieuef0e4e62013-06-10 18:52:07 +00008319 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8320 << FixItHint::CreateInsertion(FirstOpen, "(")
8321 << FixItHint::CreateInsertion(FirstClose, ")");
8322
8323 // Second note suggests (!x) < y
8324 SourceLocation SecondOpen = LHS.get()->getLocStart();
8325 SourceLocation SecondClose = LHS.get()->getLocEnd();
8326 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
Eli Friedman4e16bf22013-07-22 23:09:39 +00008327 if (SecondClose.isInvalid())
8328 SecondOpen = SourceLocation();
Richard Trieuef0e4e62013-06-10 18:52:07 +00008329 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8330 << FixItHint::CreateInsertion(SecondOpen, "(")
8331 << FixItHint::CreateInsertion(SecondClose, ")");
8332}
8333
Eli Friedman9c5716c2013-09-06 03:13:09 +00008334// Get the decl for a simple expression: a reference to a variable,
8335// an implicit C++ field reference, or an implicit ObjC ivar reference.
8336static ValueDecl *getCompareDecl(Expr *E) {
8337 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8338 return DR->getDecl();
8339 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8340 if (Ivar->isFreeIvar())
8341 return Ivar->getDecl();
8342 }
8343 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8344 if (Mem->isImplicitAccess())
8345 return Mem->getMemberDecl();
8346 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008347 return nullptr;
Eli Friedman9c5716c2013-09-06 03:13:09 +00008348}
8349
Douglas Gregor0c6db942009-05-04 06:07:12 +00008350// C99 6.5.8, C++ [expr.rel]
Richard Trieuf1775fb2011-09-06 21:43:51 +00008351QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00008352 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008353 bool IsRelational) {
Richard Trieu481037f2011-09-16 00:53:10 +00008354 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8355
John McCall2de56d12010-08-25 11:45:40 +00008356 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00008357
Chris Lattner02dd4b12009-12-05 05:40:13 +00008358 // Handle vector comparisons separately.
Richard Trieuf1775fb2011-09-06 21:43:51 +00008359 if (LHS.get()->getType()->isVectorType() ||
8360 RHS.get()->getType()->isVectorType())
Richard Trieuccd891a2011-09-09 01:45:06 +00008361 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008362
Richard Trieuf1775fb2011-09-06 21:43:51 +00008363 QualType LHSType = LHS.get()->getType();
8364 QualType RHSType = RHS.get()->getType();
Benjamin Kramerfec09592011-09-03 08:46:20 +00008365
Richard Trieuf1775fb2011-09-06 21:43:51 +00008366 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8367 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00008368
Ted Kremenek16bdd3b2013-01-30 19:10:21 +00008369 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
Richard Trieuef0e4e62013-06-10 18:52:07 +00008370 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
Chandler Carruth543cb652011-02-17 08:37:06 +00008371
Richard Trieuf1775fb2011-09-06 21:43:51 +00008372 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuccd891a2011-09-09 01:45:06 +00008373 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008374 !LHS.get()->getLocStart().isMacroID() &&
Richard Trieu54237462013-11-02 02:11:23 +00008375 !RHS.get()->getLocStart().isMacroID() &&
8376 ActiveTemplateInstantiations.empty()) {
Chris Lattner55660a72009-03-08 19:39:53 +00008377 // For non-floating point types, check for self-comparisons of the form
8378 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
8379 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00008380 //
8381 // NOTE: Don't warn about comparison expressions resulting from macro
8382 // expansion. Also don't warn about comparisons which are only self
8383 // comparisons within a template specialization. The warnings should catch
8384 // obvious cases in the definition of the template anyways. The idea is to
8385 // warn when the typed comparison operator will always evaluate to the same
8386 // result.
Eli Friedman9c5716c2013-09-06 03:13:09 +00008387 ValueDecl *DL = getCompareDecl(LHSStripped);
8388 ValueDecl *DR = getCompareDecl(RHSStripped);
8389 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008390 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman9c5716c2013-09-06 03:13:09 +00008391 << 0 // self-
8392 << (Opc == BO_EQ
8393 || Opc == BO_LE
8394 || Opc == BO_GE));
8395 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8396 !DL->getType()->isReferenceType() &&
8397 !DR->getType()->isReferenceType()) {
8398 // what is it always going to eval to?
8399 char always_evals_to;
8400 switch(Opc) {
8401 case BO_EQ: // e.g. array1 == array2
8402 always_evals_to = 0; // false
8403 break;
8404 case BO_NE: // e.g. array1 != array2
8405 always_evals_to = 1; // true
8406 break;
8407 default:
8408 // best we can say is 'a constant'
8409 always_evals_to = 2; // e.g. array1 <= array2
8410 break;
Douglas Gregord64fdd02010-06-08 19:50:34 +00008411 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008412 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
Eli Friedman9c5716c2013-09-06 03:13:09 +00008413 << 1 // array
8414 << always_evals_to);
Chandler Carruth99919472010-07-10 12:30:03 +00008415 }
Mike Stump1eb44332009-09-09 15:08:12 +00008416
Chris Lattner55660a72009-03-08 19:39:53 +00008417 if (isa<CastExpr>(LHSStripped))
8418 LHSStripped = LHSStripped->IgnoreParenCasts();
8419 if (isa<CastExpr>(RHSStripped))
8420 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00008421
Chris Lattner55660a72009-03-08 19:39:53 +00008422 // Warn about comparisons against a string constant (unless the other
8423 // operand is null), the user probably wants strcmp.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008424 Expr *literalString = nullptr;
8425 Expr *literalStringStripped = nullptr;
Chris Lattner55660a72009-03-08 19:39:53 +00008426 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008427 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00008428 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00008429 literalString = LHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00008430 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00008431 } else if ((isa<StringLiteral>(RHSStripped) ||
8432 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008433 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00008434 Expr::NPC_ValueDependentIsNull)) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00008435 literalString = RHS.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00008436 literalStringStripped = RHSStripped;
8437 }
8438
8439 if (literalString) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008440 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00008441 PDiag(diag::warn_stringcompare)
8442 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00008443 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00008444 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00008445 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008446
Douglas Gregord64fdd02010-06-08 19:50:34 +00008447 // C99 6.5.8p3 / C99 6.5.9p4
Eli Friedman09bddcf2013-07-08 20:20:06 +00008448 UsualArithmeticConversions(LHS, RHS);
8449 if (LHS.isInvalid() || RHS.isInvalid())
8450 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00008451
Richard Trieuf1775fb2011-09-06 21:43:51 +00008452 LHSType = LHS.get()->getType();
8453 RHSType = RHS.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00008454
Douglas Gregor447b69e2008-11-19 03:25:36 +00008455 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008456 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00008457
Richard Trieuccd891a2011-09-09 01:45:06 +00008458 if (IsRelational) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00008459 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00008460 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00008461 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00008462 // Check for comparisons of floating point operands using != and ==.
Richard Trieuf1775fb2011-09-06 21:43:51 +00008463 if (LHSType->hasFloatingRepresentation())
8464 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00008465
Richard Trieuf1775fb2011-09-06 21:43:51 +00008466 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00008467 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00008468 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008469
Stephen Hines651f13c2014-04-23 16:59:28 -07008470 const Expr::NullPointerConstantKind LHSNullKind =
8471 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8472 const Expr::NullPointerConstantKind RHSNullKind =
8473 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8474 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8475 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8476
8477 if (!IsRelational && LHSIsNull != RHSIsNull) {
8478 bool IsEquality = Opc == BO_EQ;
8479 if (RHSIsNull)
8480 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8481 RHS.get()->getSourceRange());
8482 else
8483 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8484 LHS.get()->getSourceRange());
8485 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008486
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008487 // All of the following pointer-related warnings are GCC extensions, except
8488 // when handling null pointer constants.
Richard Trieuf1775fb2011-09-06 21:43:51 +00008489 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00008490 QualType LCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00008491 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattnerbc896f52008-04-03 05:07:25 +00008492 QualType RCanPointeeTy =
John McCall1d9b3b22011-09-09 05:25:32 +00008493 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008494
David Blaikie4e4d0842012-03-11 07:00:24 +00008495 if (getLangOpts().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00008496 if (LCanPointeeTy == RCanPointeeTy)
8497 return ResultTy;
Richard Trieuccd891a2011-09-09 01:45:06 +00008498 if (!IsRelational &&
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00008499 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8500 // Valid unless comparison between non-null pointer and function pointer
8501 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008502 // In a SFINAE context, we treat this as a hard error to maintain
8503 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00008504 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8505 && !LHSIsNull && !RHSIsNull) {
Richard Trieu7be1be02011-09-02 02:55:45 +00008506 diagnoseFunctionPointerToVoidComparison(
David Blaikie0adb1752013-02-21 06:05:05 +00008507 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008508
8509 if (isSFINAEContext())
8510 return QualType();
8511
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008512 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00008513 return ResultTy;
8514 }
8515 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00008516
Richard Trieuf1775fb2011-09-06 21:43:51 +00008517 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor0c6db942009-05-04 06:07:12 +00008518 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00008519 else
8520 return ResultTy;
Douglas Gregor0c6db942009-05-04 06:07:12 +00008521 }
Eli Friedman3075e762009-08-23 00:27:47 +00008522 // C99 6.5.9p2 and C99 6.5.8p2
8523 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8524 RCanPointeeTy.getUnqualifiedType())) {
8525 // Valid unless a relational comparison of function pointers
Richard Trieuccd891a2011-09-09 01:45:06 +00008526 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman3075e762009-08-23 00:27:47 +00008527 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieuf1775fb2011-09-06 21:43:51 +00008528 << LHSType << RHSType << LHS.get()->getSourceRange()
8529 << RHS.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00008530 }
Richard Trieuccd891a2011-09-09 01:45:06 +00008531 } else if (!IsRelational &&
Eli Friedman3075e762009-08-23 00:27:47 +00008532 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8533 // Valid unless comparison between non-null pointer and function pointer
8534 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieu7be1be02011-09-02 02:55:45 +00008535 && !LHSIsNull && !RHSIsNull)
Richard Trieuf1775fb2011-09-06 21:43:51 +00008536 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00008537 /*isError*/false);
Eli Friedman3075e762009-08-23 00:27:47 +00008538 } else {
8539 // Invalid
Richard Trieuf1775fb2011-09-06 21:43:51 +00008540 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +00008541 }
John McCall34d6f932011-03-11 04:25:25 +00008542 if (LCanPointeeTy != RCanPointeeTy) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008543 const PointerType *lhsPtr = LHSType->getAs<PointerType>();
8544 if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8545 Diag(Loc,
8546 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8547 << LHSType << RHSType << 0 /* comparison */
8548 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8549 }
Stephen Hines651f13c2014-04-23 16:59:28 -07008550 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8551 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8552 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8553 : CK_BitCast;
John McCall34d6f932011-03-11 04:25:25 +00008554 if (LHSIsNull && !RHSIsNull)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008555 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
John McCall34d6f932011-03-11 04:25:25 +00008556 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008557 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
John McCall34d6f932011-03-11 04:25:25 +00008558 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00008559 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00008560 }
Mike Stump1eb44332009-09-09 15:08:12 +00008561
David Blaikie4e4d0842012-03-11 07:00:24 +00008562 if (getLangOpts().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00008563 // Comparison of nullptr_t with itself.
Richard Trieuf1775fb2011-09-06 21:43:51 +00008564 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlsson0c8209e2010-11-04 03:17:43 +00008565 return ResultTy;
8566
Mike Stump1eb44332009-09-09 15:08:12 +00008567 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00008568 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00008569 if (RHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008570 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00008571 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008572 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008573 RHS = ImpCastExprToType(RHS.get(), LHSType,
Richard Trieuf1775fb2011-09-06 21:43:51 +00008574 LHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00008575 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00008576 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00008577 return ResultTy;
8578 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00008579 if (LHSIsNull &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008580 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuccd891a2011-09-09 01:45:06 +00008581 (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008582 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008583 LHS = ImpCastExprToType(LHS.get(), RHSType,
Richard Trieuf1775fb2011-09-06 21:43:51 +00008584 RHSType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00008585 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00008586 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00008587 return ResultTy;
8588 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00008589
8590 // Comparison of member pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00008591 if (!IsRelational &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008592 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8593 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor20b3e992009-08-24 17:42:35 +00008594 return QualType();
Richard Trieu7be1be02011-09-02 02:55:45 +00008595 else
8596 return ResultTy;
Douglas Gregor20b3e992009-08-24 17:42:35 +00008597 }
Douglas Gregor90566c02011-03-01 17:16:20 +00008598
8599 // Handle scoped enumeration types specifically, since they don't promote
8600 // to integers.
Richard Trieuf1775fb2011-09-06 21:43:51 +00008601 if (LHS.get()->getType()->isEnumeralType() &&
8602 Context.hasSameUnqualifiedType(LHS.get()->getType(),
8603 RHS.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00008604 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00008605 }
Mike Stump1eb44332009-09-09 15:08:12 +00008606
Steve Naroff1c7d0672008-09-04 15:10:53 +00008607 // Handle block pointer types.
Richard Trieuccd891a2011-09-09 01:45:06 +00008608 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008609 RHSType->isBlockPointerType()) {
John McCall1d9b3b22011-09-09 05:25:32 +00008610 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8611 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008612
Steve Naroff1c7d0672008-09-04 15:10:53 +00008613 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00008614 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00008615 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00008616 << LHSType << RHSType << LHS.get()->getSourceRange()
8617 << RHS.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00008618 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008619 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00008620 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008621 }
John Wiegley429bb272011-04-08 18:41:53 +00008622
Steve Naroff59f53942008-09-28 01:11:11 +00008623 // Allow block pointers to be compared with null pointer constants.
Richard Trieuccd891a2011-09-09 01:45:06 +00008624 if (!IsRelational
Richard Trieuf1775fb2011-09-06 21:43:51 +00008625 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8626 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00008627 if (!LHSIsNull && !RHSIsNull) {
Richard Trieuf1775fb2011-09-06 21:43:51 +00008628 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00008629 ->getPointeeType()->isVoidType())
Richard Trieuf1775fb2011-09-06 21:43:51 +00008630 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00008631 ->getPointeeType()->isVoidType())))
8632 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieuf1775fb2011-09-06 21:43:51 +00008633 << LHSType << RHSType << LHS.get()->getSourceRange()
8634 << RHS.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00008635 }
John McCall34d6f932011-03-11 04:25:25 +00008636 if (LHSIsNull && !RHSIsNull)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008637 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCall1d9b3b22011-09-09 05:25:32 +00008638 RHSType->isPointerType() ? CK_BitCast
8639 : CK_AnyPointerToBlockPointerCast);
John McCall34d6f932011-03-11 04:25:25 +00008640 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008641 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCall1d9b3b22011-09-09 05:25:32 +00008642 LHSType->isPointerType() ? CK_BitCast
8643 : CK_AnyPointerToBlockPointerCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00008644 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00008645 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00008646
Richard Trieuf1775fb2011-09-06 21:43:51 +00008647 if (LHSType->isObjCObjectPointerType() ||
8648 RHSType->isObjCObjectPointerType()) {
8649 const PointerType *LPT = LHSType->getAs<PointerType>();
8650 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall34d6f932011-03-11 04:25:25 +00008651 if (LPT || RPT) {
8652 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8653 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008654
Steve Naroffa8069f12008-11-17 19:49:16 +00008655 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieuf1775fb2011-09-06 21:43:51 +00008656 !Context.typesAreCompatible(LHSType, RHSType)) {
8657 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00008658 /*isError*/false);
Steve Naroffa5ad8632008-10-27 10:33:19 +00008659 }
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00008660 if (LHSIsNull && !RHSIsNull) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008661 Expr *E = LHS.get();
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00008662 if (getLangOpts().ObjCAutoRefCount)
8663 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8664 LHS = ImpCastExprToType(E, RHSType,
John McCall1d9b3b22011-09-09 05:25:32 +00008665 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00008666 }
8667 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008668 Expr *E = RHS.get();
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00008669 if (getLangOpts().ObjCAutoRefCount)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008670 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8671 Opc);
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00008672 RHS = ImpCastExprToType(E, LHSType,
John McCall1d9b3b22011-09-09 05:25:32 +00008673 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00008674 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00008675 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00008676 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00008677 if (LHSType->isObjCObjectPointerType() &&
8678 RHSType->isObjCObjectPointerType()) {
8679 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8680 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieu7be1be02011-09-02 02:55:45 +00008681 /*isError*/false);
Jordan Rose9f63a452012-06-08 21:14:25 +00008682 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
Jordan Rose8d872ca2012-07-17 17:46:40 +00008683 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
Jordan Rose9f63a452012-06-08 21:14:25 +00008684
John McCall34d6f932011-03-11 04:25:25 +00008685 if (LHSIsNull && !RHSIsNull)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008686 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00008687 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008688 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00008689 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00008690 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00008691 }
Richard Trieuf1775fb2011-09-06 21:43:51 +00008692 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8693 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00008694 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008695 bool isError = false;
Douglas Gregor6db351a2012-09-14 04:35:37 +00008696 if (LangOpts.DebuggerSupport) {
8697 // Under a debugger, allow the comparison of pointers to integers,
8698 // since users tend to want to compare addresses.
8699 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
Richard Trieuf1775fb2011-09-06 21:43:51 +00008700 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008701 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00008702 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikie4e4d0842012-03-11 07:00:24 +00008703 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00008704 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikie4e4d0842012-03-11 07:00:24 +00008705 else if (getLangOpts().CPlusPlus) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008706 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8707 isError = true;
8708 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00008709 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00008710
Chris Lattner06c0f5b2009-08-23 00:03:44 +00008711 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00008712 Diag(Loc, DiagID)
Richard Trieuf1775fb2011-09-06 21:43:51 +00008713 << LHSType << RHSType << LHS.get()->getSourceRange()
8714 << RHS.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008715 if (isError)
8716 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00008717 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008718
Richard Trieuf1775fb2011-09-06 21:43:51 +00008719 if (LHSType->isIntegerType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008720 LHS = ImpCastExprToType(LHS.get(), RHSType,
John McCall404cd162010-11-13 01:35:44 +00008721 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00008722 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008723 RHS = ImpCastExprToType(RHS.get(), LHSType,
John McCall404cd162010-11-13 01:35:44 +00008724 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00008725 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008726 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00008727
Steve Naroff39218df2008-09-04 16:56:14 +00008728 // Handle block pointers.
Richard Trieuccd891a2011-09-09 01:45:06 +00008729 if (!IsRelational && RHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00008730 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008731 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00008732 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00008733 }
Richard Trieuccd891a2011-09-09 01:45:06 +00008734 if (!IsRelational && LHSIsNull
Richard Trieuf1775fb2011-09-06 21:43:51 +00008735 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008736 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00008737 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00008738 }
Douglas Gregor90566c02011-03-01 17:16:20 +00008739
Richard Trieuf1775fb2011-09-06 21:43:51 +00008740 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00008741}
8742
Tanya Lattner4f692c22012-01-16 21:02:28 +00008743
8744// Return a signed type that is of identical size and number of elements.
8745// For floating point vectors, return an integer type of identical size
8746// and number of elements.
8747QualType Sema::GetSignedVectorType(QualType V) {
8748 const VectorType *VTy = V->getAs<VectorType>();
8749 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8750 if (TypeSize == Context.getTypeSize(Context.CharTy))
8751 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8752 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8753 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8754 else if (TypeSize == Context.getTypeSize(Context.IntTy))
8755 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8756 else if (TypeSize == Context.getTypeSize(Context.LongTy))
8757 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8758 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8759 "Unhandled vector element size in vector compare");
8760 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8761}
8762
Nate Begemanbe2341d2008-07-14 18:02:46 +00008763/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00008764/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00008765/// like a scalar comparison, a vector comparison produces a vector of integer
8766/// types.
Richard Trieu9f60dee2011-09-07 01:19:57 +00008767QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008768 SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +00008769 bool IsRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00008770 // Check to make sure we're operating on vectors of the same type and width,
8771 // Allowing one side to be a scalar of element type.
Richard Trieu9f60dee2011-09-07 01:19:57 +00008772 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00008773 if (vType.isNull())
8774 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008775
Richard Trieu9f60dee2011-09-07 01:19:57 +00008776 QualType LHSType = LHS.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008777
Anton Yartsev7870b132011-03-27 15:36:07 +00008778 // If AltiVec, the comparison results in a numeric type, i.e.
8779 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00008780 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00008781 return Context.getLogicalOperationType();
8782
Nate Begemanbe2341d2008-07-14 18:02:46 +00008783 // For non-floating point types, check for self-comparisons of the form
8784 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
8785 // often indicate logic errors in the program.
Richard Trieu54237462013-11-02 02:11:23 +00008786 if (!LHSType->hasFloatingRepresentation() &&
8787 ActiveTemplateInstantiations.empty()) {
Richard Smith9c129f82011-10-28 03:31:48 +00008788 if (DeclRefExpr* DRL
8789 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8790 if (DeclRefExpr* DRR
8791 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00008792 if (DRL->getDecl() == DRR->getDecl())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008793 DiagRuntimeBehavior(Loc, nullptr,
Douglas Gregord64fdd02010-06-08 19:50:34 +00008794 PDiag(diag::warn_comparison_always)
8795 << 0 // self-
8796 << 2 // "a constant"
8797 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00008798 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008799
Nate Begemanbe2341d2008-07-14 18:02:46 +00008800 // Check for comparisons of floating point operands using != and ==.
Richard Trieuccd891a2011-09-09 01:45:06 +00008801 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikie52e4c602012-01-16 05:16:03 +00008802 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieu9f60dee2011-09-07 01:19:57 +00008803 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00008804 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00008805
8806 // Return a signed type for the vector.
8807 return GetSignedVectorType(LHSType);
8808}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008809
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +00008810QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8811 SourceLocation Loc) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00008812 // Ensure that either both operands are of the same vector type, or
8813 // one operand is of a vector type and the other is of its element type.
8814 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
Joey Gouly52e933b2013-02-21 11:49:56 +00008815 if (vType.isNull())
8816 return InvalidOperands(Loc, LHS, RHS);
8817 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8818 vType->hasFloatingRepresentation())
Tanya Lattner4f692c22012-01-16 21:02:28 +00008819 return InvalidOperands(Loc, LHS, RHS);
8820
8821 return GetSignedVectorType(LHS.get()->getType());
Nate Begemanbe2341d2008-07-14 18:02:46 +00008822}
8823
Reid Spencer5f016e22007-07-11 17:01:13 +00008824inline QualType Sema::CheckBitwiseOperands(
Richard Trieuccd891a2011-09-09 01:45:06 +00008825 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieu481037f2011-09-16 00:53:10 +00008826 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8827
Richard Trieu9f60dee2011-09-07 01:19:57 +00008828 if (LHS.get()->getType()->isVectorType() ||
8829 RHS.get()->getType()->isVectorType()) {
8830 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8831 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuccd891a2011-09-09 01:45:06 +00008832 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00008833
Richard Trieu9f60dee2011-09-07 01:19:57 +00008834 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregorf6094622010-07-23 15:58:24 +00008835 }
Steve Naroff90045e82007-07-13 23:32:42 +00008836
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008837 ExprResult LHSResult = LHS, RHSResult = RHS;
Richard Trieu9f60dee2011-09-07 01:19:57 +00008838 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuccd891a2011-09-09 01:45:06 +00008839 IsCompAssign);
Richard Trieu9f60dee2011-09-07 01:19:57 +00008840 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008841 return QualType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008842 LHS = LHSResult.get();
8843 RHS = RHSResult.get();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008844
Eli Friedman860a3192012-06-16 02:19:17 +00008845 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00008846 return compType;
Richard Trieu9f60dee2011-09-07 01:19:57 +00008847 return InvalidOperands(Loc, LHS, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +00008848}
8849
8850inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieu9f60dee2011-09-07 01:19:57 +00008851 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00008852
Tanya Lattner4f692c22012-01-16 21:02:28 +00008853 // Check vector operands differently.
8854 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8855 return CheckVectorLogicalOperands(LHS, RHS, Loc);
8856
Chris Lattner90a8f272010-07-13 19:41:32 +00008857 // Diagnose cases where the user write a logical and/or but probably meant a
8858 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8859 // is a constant.
Richard Trieu9f60dee2011-09-07 01:19:57 +00008860 if (LHS.get()->getType()->isIntegerType() &&
8861 !LHS.get()->getType()->isBooleanType() &&
8862 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00008863 // Don't warn in macros or template instantiations.
8864 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00008865 // If the RHS can be constant folded, and if it constant folds to something
8866 // that isn't 0 or 1 (which indicate a potential logical operation that
8867 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00008868 // Parens on the RHS are ignored.
Richard Smith909c5552011-10-16 23:01:09 +00008869 llvm::APSInt Result;
8870 if (RHS.get()->EvaluateAsInt(Result, Context))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008871 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8872 !RHS.get()->getExprLoc().isMacroID()) ||
Richard Smith909c5552011-10-16 23:01:09 +00008873 (Result != 0 && Result != 1)) {
Chandler Carruth0683a142011-05-31 05:41:42 +00008874 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieu9f60dee2011-09-07 01:19:57 +00008875 << RHS.get()->getSourceRange()
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00008876 << (Opc == BO_LAnd ? "&&" : "||");
8877 // Suggest replacing the logical operator with the bitwise version
8878 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8879 << (Opc == BO_LAnd ? "&" : "|")
8880 << FixItHint::CreateReplacement(SourceRange(
8881 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00008882 getLangOpts())),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00008883 Opc == BO_LAnd ? "&" : "|");
8884 if (Opc == BO_LAnd)
8885 // Suggest replacing "Foo() && kNonZero" with "Foo()"
8886 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8887 << FixItHint::CreateRemoval(
8888 SourceRange(
Richard Trieu9f60dee2011-09-07 01:19:57 +00008889 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00008890 0, getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +00008891 getLangOpts()),
Richard Trieu9f60dee2011-09-07 01:19:57 +00008892 RHS.get()->getLocEnd()));
Matt Beaumont-Gay9b127f32011-08-15 17:50:06 +00008893 }
Chris Lattnerb7690b42010-07-24 01:10:11 +00008894 }
Joey Gouly52e933b2013-02-21 11:49:56 +00008895
David Blaikie4e4d0842012-03-11 07:00:24 +00008896 if (!Context.getLangOpts().CPlusPlus) {
Joey Gouly52e933b2013-02-21 11:49:56 +00008897 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8898 // not operate on the built-in scalar and vector float types.
8899 if (Context.getLangOpts().OpenCL &&
8900 Context.getLangOpts().OpenCLVersion < 120) {
8901 if (LHS.get()->getType()->isFloatingType() ||
8902 RHS.get()->getType()->isFloatingType())
8903 return InvalidOperands(Loc, LHS, RHS);
8904 }
8905
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008906 LHS = UsualUnaryConversions(LHS.get());
Richard Trieu9f60dee2011-09-07 01:19:57 +00008907 if (LHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008908 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008909
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008910 RHS = UsualUnaryConversions(RHS.get());
Richard Trieu9f60dee2011-09-07 01:19:57 +00008911 if (RHS.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008912 return QualType();
8913
Richard Trieu9f60dee2011-09-07 01:19:57 +00008914 if (!LHS.get()->getType()->isScalarType() ||
8915 !RHS.get()->getType()->isScalarType())
8916 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008917
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008918 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00008919 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008920
John McCall75f7c0f2010-06-04 00:29:51 +00008921 // The following is safe because we only use this method for
8922 // non-overloadable operands.
8923
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008924 // C++ [expr.log.and]p1
8925 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00008926 // The operands are both contextually converted to type bool.
Richard Trieu9f60dee2011-09-07 01:19:57 +00008927 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8928 if (LHSRes.isInvalid())
8929 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008930 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00008931
Richard Trieu9f60dee2011-09-07 01:19:57 +00008932 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8933 if (RHSRes.isInvalid())
8934 return InvalidOperands(Loc, LHS, RHS);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008935 RHS = RHSRes;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008936
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008937 // C++ [expr.log.and]p2
8938 // C++ [expr.log.or]p2
8939 // The result is a bool.
8940 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008941}
8942
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008943static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall3c3b7f92011-10-25 17:37:35 +00008944 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8945 if (!ME) return false;
8946 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8947 ObjCMessageExpr *Base =
8948 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8949 if (!Base) return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008950 return Base->getMethodDecl() != nullptr;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008951}
8952
John McCall78dae242012-03-13 00:37:01 +00008953/// Is the given expression (which must be 'const') a reference to a
8954/// variable which was originally non-const, but which has become
8955/// 'const' due to being captured within a block?
8956enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8957static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8958 assert(E->isLValue() && E->getType().isConstQualified());
8959 E = E->IgnoreParens();
8960
8961 // Must be a reference to a declaration from an enclosing scope.
8962 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8963 if (!DRE) return NCCK_None;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008964 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
John McCall78dae242012-03-13 00:37:01 +00008965
8966 // The declaration must be a variable which is not declared 'const'.
8967 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8968 if (!var) return NCCK_None;
8969 if (var->getType().isConstQualified()) return NCCK_None;
8970 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8971
8972 // Decide whether the first capture was for a block or a lambda.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008973 DeclContext *DC = S.CurContext, *Prev = nullptr;
Richard Smith39edfeb2013-09-28 04:31:26 +00008974 while (DC != var->getDeclContext()) {
8975 Prev = DC;
John McCall78dae242012-03-13 00:37:01 +00008976 DC = DC->getParent();
Richard Smith39edfeb2013-09-28 04:31:26 +00008977 }
8978 // Unless we have an init-capture, we've gone one step too far.
8979 if (!var->isInitCapture())
8980 DC = Prev;
John McCall78dae242012-03-13 00:37:01 +00008981 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8982}
8983
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07008984static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
8985 Ty = Ty.getNonReferenceType();
8986 if (IsDereference && Ty->isPointerType())
8987 Ty = Ty->getPointeeType();
8988 return !Ty.isConstQualified();
8989}
8990
8991/// Emit the "read-only variable not assignable" error and print notes to give
8992/// more information about why the variable is not assignable, such as pointing
8993/// to the declaration of a const variable, showing that a method is const, or
8994/// that the function is returning a const reference.
8995static void DiagnoseConstAssignment(Sema &S, const Expr *E,
8996 SourceLocation Loc) {
8997 // Update err_typecheck_assign_const and note_typecheck_assign_const
8998 // when this enum is changed.
8999 enum {
9000 ConstFunction,
9001 ConstVariable,
9002 ConstMember,
9003 ConstMethod,
9004 ConstUnknown, // Keep as last element
9005 };
9006
9007 SourceRange ExprRange = E->getSourceRange();
9008
9009 // Only emit one error on the first const found. All other consts will emit
9010 // a note to the error.
9011 bool DiagnosticEmitted = false;
9012
9013 // Track if the current expression is the result of a derefence, and if the
9014 // next checked expression is the result of a derefence.
9015 bool IsDereference = false;
9016 bool NextIsDereference = false;
9017
9018 // Loop to process MemberExpr chains.
9019 while (true) {
9020 IsDereference = NextIsDereference;
9021 NextIsDereference = false;
9022
9023 E = E->IgnoreParenImpCasts();
9024 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9025 NextIsDereference = ME->isArrow();
9026 const ValueDecl *VD = ME->getMemberDecl();
9027 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9028 // Mutable fields can be modified even if the class is const.
9029 if (Field->isMutable()) {
9030 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9031 break;
9032 }
9033
9034 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9035 if (!DiagnosticEmitted) {
9036 S.Diag(Loc, diag::err_typecheck_assign_const)
9037 << ExprRange << ConstMember << false /*static*/ << Field
9038 << Field->getType();
9039 DiagnosticEmitted = true;
9040 }
9041 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9042 << ConstMember << false /*static*/ << Field << Field->getType()
9043 << Field->getSourceRange();
9044 }
9045 E = ME->getBase();
9046 continue;
9047 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9048 if (VDecl->getType().isConstQualified()) {
9049 if (!DiagnosticEmitted) {
9050 S.Diag(Loc, diag::err_typecheck_assign_const)
9051 << ExprRange << ConstMember << true /*static*/ << VDecl
9052 << VDecl->getType();
9053 DiagnosticEmitted = true;
9054 }
9055 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9056 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9057 << VDecl->getSourceRange();
9058 }
9059 // Static fields do not inherit constness from parents.
9060 break;
9061 }
9062 break;
9063 } // End MemberExpr
9064 break;
9065 }
9066
9067 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9068 // Function calls
9069 const FunctionDecl *FD = CE->getDirectCallee();
9070 if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9071 if (!DiagnosticEmitted) {
9072 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9073 << ConstFunction << FD;
9074 DiagnosticEmitted = true;
9075 }
9076 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9077 diag::note_typecheck_assign_const)
9078 << ConstFunction << FD << FD->getReturnType()
9079 << FD->getReturnTypeSourceRange();
9080 }
9081 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9082 // Point to variable declaration.
9083 if (const ValueDecl *VD = DRE->getDecl()) {
9084 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9085 if (!DiagnosticEmitted) {
9086 S.Diag(Loc, diag::err_typecheck_assign_const)
9087 << ExprRange << ConstVariable << VD << VD->getType();
9088 DiagnosticEmitted = true;
9089 }
9090 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9091 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9092 }
9093 }
9094 } else if (isa<CXXThisExpr>(E)) {
9095 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9096 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9097 if (MD->isConst()) {
9098 if (!DiagnosticEmitted) {
9099 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9100 << ConstMethod << MD;
9101 DiagnosticEmitted = true;
9102 }
9103 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9104 << ConstMethod << MD << MD->getSourceRange();
9105 }
9106 }
9107 }
9108 }
9109
9110 if (DiagnosticEmitted)
9111 return;
9112
9113 // Can't determine a more specific message, so display the generic error.
9114 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9115}
9116
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009117/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
9118/// emit an error and return true. If so, return false.
9119static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniane7ea28a2012-04-10 17:30:10 +00009120 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbar44e35f72009-04-15 00:08:05 +00009121 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00009122 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00009123 &Loc);
Eli Friedman642038d2013-06-27 01:36:36 +00009124 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
Fariborz Jahanian077f4902011-03-26 19:48:30 +00009125 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009126 if (IsLV == Expr::MLV_Valid)
9127 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009128
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009129 unsigned DiagID = 0;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009130 bool NeedType = false;
9131 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00009132 case Expr::MLV_ConstQualified:
John McCall78dae242012-03-13 00:37:01 +00009133 // Use a specialized diagnostic when we're assigning to an object
9134 // from an enclosing function or block.
9135 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9136 if (NCCK == NCCK_Block)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009137 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
John McCall78dae242012-03-13 00:37:01 +00009138 else
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009139 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
John McCall78dae242012-03-13 00:37:01 +00009140 break;
9141 }
9142
John McCall7acddac2011-06-17 06:42:21 +00009143 // In ARC, use some specialized diagnostics for occasions where we
9144 // infer 'const'. These are always pseudo-strong variables.
David Blaikie4e4d0842012-03-11 07:00:24 +00009145 if (S.getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00009146 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9147 if (declRef && isa<VarDecl>(declRef->getDecl())) {
9148 VarDecl *var = cast<VarDecl>(declRef->getDecl());
9149
John McCall7acddac2011-06-17 06:42:21 +00009150 // Use the normal diagnostic if it's pseudo-__strong but the
9151 // user actually wrote 'const'.
9152 if (var->isARCPseudoStrong() &&
9153 (!var->getTypeSourceInfo() ||
9154 !var->getTypeSourceInfo()->getType().isConstQualified())) {
9155 // There are two pseudo-strong cases:
9156 // - self
John McCallf85e1932011-06-15 23:02:42 +00009157 ObjCMethodDecl *method = S.getCurMethodDecl();
9158 if (method && var == method->getSelfDecl())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009159 DiagID = method->isClassMethod()
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00009160 ? diag::err_typecheck_arc_assign_self_class_method
9161 : diag::err_typecheck_arc_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00009162
9163 // - fast enumeration variables
9164 else
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009165 DiagID = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00009166
John McCallf85e1932011-06-15 23:02:42 +00009167 SourceRange Assign;
9168 if (Loc != OrigLoc)
9169 Assign = SourceRange(OrigLoc, OrigLoc);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009170 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07009171 // We need to preserve the AST regardless, so migration tool
John McCallf85e1932011-06-15 23:02:42 +00009172 // can do its job.
9173 return false;
9174 }
9175 }
9176 }
9177
Pirama Arumuga Nainar33337ca2015-05-06 11:48:57 -07009178 // If none of the special cases above are triggered, then this is a
9179 // simple const assignment.
9180 if (DiagID == 0) {
9181 DiagnoseConstAssignment(S, E, Loc);
9182 return true;
9183 }
9184
John McCallf85e1932011-06-15 23:02:42 +00009185 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009186 case Expr::MLV_ArrayType:
Richard Smith36d02af2012-06-04 22:27:30 +00009187 case Expr::MLV_ArrayTemporary:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009188 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009189 NeedType = true;
9190 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009191 case Expr::MLV_NotObjectType:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009192 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009193 NeedType = true;
9194 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00009195 case Expr::MLV_LValueCast:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009196 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009197 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00009198 case Expr::MLV_Valid:
9199 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00009200 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00009201 case Expr::MLV_MemberFunction:
9202 case Expr::MLV_ClassTemporary:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009203 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009204 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009205 case Expr::MLV_IncompleteType:
9206 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00009207 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00009208 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009209 case Expr::MLV_DuplicateVectorComponents:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009210 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009211 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00009212 case Expr::MLV_NoSetterProperty:
John McCall3c3b7f92011-10-25 17:37:35 +00009213 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian077f4902011-03-26 19:48:30 +00009214 case Expr::MLV_InvalidMessageExpression:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009215 DiagID = diag::error_readonly_message_assignment;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00009216 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00009217 case Expr::MLV_SubObjCPropertySetting:
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009218 DiagID = diag::error_no_subobject_property_setting;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00009219 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00009220 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00009221
Daniel Dunbar44e35f72009-04-15 00:08:05 +00009222 SourceRange Assign;
9223 if (Loc != OrigLoc)
9224 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009225 if (NeedType)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009226 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009227 else
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009228 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009229 return true;
9230}
9231
Nico Weber7c81b432012-07-03 02:03:06 +00009232static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9233 SourceLocation Loc,
9234 Sema &Sema) {
9235 // C / C++ fields
Nico Weber43bb1792012-06-28 23:53:12 +00009236 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9237 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9238 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9239 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
Nico Weber7c81b432012-07-03 02:03:06 +00009240 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
Nico Weber43bb1792012-06-28 23:53:12 +00009241 }
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009242
Nico Weber7c81b432012-07-03 02:03:06 +00009243 // Objective-C instance variables
Nico Weber43bb1792012-06-28 23:53:12 +00009244 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9245 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9246 if (OL && OR && OL->getDecl() == OR->getDecl()) {
9247 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9248 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9249 if (RL && RR && RL->getDecl() == RR->getDecl())
Nico Weber7c81b432012-07-03 02:03:06 +00009250 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
Nico Weber43bb1792012-06-28 23:53:12 +00009251 }
9252}
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009253
9254// C99 6.5.16.1
Richard Trieu268942b2011-09-07 01:33:52 +00009255QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009256 SourceLocation Loc,
9257 QualType CompoundType) {
John McCall3c3b7f92011-10-25 17:37:35 +00009258 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9259
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009260 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieu268942b2011-09-07 01:33:52 +00009261 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00009262 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009263
Richard Trieu268942b2011-09-07 01:33:52 +00009264 QualType LHSType = LHSExpr->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00009265 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9266 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009267 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009268 if (CompoundType.isNull()) {
Nico Weber43bb1792012-06-28 23:53:12 +00009269 Expr *RHSCheck = RHS.get();
9270
Nico Weber7c81b432012-07-03 02:03:06 +00009271 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
Nico Weber43bb1792012-06-28 23:53:12 +00009272
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00009273 QualType LHSTy(LHSType);
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00009274 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00009275 if (RHS.isInvalid())
9276 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00009277 // Special case of NSObject attributes on c-style pointer types.
9278 if (ConvTy == IncompatiblePointer &&
9279 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00009280 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00009281 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00009282 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00009283 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009284
John McCallf89e55a2010-11-18 06:31:45 +00009285 if (ConvTy == Compatible &&
Fariborz Jahanian466f45a2012-01-24 19:40:13 +00009286 LHSType->isObjCObjectType())
Fariborz Jahanian7b383e42012-01-24 18:05:45 +00009287 Diag(Loc, diag::err_objc_object_assignment)
9288 << LHSType;
John McCallf89e55a2010-11-18 06:31:45 +00009289
Chris Lattner2c156472008-08-21 18:04:13 +00009290 // If the RHS is a unary plus or minus, check to see if they = and + are
9291 // right next to each other. If so, the user may have typo'd "x =+ 4"
9292 // instead of "x += 4".
Chris Lattner2c156472008-08-21 18:04:13 +00009293 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9294 RHSCheck = ICE->getSubExpr();
9295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00009296 if ((UO->getOpcode() == UO_Plus ||
9297 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009298 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00009299 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00009300 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner399bd1b2009-03-08 06:51:10 +00009301 // And there is a space or other character before the subexpr of the
9302 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00009303 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattner3e872092009-03-09 07:11:10 +00009304 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00009305 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00009306 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00009307 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00009308 }
Chris Lattner2c156472008-08-21 18:04:13 +00009309 }
John McCallf85e1932011-06-15 23:02:42 +00009310
9311 if (ConvTy == Compatible) {
Jordan Rosee10f4d32012-09-15 02:48:31 +00009312 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9313 // Warn about retain cycles where a block captures the LHS, but
9314 // not if the LHS is a simple variable into which the block is
9315 // being stored...unless that variable can be captured by reference!
9316 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9317 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9318 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9319 checkRetainCycles(LHSExpr, RHS.get());
9320
Jordan Rose58b6bdc2012-09-28 22:21:30 +00009321 // It is safe to assign a weak reference into a strong variable.
9322 // Although this code can still have problems:
9323 // id x = self.weakProp;
9324 // id y = self.weakProp;
9325 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9326 // paths through the function. This should be revisited if
9327 // -Wrepeated-use-of-weak is made flow-sensitive.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009328 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9329 RHS.get()->getLocStart()))
Jordan Rose58b6bdc2012-09-28 22:21:30 +00009330 getCurFunction()->markSafeWeakUse(RHS.get());
9331
Jordan Rosee10f4d32012-09-15 02:48:31 +00009332 } else if (getLangOpts().ObjCAutoRefCount) {
Richard Trieu268942b2011-09-07 01:33:52 +00009333 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
Jordan Rosee10f4d32012-09-15 02:48:31 +00009334 }
John McCallf85e1932011-06-15 23:02:42 +00009335 }
Chris Lattner2c156472008-08-21 18:04:13 +00009336 } else {
9337 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00009338 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00009339 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009340
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009341 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00009342 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00009343 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00009344
Richard Trieu268942b2011-09-07 01:33:52 +00009345 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00009346
Reid Spencer5f016e22007-07-11 17:01:13 +00009347 // C99 6.5.16p3: The type of an assignment expression is the type of the
9348 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00009349 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00009350 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9351 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009352 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00009353 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00009354 return (getLangOpts().CPlusPlus
John McCall2bf6f492010-10-12 02:19:57 +00009355 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00009356}
9357
Chris Lattner29a1cfb2008-11-18 01:30:42 +00009358// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00009359static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00009360 SourceLocation Loc) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009361 LHS = S.CheckPlaceholderExpr(LHS.get());
9362 RHS = S.CheckPlaceholderExpr(RHS.get());
John Wiegley429bb272011-04-08 18:41:53 +00009363 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00009364 return QualType();
9365
John McCallcf2e5062010-10-12 07:14:40 +00009366 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9367 // operands, but not unary promotions.
9368 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009369
John McCallf6a16482010-12-04 03:47:34 +00009370 // So we treat the LHS as a ignored value, and in C++ we allow the
9371 // containing site to determine what should be done with the RHS.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009372 LHS = S.IgnoredValueConversions(LHS.get());
John Wiegley429bb272011-04-08 18:41:53 +00009373 if (LHS.isInvalid())
9374 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00009375
Eli Friedmana6115062012-05-24 00:47:05 +00009376 S.DiagnoseUnusedExprResult(LHS.get());
9377
David Blaikie4e4d0842012-03-11 07:00:24 +00009378 if (!S.getLangOpts().CPlusPlus) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009379 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley429bb272011-04-08 18:41:53 +00009380 if (RHS.isInvalid())
9381 return QualType();
9382 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00009383 S.RequireCompleteType(Loc, RHS.get()->getType(),
9384 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00009385 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009386
John Wiegley429bb272011-04-08 18:41:53 +00009387 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009388}
9389
Steve Naroff49b45262007-07-13 16:58:59 +00009390/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9391/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00009392static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9393 ExprValueKind &VK,
Stephen Hines176edba2014-12-01 14:53:08 -08009394 ExprObjectKind &OK,
John McCall09431682010-11-18 19:01:18 +00009395 SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009396 bool IsInc, bool IsPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00009397 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00009398 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00009399
Chris Lattner3528d352008-11-21 07:05:48 +00009400 QualType ResType = Op->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00009401 // Atomic types can be used for increment / decrement where the non-atomic
9402 // versions can, so ignore the _Atomic() specifier for the purpose of
9403 // checking.
9404 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9405 ResType = ResAtomicType->getValueType();
9406
Chris Lattner3528d352008-11-21 07:05:48 +00009407 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00009408
David Blaikie4e4d0842012-03-11 07:00:24 +00009409 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00009410 // Decrement of bool is not allowed.
Richard Trieuccd891a2011-09-09 01:45:06 +00009411 if (!IsInc) {
John McCall09431682010-11-18 19:01:18 +00009412 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00009413 return QualType();
9414 }
9415 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00009416 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Richard Trieufbbdc5d2013-08-08 01:50:23 +00009417 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9418 // Error on enum increments and decrements in C++ mode
9419 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9420 return QualType();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00009421 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00009422 // OK!
John McCall1503f0d2012-07-31 05:14:30 +00009423 } else if (ResType->isPointerType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00009424 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00009425 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009426 return QualType();
John McCall1503f0d2012-07-31 05:14:30 +00009427 } else if (ResType->isObjCObjectPointerType()) {
9428 // On modern runtimes, ObjC pointer arithmetic is forbidden.
9429 // Otherwise, we just need a complete type.
9430 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9431 checkArithmeticOnObjCPointer(S, OpLoc, Op))
9432 return QualType();
Eli Friedman5b088a12010-01-03 00:20:48 +00009433 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00009434 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00009435 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00009436 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00009437 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009438 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00009439 if (PR.isInvalid()) return QualType();
Stephen Hines176edba2014-12-01 14:53:08 -08009440 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +00009441 IsInc, IsPrefix);
David Blaikie4e4d0842012-03-11 07:00:24 +00009442 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00009443 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
David Tweedd7d94dc2013-09-06 09:58:08 +00009444 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9445 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9446 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
Chris Lattner3528d352008-11-21 07:05:48 +00009447 } else {
John McCall09431682010-11-18 19:01:18 +00009448 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuccd891a2011-09-09 01:45:06 +00009449 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00009450 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009451 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009452 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00009453 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00009454 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00009455 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009456 // In C++, a prefix increment is the same type as the operand. Otherwise
9457 // (in C or with postfix), the increment is the unqualified type of the
9458 // operand.
David Blaikie4e4d0842012-03-11 07:00:24 +00009459 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall09431682010-11-18 19:01:18 +00009460 VK = VK_LValue;
Stephen Hines176edba2014-12-01 14:53:08 -08009461 OK = Op->getObjectKind();
John McCall09431682010-11-18 19:01:18 +00009462 return ResType;
9463 } else {
9464 VK = VK_RValue;
9465 return ResType.getUnqualifiedType();
9466 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009467}
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00009468
9469
Anders Carlsson369dee42008-02-01 07:15:58 +00009470/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00009471/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00009472/// where the declaration is needed for type checking. We only need to
9473/// handle cases when the expression references a function designator
9474/// or is an lvalue. Here are some examples:
9475/// - &(x) => x
9476/// - &*****f => f for f a function designator.
9477/// - &s.xx => s
9478/// - &s.zz[1].yy -> s, if zz is an array
9479/// - *(x + 1) -> x, if x is an array
9480/// - &"123"[2] -> 0
9481/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00009482static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00009483 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00009484 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00009485 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00009486 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00009487 // If this is an arrow operator, the address is an offset from
9488 // the base's value, so the object the base refers to is
9489 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00009490 if (cast<MemberExpr>(E)->isArrow())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009491 return nullptr;
Eli Friedman23d58ce2009-04-20 08:23:18 +00009492 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00009493 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00009494 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00009495 // FIXME: This code shouldn't be necessary! We should catch the implicit
9496 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00009497 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9498 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9499 if (ICE->getSubExpr()->getType()->isArrayType())
9500 return getPrimaryDecl(ICE->getSubExpr());
9501 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009502 return nullptr;
Anders Carlsson369dee42008-02-01 07:15:58 +00009503 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00009504 case Stmt::UnaryOperatorClass: {
9505 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009506
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00009507 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00009508 case UO_Real:
9509 case UO_Imag:
9510 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00009511 return getPrimaryDecl(UO->getSubExpr());
9512 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009513 return nullptr;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00009514 }
9515 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009516 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00009517 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00009518 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00009519 // If the result of an implicit cast is an l-value, we care about
9520 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00009521 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00009522 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009523 return nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +00009524 }
9525}
9526
Richard Trieu5520f232011-09-07 21:46:33 +00009527namespace {
9528 enum {
9529 AO_Bit_Field = 0,
9530 AO_Vector_Element = 1,
9531 AO_Property_Expansion = 2,
9532 AO_Register_Variable = 3,
9533 AO_No_Error = 4
9534 };
9535}
Richard Trieu09a26ad2011-09-02 00:47:55 +00009536/// \brief Diagnose invalid operand for address of operations.
9537///
9538/// \param Type The type of operand which cannot have its address taken.
Richard Trieu09a26ad2011-09-02 00:47:55 +00009539static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9540 Expr *E, unsigned Type) {
9541 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9542}
9543
Reid Spencer5f016e22007-07-11 17:01:13 +00009544/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00009545/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00009546/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009547/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00009548/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009549/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00009550/// we allow the '&' but retain the overloaded-function type.
Richard Smith27ec2d02013-07-11 02:26:56 +00009551QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
John McCall3c3b7f92011-10-25 17:37:35 +00009552 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9553 if (PTy->getKind() == BuiltinType::Overload) {
David Majnemerc77039e2013-07-05 06:23:33 +00009554 Expr *E = OrigOp.get()->IgnoreParens();
9555 if (!isa<OverloadExpr>(E)) {
9556 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
Richard Smith27ec2d02013-07-11 02:26:56 +00009557 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
John McCall3c3b7f92011-10-25 17:37:35 +00009558 << OrigOp.get()->getSourceRange();
9559 return QualType();
9560 }
David Majnemer01e0b1f2013-06-11 03:56:29 +00009561
David Majnemerc77039e2013-07-05 06:23:33 +00009562 OverloadExpr *Ovl = cast<OverloadExpr>(E);
David Majnemer01e0b1f2013-06-11 03:56:29 +00009563 if (isa<UnresolvedMemberExpr>(Ovl))
Richard Smith27ec2d02013-07-11 02:26:56 +00009564 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9565 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
David Majnemer01e0b1f2013-06-11 03:56:29 +00009566 << OrigOp.get()->getSourceRange();
9567 return QualType();
9568 }
9569
Richard Smith27ec2d02013-07-11 02:26:56 +00009570 return Context.OverloadTy;
John McCall3c3b7f92011-10-25 17:37:35 +00009571 }
9572
9573 if (PTy->getKind() == BuiltinType::UnknownAny)
Richard Smith27ec2d02013-07-11 02:26:56 +00009574 return Context.UnknownAnyTy;
John McCall3c3b7f92011-10-25 17:37:35 +00009575
9576 if (PTy->getKind() == BuiltinType::BoundMember) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009577 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00009578 << OrigOp.get()->getSourceRange();
Douglas Gregor44efed02011-10-09 19:10:41 +00009579 return QualType();
9580 }
John McCall3c3b7f92011-10-25 17:37:35 +00009581
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009582 OrigOp = CheckPlaceholderExpr(OrigOp.get());
John McCall3c3b7f92011-10-25 17:37:35 +00009583 if (OrigOp.isInvalid()) return QualType();
John McCall864c0412011-04-26 20:42:42 +00009584 }
John McCall9c72c602010-08-27 09:08:28 +00009585
John McCall3c3b7f92011-10-25 17:37:35 +00009586 if (OrigOp.get()->isTypeDependent())
Richard Smith27ec2d02013-07-11 02:26:56 +00009587 return Context.DependentTy;
John McCall3c3b7f92011-10-25 17:37:35 +00009588
9589 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00009590
John McCall9c72c602010-08-27 09:08:28 +00009591 // Make sure to ignore parentheses in subsequent checks
John McCall3c3b7f92011-10-25 17:37:35 +00009592 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00009593
Stephen Hines651f13c2014-04-23 16:59:28 -07009594 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9595 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9596 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9597 return QualType();
9598 }
9599
Richard Smith27ec2d02013-07-11 02:26:56 +00009600 if (getLangOpts().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00009601 // Implement C99-only parts of addressof rules.
9602 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00009603 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00009604 // Per C99 6.5.3.2, the address of a deref always returns a valid result
9605 // (assuming the deref expression is valid).
9606 return uOp->getSubExpr()->getType();
9607 }
9608 // Technically, there should be a check for array subscript
9609 // expressions here, but the result of one is always an lvalue anyway.
9610 }
John McCall5808ce42011-02-03 08:15:49 +00009611 ValueDecl *dcl = getPrimaryDecl(op);
Richard Smith27ec2d02013-07-11 02:26:56 +00009612 Expr::LValueClassification lval = op->ClassifyLValue(Context);
Richard Trieu5520f232011-09-07 21:46:33 +00009613 unsigned AddressOfError = AO_No_Error;
Nuno Lopes6b6609f2008-12-16 22:59:47 +00009614
Richard Smith3fa3fea2013-02-02 02:14:45 +00009615 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009616 bool sfinae = (bool)isSFINAEContext();
9617 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9618 : diag::ext_typecheck_addrof_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00009619 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00009620 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00009621 return QualType();
Richard Smitha07a6c32013-05-01 19:00:39 +00009622 // Materialize the temporary as an lvalue so that we can take its address.
Richard Smith27ec2d02013-07-11 02:26:56 +00009623 OrigOp = op = new (Context)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009624 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
John McCall9c72c602010-08-27 09:08:28 +00009625 } else if (isa<ObjCSelectorExpr>(op)) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009626 return Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00009627 } else if (lval == Expr::LV_MemberFunction) {
9628 // If it's an instance method, make a member pointer.
9629 // The expression must have exactly the form &A::foo.
9630
9631 // If the underlying expression isn't a decl ref, give up.
9632 if (!isa<DeclRefExpr>(op)) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009633 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00009634 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00009635 return QualType();
9636 }
9637 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9638 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9639
9640 // The id-expression was parenthesized.
John McCall3c3b7f92011-10-25 17:37:35 +00009641 if (OrigOp.get() != DRE) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009642 Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall3c3b7f92011-10-25 17:37:35 +00009643 << OrigOp.get()->getSourceRange();
John McCall9c72c602010-08-27 09:08:28 +00009644
9645 // The method was named without a qualifier.
9646 } else if (!DRE->getQualifier()) {
David Blaikieabeadfb2012-10-11 22:55:07 +00009647 if (MD->getParent()->getName().empty())
Richard Smith27ec2d02013-07-11 02:26:56 +00009648 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikieabeadfb2012-10-11 22:55:07 +00009649 << op->getSourceRange();
9650 else {
9651 SmallString<32> Str;
9652 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
Richard Smith27ec2d02013-07-11 02:26:56 +00009653 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
David Blaikieabeadfb2012-10-11 22:55:07 +00009654 << op->getSourceRange()
9655 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9656 }
John McCall9c72c602010-08-27 09:08:28 +00009657 }
9658
Benjamin Kramer6e04a842013-10-10 09:44:41 +00009659 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9660 if (isa<CXXDestructorDecl>(MD))
9661 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9662
Stephen Hines651f13c2014-04-23 16:59:28 -07009663 QualType MPTy = Context.getMemberPointerType(
9664 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9665 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9666 RequireCompleteType(OpLoc, MPTy, 0);
9667 return MPTy;
John McCall9c72c602010-08-27 09:08:28 +00009668 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00009669 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00009670 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00009671 if (!op->getType()->isFunctionType()) {
John McCall3c3b7f92011-10-25 17:37:35 +00009672 // Use a special diagnostic for loads from property references.
John McCall4b9c2d22011-11-06 09:01:30 +00009673 if (isa<PseudoObjectExpr>(op)) {
John McCall3c3b7f92011-10-25 17:37:35 +00009674 AddressOfError = AO_Property_Expansion;
9675 } else {
Richard Smith27ec2d02013-07-11 02:26:56 +00009676 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Richard Smith3fa3fea2013-02-02 02:14:45 +00009677 << op->getType() << op->getSourceRange();
John McCall3c3b7f92011-10-25 17:37:35 +00009678 return QualType();
9679 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009680 }
John McCall7eb0a9e2010-11-24 05:12:34 +00009681 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00009682 // The operand cannot be a bit-field
Richard Trieu5520f232011-09-07 21:46:33 +00009683 AddressOfError = AO_Bit_Field;
John McCall7eb0a9e2010-11-24 05:12:34 +00009684 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00009685 // The operand cannot be an element of a vector
Richard Trieu5520f232011-09-07 21:46:33 +00009686 AddressOfError = AO_Vector_Element;
Steve Naroffbcb2b612008-02-29 23:30:25 +00009687 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00009688 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00009689 // with the register storage-class specifier.
9690 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00009691 // in C++ it is not error to take address of a register
9692 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00009693 if (vd->getStorageClass() == SC_Register &&
Richard Smith27ec2d02013-07-11 02:26:56 +00009694 !getLangOpts().CPlusPlus) {
Richard Trieu5520f232011-09-07 21:46:33 +00009695 AddressOfError = AO_Register_Variable;
Reid Spencer5f016e22007-07-11 17:01:13 +00009696 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009697 } else if (isa<MSPropertyDecl>(dcl)) {
9698 AddressOfError = AO_Property_Expansion;
John McCallba135432009-11-21 08:51:07 +00009699 } else if (isa<FunctionTemplateDecl>(dcl)) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009700 return Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00009701 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00009702 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00009703 // Could be a pointer to member, though, if there is an explicit
9704 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00009705 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00009706 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00009707 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00009708 if (dcl->getType()->isReferenceType()) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009709 Diag(OpLoc,
9710 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00009711 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00009712 return QualType();
9713 }
Mike Stump1eb44332009-09-09 15:08:12 +00009714
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00009715 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9716 Ctx = Ctx->getParent();
Stephen Hines651f13c2014-04-23 16:59:28 -07009717
9718 QualType MPTy = Context.getMemberPointerType(
9719 op->getType(),
9720 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9721 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9722 RequireCompleteType(OpLoc, MPTy, 0);
9723 return MPTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00009724 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00009725 }
Eli Friedman7b2f51c2011-08-26 20:28:17 +00009726 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikieb219cfc2011-09-23 05:06:16 +00009727 llvm_unreachable("Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00009728 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00009729
Richard Trieu5520f232011-09-07 21:46:33 +00009730 if (AddressOfError != AO_No_Error) {
Richard Smith27ec2d02013-07-11 02:26:56 +00009731 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
Richard Trieu5520f232011-09-07 21:46:33 +00009732 return QualType();
9733 }
9734
Eli Friedman441cf102009-05-16 23:27:50 +00009735 if (lval == Expr::LV_IncompleteVoidType) {
9736 // Taking the address of a void variable is technically illegal, but we
9737 // allow it in cases which are otherwise valid.
9738 // Example: "extern void x; void* y = &x;".
Richard Smith27ec2d02013-07-11 02:26:56 +00009739 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00009740 }
9741
Reid Spencer5f016e22007-07-11 17:01:13 +00009742 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00009743 if (op->getType()->isObjCObjectType())
Richard Smith27ec2d02013-07-11 02:26:56 +00009744 return Context.getObjCObjectPointerType(op->getType());
9745 return Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00009746}
9747
Stephen Hines176edba2014-12-01 14:53:08 -08009748static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
9749 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
9750 if (!DRE)
9751 return;
9752 const Decl *D = DRE->getDecl();
9753 if (!D)
9754 return;
9755 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
9756 if (!Param)
9757 return;
9758 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009759 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
Stephen Hines176edba2014-12-01 14:53:08 -08009760 return;
9761 if (FunctionScopeInfo *FD = S.getCurFunction())
9762 if (!FD->ModifiedNonNullParams.count(Param))
9763 FD->ModifiedNonNullParams.insert(Param);
9764}
9765
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00009766/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00009767static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9768 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00009769 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00009770 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00009771
John Wiegley429bb272011-04-08 18:41:53 +00009772 ExprResult ConvResult = S.UsualUnaryConversions(Op);
9773 if (ConvResult.isInvalid())
9774 return QualType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009775 Op = ConvResult.get();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00009776 QualType OpTy = Op->getType();
9777 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00009778
9779 if (isa<CXXReinterpretCastExpr>(Op)) {
9780 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9781 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9782 Op->getSourceRange());
9783 }
9784
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00009785 if (const PointerType *PT = OpTy->getAs<PointerType>())
9786 Result = PT->getPointeeType();
9787 else if (const ObjCObjectPointerType *OPT =
9788 OpTy->getAs<ObjCObjectPointerType>())
9789 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00009790 else {
John McCallfb8721c2011-04-10 19:13:55 +00009791 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00009792 if (PR.isInvalid()) return QualType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009793 if (PR.get() != Op)
9794 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00009795 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009796
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00009797 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00009798 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00009799 << OpTy << Op->getSourceRange();
9800 return QualType();
9801 }
John McCall09431682010-11-18 19:01:18 +00009802
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009803 // Note that per both C89 and C99, indirection is always legal, even if Result
9804 // is an incomplete type or void. It would be possible to warn about
9805 // dereferencing a void pointer, but it's completely well-defined, and such a
9806 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9807 // for pointers to 'void' but is fine for any other pointer type:
9808 //
9809 // C++ [expr.unary.op]p1:
9810 // [...] the expression to which [the unary * operator] is applied shall
9811 // be a pointer to an object type, or a pointer to a function type
9812 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9813 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9814 << OpTy << Op->getSourceRange();
9815
John McCall09431682010-11-18 19:01:18 +00009816 // Dereferences are usually l-values...
9817 VK = VK_LValue;
9818
9819 // ...except that certain expressions are never l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009820 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00009821 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00009822
9823 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00009824}
9825
Stephen Hines176edba2014-12-01 14:53:08 -08009826BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00009827 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009828 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009829 default: llvm_unreachable("Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00009830 case tok::periodstar: Opc = BO_PtrMemD; break;
9831 case tok::arrowstar: Opc = BO_PtrMemI; break;
9832 case tok::star: Opc = BO_Mul; break;
9833 case tok::slash: Opc = BO_Div; break;
9834 case tok::percent: Opc = BO_Rem; break;
9835 case tok::plus: Opc = BO_Add; break;
9836 case tok::minus: Opc = BO_Sub; break;
9837 case tok::lessless: Opc = BO_Shl; break;
9838 case tok::greatergreater: Opc = BO_Shr; break;
9839 case tok::lessequal: Opc = BO_LE; break;
9840 case tok::less: Opc = BO_LT; break;
9841 case tok::greaterequal: Opc = BO_GE; break;
9842 case tok::greater: Opc = BO_GT; break;
9843 case tok::exclaimequal: Opc = BO_NE; break;
9844 case tok::equalequal: Opc = BO_EQ; break;
9845 case tok::amp: Opc = BO_And; break;
9846 case tok::caret: Opc = BO_Xor; break;
9847 case tok::pipe: Opc = BO_Or; break;
9848 case tok::ampamp: Opc = BO_LAnd; break;
9849 case tok::pipepipe: Opc = BO_LOr; break;
9850 case tok::equal: Opc = BO_Assign; break;
9851 case tok::starequal: Opc = BO_MulAssign; break;
9852 case tok::slashequal: Opc = BO_DivAssign; break;
9853 case tok::percentequal: Opc = BO_RemAssign; break;
9854 case tok::plusequal: Opc = BO_AddAssign; break;
9855 case tok::minusequal: Opc = BO_SubAssign; break;
9856 case tok::lesslessequal: Opc = BO_ShlAssign; break;
9857 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
9858 case tok::ampequal: Opc = BO_AndAssign; break;
9859 case tok::caretequal: Opc = BO_XorAssign; break;
9860 case tok::pipeequal: Opc = BO_OrAssign; break;
9861 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00009862 }
9863 return Opc;
9864}
9865
John McCall2de56d12010-08-25 11:45:40 +00009866static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00009867 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00009868 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00009869 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00009870 default: llvm_unreachable("Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00009871 case tok::plusplus: Opc = UO_PreInc; break;
9872 case tok::minusminus: Opc = UO_PreDec; break;
9873 case tok::amp: Opc = UO_AddrOf; break;
9874 case tok::star: Opc = UO_Deref; break;
9875 case tok::plus: Opc = UO_Plus; break;
9876 case tok::minus: Opc = UO_Minus; break;
9877 case tok::tilde: Opc = UO_Not; break;
9878 case tok::exclaim: Opc = UO_LNot; break;
9879 case tok::kw___real: Opc = UO_Real; break;
9880 case tok::kw___imag: Opc = UO_Imag; break;
9881 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00009882 }
9883 return Opc;
9884}
9885
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009886/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9887/// This warning is only emitted for builtin assignment operations. It is also
9888/// suppressed in the event of macro expansions.
Richard Trieu268942b2011-09-07 01:33:52 +00009889static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009890 SourceLocation OpLoc) {
9891 if (!S.ActiveTemplateInstantiations.empty())
9892 return;
9893 if (OpLoc.isInvalid() || OpLoc.isMacroID())
9894 return;
Richard Trieu268942b2011-09-07 01:33:52 +00009895 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9896 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9897 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9898 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9899 if (!LHSDeclRef || !RHSDeclRef ||
9900 LHSDeclRef->getLocation().isMacroID() ||
9901 RHSDeclRef->getLocation().isMacroID())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009902 return;
Richard Trieu268942b2011-09-07 01:33:52 +00009903 const ValueDecl *LHSDecl =
9904 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9905 const ValueDecl *RHSDecl =
9906 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9907 if (LHSDecl != RHSDecl)
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009908 return;
Richard Trieu268942b2011-09-07 01:33:52 +00009909 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009910 return;
Richard Trieu268942b2011-09-07 01:33:52 +00009911 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009912 if (RefTy->getPointeeType().isVolatileQualified())
9913 return;
9914
9915 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieu268942b2011-09-07 01:33:52 +00009916 << LHSDeclRef->getType()
9917 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00009918}
9919
Ted Kremenek3aaf41a2013-04-22 22:46:52 +00009920/// Check if a bitwise-& is performed on an Objective-C pointer. This
9921/// is usually indicative of introspection within the Objective-C pointer.
9922static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9923 SourceLocation OpLoc) {
9924 if (!S.getLangOpts().ObjC1)
9925 return;
9926
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009927 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
Ted Kremenek3aaf41a2013-04-22 22:46:52 +00009928 const Expr *LHS = L.get();
9929 const Expr *RHS = R.get();
9930
9931 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9932 ObjCPointerExpr = LHS;
9933 OtherExpr = RHS;
9934 }
9935 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9936 ObjCPointerExpr = RHS;
9937 OtherExpr = LHS;
9938 }
9939
9940 // This warning is deliberately made very specific to reduce false
9941 // positives with logic that uses '&' for hashing. This logic mainly
9942 // looks for code trying to introspect into tagged pointers, which
9943 // code should generally never do.
9944 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
Ted Kremenekea943142013-06-24 21:35:39 +00009945 unsigned Diag = diag::warn_objc_pointer_masking;
9946 // Determine if we are introspecting the result of performSelectorXXX.
9947 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9948 // Special case messages to -performSelector and friends, which
9949 // can return non-pointer values boxed in a pointer value.
9950 // Some clients may wish to silence warnings in this subcase.
9951 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9952 Selector S = ME->getSelector();
9953 StringRef SelArg0 = S.getNameForSlot(0);
9954 if (SelArg0.startswith("performSelector"))
9955 Diag = diag::warn_objc_pointer_masking_performSelector;
9956 }
9957
9958 S.Diag(OpLoc, Diag)
Ted Kremenek3aaf41a2013-04-22 22:46:52 +00009959 << ObjCPointerExpr->getSourceRange();
9960 }
9961}
9962
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009963static NamedDecl *getDeclFromExpr(Expr *E) {
9964 if (!E)
9965 return nullptr;
9966 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
9967 return DRE->getDecl();
9968 if (auto *ME = dyn_cast<MemberExpr>(E))
9969 return ME->getMemberDecl();
9970 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
9971 return IRE->getDecl();
9972 return nullptr;
9973}
9974
Douglas Gregoreaebc752008-11-06 23:29:22 +00009975/// CreateBuiltinBinOp - Creates a new built-in binary operation with
9976/// operator @p Opc at location @c TokLoc. This routine only supports
9977/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00009978ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00009979 BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +00009980 Expr *LHSExpr, Expr *RHSExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00009981 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00009982 // The syntax only allows initializer lists on the RHS of assignment,
9983 // so we don't need to worry about accepting invalid code for
9984 // non-assignment operators.
9985 // C++11 5.17p9:
9986 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9987 // of x = {} is x = T().
9988 InitializationKind Kind =
9989 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9990 InitializedEntity Entity =
9991 InitializedEntity::InitializeTemporary(LHSExpr->getType());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00009992 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
Benjamin Kramer5354e772012-08-23 23:38:35 +00009993 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00009994 if (Init.isInvalid())
9995 return Init;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009996 RHSExpr = Init.get();
Sebastian Redl0d8ab2e2012-02-27 20:34:02 +00009997 }
9998
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009999 ExprResult LHS = LHSExpr, RHS = RHSExpr;
Eli Friedmanab3a8522009-03-28 01:22:36 +000010000 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +000010001 // The following two variables are used for compound assignment operators
10002 QualType CompLHSTy; // Type of LHS after promotions for computation
10003 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +000010004 ExprValueKind VK = VK_RValue;
10005 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +000010006
Stephen Hines0e2c34f2015-03-23 12:09:02 -070010007 if (!getLangOpts().CPlusPlus) {
10008 // C cannot handle TypoExpr nodes on either side of a binop because it
10009 // doesn't handle dependent types properly, so make sure any TypoExprs have
10010 // been dealt with before checking the operands.
10011 LHS = CorrectDelayedTyposInExpr(LHSExpr);
10012 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10013 if (Opc != BO_Assign)
10014 return ExprResult(E);
10015 // Avoid correcting the RHS to the same Expr as the LHS.
10016 Decl *D = getDeclFromExpr(E);
10017 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10018 });
10019 if (!LHS.isUsable() || !RHS.isUsable())
10020 return ExprError();
10021 }
10022
Douglas Gregoreaebc752008-11-06 23:29:22 +000010023 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +000010024 case BO_Assign:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010025 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikie4e4d0842012-03-11 07:00:24 +000010026 if (getLangOpts().CPlusPlus &&
Richard Trieu78ea78b2011-09-07 01:49:20 +000010027 LHS.get()->getObjectKind() != OK_ObjCProperty) {
10028 VK = LHS.get()->getValueKind();
10029 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +000010030 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -070010031 if (!ResultTy.isNull()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +000010032 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070010033 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10034 }
Stephen Hines176edba2014-12-01 14:53:08 -080010035 RecordModifiableNonNullParam(*this, LHS.get());
Douglas Gregoreaebc752008-11-06 23:29:22 +000010036 break;
John McCall2de56d12010-08-25 11:45:40 +000010037 case BO_PtrMemD:
10038 case BO_PtrMemI:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010039 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +000010040 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +000010041 break;
John McCall2de56d12010-08-25 11:45:40 +000010042 case BO_Mul:
10043 case BO_Div:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010044 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +000010045 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010046 break;
John McCall2de56d12010-08-25 11:45:40 +000010047 case BO_Rem:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010048 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010049 break;
John McCall2de56d12010-08-25 11:45:40 +000010050 case BO_Add:
Nico Weber1cb2d742012-03-02 22:01:22 +000010051 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010052 break;
John McCall2de56d12010-08-25 11:45:40 +000010053 case BO_Sub:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010054 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010055 break;
John McCall2de56d12010-08-25 11:45:40 +000010056 case BO_Shl:
10057 case BO_Shr:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010058 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010059 break;
John McCall2de56d12010-08-25 11:45:40 +000010060 case BO_LE:
10061 case BO_LT:
10062 case BO_GE:
10063 case BO_GT:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010064 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010065 break;
John McCall2de56d12010-08-25 11:45:40 +000010066 case BO_EQ:
10067 case BO_NE:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010068 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010069 break;
John McCall2de56d12010-08-25 11:45:40 +000010070 case BO_And:
Ted Kremenek3aaf41a2013-04-22 22:46:52 +000010071 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
John McCall2de56d12010-08-25 11:45:40 +000010072 case BO_Xor:
10073 case BO_Or:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010074 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010075 break;
John McCall2de56d12010-08-25 11:45:40 +000010076 case BO_LAnd:
10077 case BO_LOr:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010078 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010079 break;
John McCall2de56d12010-08-25 11:45:40 +000010080 case BO_MulAssign:
10081 case BO_DivAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010082 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +000010083 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +000010084 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +000010085 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10086 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010087 break;
John McCall2de56d12010-08-25 11:45:40 +000010088 case BO_RemAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010089 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +000010090 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +000010091 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10092 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010093 break;
John McCall2de56d12010-08-25 11:45:40 +000010094 case BO_AddAssign:
Nico Weber1cb2d742012-03-02 22:01:22 +000010095 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu78ea78b2011-09-07 01:49:20 +000010096 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10097 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010098 break;
John McCall2de56d12010-08-25 11:45:40 +000010099 case BO_SubAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010100 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10101 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10102 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010103 break;
John McCall2de56d12010-08-25 11:45:40 +000010104 case BO_ShlAssign:
10105 case BO_ShrAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010106 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +000010107 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +000010108 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10109 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010110 break;
John McCall2de56d12010-08-25 11:45:40 +000010111 case BO_AndAssign:
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010112 case BO_OrAssign: // fallthrough
10113 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
John McCall2de56d12010-08-25 11:45:40 +000010114 case BO_XorAssign:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010115 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +000010116 CompLHSTy = CompResultTy;
Richard Trieu78ea78b2011-09-07 01:49:20 +000010117 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10118 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010119 break;
John McCall2de56d12010-08-25 11:45:40 +000010120 case BO_Comma:
Richard Trieu78ea78b2011-09-07 01:49:20 +000010121 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikie4e4d0842012-03-11 07:00:24 +000010122 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu78ea78b2011-09-07 01:49:20 +000010123 VK = RHS.get()->getValueKind();
10124 OK = RHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +000010125 }
Douglas Gregoreaebc752008-11-06 23:29:22 +000010126 break;
10127 }
Richard Trieu78ea78b2011-09-07 01:49:20 +000010128 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +000010129 return ExprError();
Kaelyn Uhraind6c88652011-08-05 23:18:04 +000010130
10131 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu78ea78b2011-09-07 01:49:20 +000010132 CheckArrayAccess(LHS.get());
10133 CheckArrayAccess(RHS.get());
Kaelyn Uhraind6c88652011-08-05 23:18:04 +000010134
Fariborz Jahanianec8deba2013-03-28 19:50:55 +000010135 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10136 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10137 &Context.Idents.get("object_setClass"),
10138 SourceLocation(), LookupOrdinaryName);
10139 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10140 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
10141 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10142 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10143 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10144 FixItHint::CreateInsertion(RHSLocEnd, ")");
10145 }
10146 else
10147 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10148 }
Fariborz Jahanian99a72d22013-03-28 23:39:11 +000010149 else if (const ObjCIvarRefExpr *OIRE =
10150 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
Fariborz Jahanian0c701812013-04-02 18:57:54 +000010151 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
Fariborz Jahanian99a72d22013-03-28 23:39:11 +000010152
Eli Friedmanab3a8522009-03-28 01:22:36 +000010153 if (CompResultTy.isNull())
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010154 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10155 OK, OpLoc, FPFeatures.fp_contract);
David Blaikie4e4d0842012-03-11 07:00:24 +000010156 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieu67e29332011-08-02 04:35:43 +000010157 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +000010158 VK = VK_LValue;
Richard Trieu78ea78b2011-09-07 01:49:20 +000010159 OK = LHS.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +000010160 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010161 return new (Context) CompoundAssignOperator(
10162 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10163 OpLoc, FPFeatures.fp_contract);
Douglas Gregoreaebc752008-11-06 23:29:22 +000010164}
10165
Sebastian Redlaee3c932009-10-27 12:10:02 +000010166/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10167/// operators are mixed in a way that suggests that the programmer forgot that
10168/// comparison operators have higher precedence. The most typical example of
10169/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +000010170static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu78ea78b2011-09-07 01:49:20 +000010171 SourceLocation OpLoc, Expr *LHSExpr,
10172 Expr *RHSExpr) {
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010173 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10174 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010175
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010176 // Check that one of the sides is a comparison operator.
10177 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10178 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10179 if (!isLeftComp && !isRightComp)
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010180 return;
10181
10182 // Bitwise operations are sometimes used as eager logical ops.
10183 // Don't diagnose this.
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010184 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10185 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10186 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010187 return;
10188
Richard Trieu78ea78b2011-09-07 01:49:20 +000010189 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10190 OpLoc)
10191 : SourceRange(OpLoc, RHSExpr->getLocEnd());
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010192 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
Richard Trieu70979d42011-08-10 22:41:34 +000010193 SourceRange ParensRange = isLeftComp ?
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010194 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
Stephen Hines176edba2014-12-01 14:53:08 -080010195 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
Richard Trieu70979d42011-08-10 22:41:34 +000010196
10197 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010198 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
Richard Trieu70979d42011-08-10 22:41:34 +000010199 SuggestParentheses(Self, OpLoc,
David Blaikie6b34c172012-10-08 01:19:49 +000010200 Self.PDiag(diag::note_precedence_silence) << OpStr,
Nico Weber40e29992012-06-03 07:07:00 +000010201 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu70979d42011-08-10 22:41:34 +000010202 SuggestParentheses(Self, OpLoc,
Eli Friedmanebbcd1d2012-11-15 00:29:07 +000010203 Self.PDiag(diag::note_precedence_bitwise_first)
10204 << BinaryOperator::getOpcodeStr(Opc),
Richard Trieu70979d42011-08-10 22:41:34 +000010205 ParensRange);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010206}
10207
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +000010208/// \brief It accepts a '&' expr that is inside a '|' one.
10209/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
10210/// in parentheses.
10211static void
10212EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
10213 BinaryOperator *Bop) {
10214 assert(Bop->getOpcode() == BO_And);
10215 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
10216 << Bop->getSourceRange() << OpLoc;
10217 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +000010218 Self.PDiag(diag::note_precedence_silence)
10219 << Bop->getOpcodeStr(),
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +000010220 Bop->getSourceRange());
10221}
10222
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010223/// \brief It accepts a '&&' expr that is inside a '||' one.
10224/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10225/// in parentheses.
10226static void
10227EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +000010228 BinaryOperator *Bop) {
10229 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +000010230 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10231 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +000010232 SuggestParentheses(Self, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +000010233 Self.PDiag(diag::note_precedence_silence)
10234 << Bop->getOpcodeStr(),
Chandler Carruthf0b60d62011-06-16 01:05:14 +000010235 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010236}
10237
10238/// \brief Returns true if the given expression can be evaluated as a constant
10239/// 'true'.
10240static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10241 bool Res;
Richard Smith556ef7f2013-08-19 22:06:05 +000010242 return !E->isValueDependent() &&
10243 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010244}
10245
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +000010246/// \brief Returns true if the given expression can be evaluated as a constant
10247/// 'false'.
10248static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10249 bool Res;
Richard Smith556ef7f2013-08-19 22:06:05 +000010250 return !E->isValueDependent() &&
10251 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +000010252}
10253
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010254/// \brief Look for '&&' in the left hand of a '||' expr.
10255static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +000010256 Expr *LHSExpr, Expr *RHSExpr) {
10257 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +000010258 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +000010259 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +000010260 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +000010261 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010262 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10263 if (!EvaluatesAsTrue(S, Bop->getLHS()))
10264 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10265 } else if (Bop->getOpcode() == BO_LOr) {
10266 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10267 // If it's "a || b && 1 || c" we didn't warn earlier for
10268 // "a || b && 1", but warn now.
10269 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10270 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10271 }
10272 }
10273 }
10274}
10275
10276/// \brief Look for '&&' in the right hand of a '||' expr.
10277static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieubefece12011-09-07 02:02:10 +000010278 Expr *LHSExpr, Expr *RHSExpr) {
10279 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010280 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +000010281 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieubefece12011-09-07 02:02:10 +000010282 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +000010283 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010284 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10285 if (!EvaluatesAsTrue(S, Bop->getRHS()))
10286 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +000010287 }
10288 }
10289}
10290
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +000010291/// \brief Look for '&' in the left or right hand of a '|' expr.
10292static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
10293 Expr *OrArg) {
10294 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
10295 if (Bop->getOpcode() == BO_And)
10296 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
10297 }
10298}
10299
David Blaikieb3f55c52012-10-05 00:41:03 +000010300static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
David Blaikie5f531a42012-10-19 18:26:06 +000010301 Expr *SubExpr, StringRef Shift) {
David Blaikieb3f55c52012-10-05 00:41:03 +000010302 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10303 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
David Blaikie6b34c172012-10-08 01:19:49 +000010304 StringRef Op = Bop->getOpcodeStr();
David Blaikieb3f55c52012-10-05 00:41:03 +000010305 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
David Blaikie5f531a42012-10-19 18:26:06 +000010306 << Bop->getSourceRange() << OpLoc << Shift << Op;
David Blaikieb3f55c52012-10-05 00:41:03 +000010307 SuggestParentheses(S, Bop->getOperatorLoc(),
David Blaikie6b34c172012-10-08 01:19:49 +000010308 S.PDiag(diag::note_precedence_silence) << Op,
David Blaikieb3f55c52012-10-05 00:41:03 +000010309 Bop->getSourceRange());
10310 }
10311 }
10312}
10313
Richard Trieu2a6e5282013-04-17 02:12:45 +000010314static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10315 Expr *LHSExpr, Expr *RHSExpr) {
10316 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10317 if (!OCE)
10318 return;
10319
10320 FunctionDecl *FD = OCE->getDirectCallee();
10321 if (!FD || !FD->isOverloadedOperator())
10322 return;
10323
10324 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10325 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10326 return;
10327
10328 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10329 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10330 << (Kind == OO_LessLess);
Richard Trieu2a6e5282013-04-17 02:12:45 +000010331 SuggestParentheses(S, OCE->getOperatorLoc(),
10332 S.PDiag(diag::note_precedence_silence)
10333 << (Kind == OO_LessLess ? "<<" : ">>"),
10334 OCE->getSourceRange());
Richard Trieu1a7df992013-04-18 01:04:37 +000010335 SuggestParentheses(S, OpLoc,
10336 S.PDiag(diag::note_evaluate_comparison_first),
10337 SourceRange(OCE->getArg(1)->getLocStart(),
10338 RHSExpr->getLocEnd()));
Richard Trieu2a6e5282013-04-17 02:12:45 +000010339}
10340
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010341/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +000010342/// precedence.
John McCall2de56d12010-08-25 11:45:40 +000010343static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +000010344 SourceLocation OpLoc, Expr *LHSExpr,
10345 Expr *RHSExpr){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +000010346 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +000010347 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieubefece12011-09-07 02:02:10 +000010348 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +000010349
10350 // Diagnose "arg1 & arg2 | arg3"
10351 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +000010352 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
10353 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +000010354 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +000010355
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +000010356 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10357 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +000010358 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieubefece12011-09-07 02:02:10 +000010359 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10360 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +000010361 }
David Blaikieb3f55c52012-10-05 00:41:03 +000010362
10363 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10364 || Opc == BO_Shr) {
David Blaikie5f531a42012-10-19 18:26:06 +000010365 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10366 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10367 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
David Blaikieb3f55c52012-10-05 00:41:03 +000010368 }
Richard Trieu2a6e5282013-04-17 02:12:45 +000010369
10370 // Warn on overloaded shift operators and comparisons, such as:
10371 // cout << 5 == 4;
10372 if (BinaryOperator::isComparisonOp(Opc))
10373 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010374}
10375
Reid Spencer5f016e22007-07-11 17:01:13 +000010376// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +000010377ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +000010378 tok::TokenKind Kind,
Richard Trieubefece12011-09-07 02:02:10 +000010379 Expr *LHSExpr, Expr *RHSExpr) {
John McCall2de56d12010-08-25 11:45:40 +000010380 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010381 assert(LHSExpr && "ActOnBinOp(): missing left expression");
10382 assert(RHSExpr && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +000010383
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010384 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieubefece12011-09-07 02:02:10 +000010385 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl9e1d29b2009-10-26 15:24:15 +000010386
Richard Trieubefece12011-09-07 02:02:10 +000010387 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010388}
10389
John McCall3c3b7f92011-10-25 17:37:35 +000010390/// Build an overloaded binary operator expression in the given scope.
10391static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10392 BinaryOperatorKind Opc,
10393 Expr *LHS, Expr *RHS) {
10394 // Find all of the overloaded operators visible from this
10395 // point. We perform both an operator-name lookup from the local
10396 // scope and an argument-dependent lookup based on the types of
10397 // the arguments.
10398 UnresolvedSet<16> Functions;
10399 OverloadedOperatorKind OverOp
10400 = BinaryOperator::getOverloadedOperator(Opc);
Stephen Hines176edba2014-12-01 14:53:08 -080010401 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
John McCall3c3b7f92011-10-25 17:37:35 +000010402 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10403 RHS->getType(), Functions);
10404
10405 // Build the (potentially-overloaded, potentially-dependent)
10406 // binary operation.
10407 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10408}
10409
John McCall60d7b3a2010-08-24 06:29:42 +000010410ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +000010411 BinaryOperatorKind Opc,
Richard Trieubefece12011-09-07 02:02:10 +000010412 Expr *LHSExpr, Expr *RHSExpr) {
John McCallac516502011-10-28 01:04:34 +000010413 // We want to end up calling one of checkPseudoObjectAssignment
10414 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10415 // both expressions are overloadable or either is type-dependent),
10416 // or CreateBuiltinBinOp (in any other case). We also want to get
10417 // any placeholder types out of the way.
10418
John McCall3c3b7f92011-10-25 17:37:35 +000010419 // Handle pseudo-objects in the LHS.
10420 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10421 // Assignments with a pseudo-object l-value need special analysis.
10422 if (pty->getKind() == BuiltinType::PseudoObject &&
10423 BinaryOperator::isAssignmentOp(Opc))
10424 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10425
10426 // Don't resolve overloads if the other type is overloadable.
10427 if (pty->getKind() == BuiltinType::Overload) {
10428 // We can't actually test that if we still have a placeholder,
10429 // though. Fortunately, none of the exceptions we see in that
John McCallac516502011-10-28 01:04:34 +000010430 // code below are valid when the LHS is an overload set. Note
10431 // that an overload set can be dependently-typed, but it never
10432 // instantiates to having an overloadable type.
John McCall3c3b7f92011-10-25 17:37:35 +000010433 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10434 if (resolvedRHS.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010435 RHSExpr = resolvedRHS.get();
John McCall3c3b7f92011-10-25 17:37:35 +000010436
John McCallac516502011-10-28 01:04:34 +000010437 if (RHSExpr->isTypeDependent() ||
10438 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +000010439 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10440 }
10441
10442 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10443 if (LHS.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010444 LHSExpr = LHS.get();
John McCall3c3b7f92011-10-25 17:37:35 +000010445 }
10446
10447 // Handle pseudo-objects in the RHS.
10448 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10449 // An overload in the RHS can potentially be resolved by the type
10450 // being assigned to.
John McCallac516502011-10-28 01:04:34 +000010451 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10452 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10453 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10454
Eli Friedman87884912012-01-17 21:27:43 +000010455 if (LHSExpr->getType()->isOverloadableType())
10456 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10457
John McCall3c3b7f92011-10-25 17:37:35 +000010458 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCallac516502011-10-28 01:04:34 +000010459 }
John McCall3c3b7f92011-10-25 17:37:35 +000010460
10461 // Don't resolve overloads if the other type is overloadable.
10462 if (pty->getKind() == BuiltinType::Overload &&
10463 LHSExpr->getType()->isOverloadableType())
10464 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10465
10466 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10467 if (!resolvedRHS.isUsable()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010468 RHSExpr = resolvedRHS.get();
John McCall3c3b7f92011-10-25 17:37:35 +000010469 }
10470
David Blaikie4e4d0842012-03-11 07:00:24 +000010471 if (getLangOpts().CPlusPlus) {
John McCallac516502011-10-28 01:04:34 +000010472 // If either expression is type-dependent, always build an
10473 // overloaded op.
10474 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10475 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010476
John McCallac516502011-10-28 01:04:34 +000010477 // Otherwise, build an overloaded op if either expression has an
10478 // overloadable type.
10479 if (LHSExpr->getType()->isOverloadableType() ||
10480 RHSExpr->getType()->isOverloadableType())
John McCall3c3b7f92011-10-25 17:37:35 +000010481 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +000010482 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010483
Douglas Gregoreaebc752008-11-06 23:29:22 +000010484 // Build a built-in binary operation.
Richard Trieubefece12011-09-07 02:02:10 +000010485 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +000010486}
10487
John McCall60d7b3a2010-08-24 06:29:42 +000010488ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +000010489 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +000010490 Expr *InputExpr) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010491 ExprResult Input = InputExpr;
John McCallf89e55a2010-11-18 06:31:45 +000010492 ExprValueKind VK = VK_RValue;
10493 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +000010494 QualType resultType;
10495 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +000010496 case UO_PreInc:
10497 case UO_PreDec:
10498 case UO_PostInc:
10499 case UO_PostDec:
Stephen Hines176edba2014-12-01 14:53:08 -080010500 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10501 OpLoc,
John McCall2de56d12010-08-25 11:45:40 +000010502 Opc == UO_PreInc ||
10503 Opc == UO_PostInc,
10504 Opc == UO_PreInc ||
10505 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +000010506 break;
John McCall2de56d12010-08-25 11:45:40 +000010507 case UO_AddrOf:
Richard Smith27ec2d02013-07-11 02:26:56 +000010508 resultType = CheckAddressOfOperand(Input, OpLoc);
Stephen Hines176edba2014-12-01 14:53:08 -080010509 RecordModifiableNonNullParam(*this, InputExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +000010510 break;
John McCall1de4d4e2011-04-07 08:22:57 +000010511 case UO_Deref: {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010512 Input = DefaultFunctionArrayLvalueConversion(Input.get());
Eli Friedmana6c66ce2012-08-31 00:14:07 +000010513 if (Input.isInvalid()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010514 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000010515 break;
John McCall1de4d4e2011-04-07 08:22:57 +000010516 }
John McCall2de56d12010-08-25 11:45:40 +000010517 case UO_Plus:
10518 case UO_Minus:
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010519 Input = UsualUnaryConversions(Input.get());
John Wiegley429bb272011-04-08 18:41:53 +000010520 if (Input.isInvalid()) return ExprError();
10521 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +000010522 if (resultType->isDependentType())
10523 break;
Douglas Gregor00619622010-06-22 23:41:02 +000010524 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
10525 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +000010526 break;
David Blaikie4e4d0842012-03-11 07:00:24 +000010527 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +000010528 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +000010529 resultType->isPointerType())
10530 break;
10531
Sebastian Redl0eb23302009-01-19 00:08:26 +000010532 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +000010533 << resultType << Input.get()->getSourceRange());
10534
John McCall2de56d12010-08-25 11:45:40 +000010535 case UO_Not: // bitwise complement
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010536 Input = UsualUnaryConversions(Input.get());
Joey Gouly52e933b2013-02-21 11:49:56 +000010537 if (Input.isInvalid())
10538 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010539 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +000010540 if (resultType->isDependentType())
10541 break;
Chris Lattner02a65142008-07-25 23:52:49 +000010542 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10543 if (resultType->isComplexType() || resultType->isComplexIntegerType())
10544 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +000010545 Diag(OpLoc, diag::ext_integer_complement_complex)
Joey Gouly52e933b2013-02-21 11:49:56 +000010546 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +000010547 else if (resultType->hasIntegerRepresentation())
10548 break;
Joey Gouly52e933b2013-02-21 11:49:56 +000010549 else if (resultType->isExtVectorType()) {
10550 if (Context.getLangOpts().OpenCL) {
10551 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10552 // on vector float types.
10553 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10554 if (!T->isIntegerType())
10555 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10556 << resultType << Input.get()->getSourceRange());
10557 }
10558 break;
10559 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +000010560 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
Joey Gouly52e933b2013-02-21 11:49:56 +000010561 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +000010562 }
Reid Spencer5f016e22007-07-11 17:01:13 +000010563 break;
John Wiegley429bb272011-04-08 18:41:53 +000010564
John McCall2de56d12010-08-25 11:45:40 +000010565 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +000010566 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010567 Input = DefaultFunctionArrayLvalueConversion(Input.get());
John Wiegley429bb272011-04-08 18:41:53 +000010568 if (Input.isInvalid()) return ExprError();
10569 resultType = Input.get()->getType();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000010570
10571 // Though we still have to promote half FP to float...
Joey Gouly19dbb202013-01-23 11:56:20 +000010572 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010573 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000010574 resultType = Context.FloatTy;
10575 }
10576
Sebastian Redl28507842009-02-26 14:39:58 +000010577 if (resultType->isDependentType())
10578 break;
Stephen Hines651f13c2014-04-23 16:59:28 -070010579 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
Abramo Bagnara737d5442011-04-07 09:26:19 +000010580 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikie4e4d0842012-03-11 07:00:24 +000010581 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara737d5442011-04-07 09:26:19 +000010582 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10583 // operand contextually converted to bool.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010584 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
John Wiegley429bb272011-04-08 18:41:53 +000010585 ScalarTypeToBooleanCastKind(resultType));
Joey Gouly52e933b2013-02-21 11:49:56 +000010586 } else if (Context.getLangOpts().OpenCL &&
10587 Context.getLangOpts().OpenCLVersion < 120) {
10588 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10589 // operate on scalar float types.
10590 if (!resultType->isIntegerType())
10591 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10592 << resultType << Input.get()->getSourceRange());
Abramo Bagnara737d5442011-04-07 09:26:19 +000010593 }
Tanya Lattnerb0f9dd22012-01-19 01:16:16 +000010594 } else if (resultType->isExtVectorType()) {
Joey Gouly52e933b2013-02-21 11:49:56 +000010595 if (Context.getLangOpts().OpenCL &&
10596 Context.getLangOpts().OpenCLVersion < 120) {
10597 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10598 // operate on vector float types.
10599 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10600 if (!T->isIntegerType())
10601 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10602 << resultType << Input.get()->getSourceRange());
10603 }
Tanya Lattner4f692c22012-01-16 21:02:28 +000010604 // Vector logical not returns the signed variant of the operand type.
10605 resultType = GetSignedVectorType(resultType);
10606 break;
John McCall2cd11fe2010-10-12 02:09:17 +000010607 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +000010608 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +000010609 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +000010610 }
Douglas Gregorea844f32010-09-20 17:13:33 +000010611
Reid Spencer5f016e22007-07-11 17:01:13 +000010612 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +000010613 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +000010614 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +000010615 break;
John McCall2de56d12010-08-25 11:45:40 +000010616 case UO_Real:
10617 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +000010618 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smithdfb80de2012-02-18 20:53:32 +000010619 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10620 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley429bb272011-04-08 18:41:53 +000010621 if (Input.isInvalid()) return ExprError();
Richard Smithdfb80de2012-02-18 20:53:32 +000010622 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10623 if (Input.get()->getValueKind() != VK_RValue &&
10624 Input.get()->getObjectKind() == OK_Ordinary)
10625 VK = Input.get()->getValueKind();
David Blaikie4e4d0842012-03-11 07:00:24 +000010626 } else if (!getLangOpts().CPlusPlus) {
Richard Smithdfb80de2012-02-18 20:53:32 +000010627 // In C, a volatile scalar is read by __imag. In C++, it is not.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010628 Input = DefaultLvalueConversion(Input.get());
Richard Smithdfb80de2012-02-18 20:53:32 +000010629 }
Chris Lattnerdbb36972007-08-24 21:16:53 +000010630 break;
John McCall2de56d12010-08-25 11:45:40 +000010631 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +000010632 resultType = Input.get()->getType();
10633 VK = Input.get()->getValueKind();
10634 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +000010635 break;
10636 }
John Wiegley429bb272011-04-08 18:41:53 +000010637 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +000010638 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010639
Kaelyn Uhraind6c88652011-08-05 23:18:04 +000010640 // Check for array bounds violations in the operand of the UnaryOperator,
10641 // except for the '*' and '&' operators that have to be handled specially
10642 // by CheckArrayAccess (as there are special cases like &array[arraysize]
10643 // that are explicitly defined as valid by the standard).
10644 if (Opc != UO_AddrOf && Opc != UO_Deref)
10645 CheckArrayAccess(Input.get());
10646
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010647 return new (Context)
10648 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000010649}
10650
Douglas Gregord3d08532011-12-14 21:23:13 +000010651/// \brief Determine whether the given expression is a qualified member
10652/// access expression, of a form that could be turned into a pointer to member
10653/// with the address-of operator.
10654static bool isQualifiedMemberAccess(Expr *E) {
10655 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10656 if (!DRE->getQualifier())
10657 return false;
10658
10659 ValueDecl *VD = DRE->getDecl();
10660 if (!VD->isCXXClassMember())
10661 return false;
10662
10663 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10664 return true;
10665 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10666 return Method->isInstance();
10667
10668 return false;
10669 }
10670
10671 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10672 if (!ULE->getQualifier())
10673 return false;
10674
10675 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10676 DEnd = ULE->decls_end();
10677 D != DEnd; ++D) {
10678 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10679 if (Method->isInstance())
10680 return true;
10681 } else {
10682 // Overload set does not contain methods.
10683 break;
10684 }
10685 }
10686
10687 return false;
10688 }
10689
10690 return false;
10691}
10692
John McCall60d7b3a2010-08-24 06:29:42 +000010693ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +000010694 UnaryOperatorKind Opc, Expr *Input) {
John McCall3c3b7f92011-10-25 17:37:35 +000010695 // First things first: handle placeholders so that the
10696 // overloaded-operator check considers the right type.
10697 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10698 // Increment and decrement of pseudo-object references.
10699 if (pty->getKind() == BuiltinType::PseudoObject &&
10700 UnaryOperator::isIncrementDecrementOp(Opc))
10701 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10702
10703 // extension is always a builtin operator.
10704 if (Opc == UO_Extension)
10705 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10706
10707 // & gets special logic for several kinds of placeholder.
10708 // The builtin code knows what to do.
10709 if (Opc == UO_AddrOf &&
10710 (pty->getKind() == BuiltinType::Overload ||
10711 pty->getKind() == BuiltinType::UnknownAny ||
10712 pty->getKind() == BuiltinType::BoundMember))
10713 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10714
10715 // Anything else needs to be handled now.
10716 ExprResult Result = CheckPlaceholderExpr(Input);
10717 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010718 Input = Result.get();
John McCall3c3b7f92011-10-25 17:37:35 +000010719 }
10720
David Blaikie4e4d0842012-03-11 07:00:24 +000010721 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregord3d08532011-12-14 21:23:13 +000010722 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10723 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010724 // Find all of the overloaded operators visible from this
10725 // point. We perform both an operator-name lookup from the local
10726 // scope and an argument-dependent lookup based on the types of
10727 // the arguments.
John McCall6e266892010-01-26 03:27:55 +000010728 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010729 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +000010730 if (S && OverOp != OO_None)
10731 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10732 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010733
John McCall9ae2f072010-08-23 23:25:46 +000010734 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010735 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010736
John McCall9ae2f072010-08-23 23:25:46 +000010737 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010738}
10739
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010740// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +000010741ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +000010742 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +000010743 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010744}
10745
Steve Naroff1b273c42007-09-16 14:56:35 +000010746/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +000010747ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +000010748 LabelDecl *TheDecl) {
Eli Friedman86164e82013-09-05 00:02:25 +000010749 TheDecl->markUsed(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +000010750 // Create the AST node. The address of a label always has type 'void*'.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010751 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10752 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +000010753}
10754
John McCallf85e1932011-06-15 23:02:42 +000010755/// Given the last statement in a statement-expression, check whether
10756/// the result is a producing expression (like a call to an
10757/// ns_returns_retained function) and, if so, rebuild it to hoist the
10758/// release out of the full-expression. Otherwise, return null.
10759/// Cannot fail.
Richard Trieuccd891a2011-09-09 01:45:06 +000010760static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCallf85e1932011-06-15 23:02:42 +000010761 // Should always be wrapped with one of these.
Richard Trieuccd891a2011-09-09 01:45:06 +000010762 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010763 if (!cleanups) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +000010764
10765 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall33e56f32011-09-10 06:18:15 +000010766 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010767 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +000010768
10769 // Splice out the cast. This shouldn't modify any interesting
10770 // features of the statement.
10771 Expr *producer = cast->getSubExpr();
10772 assert(producer->getType() == cast->getType());
10773 assert(producer->getValueKind() == cast->getValueKind());
10774 cleanups->setSubExpr(producer);
10775 return cleanups;
10776}
10777
John McCall73f428c2012-04-04 01:27:53 +000010778void Sema::ActOnStartStmtExpr() {
10779 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10780}
10781
10782void Sema::ActOnStmtExprError() {
John McCall7f39d512012-04-06 18:20:53 +000010783 // Note that function is also called by TreeTransform when leaving a
10784 // StmtExpr scope without rebuilding anything.
10785
John McCall73f428c2012-04-04 01:27:53 +000010786 DiscardCleanupsInEvaluationContext();
10787 PopExpressionEvaluationContext();
10788}
10789
John McCall60d7b3a2010-08-24 06:29:42 +000010790ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010791Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +000010792 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +000010793 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10794 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10795
John McCall73f428c2012-04-04 01:27:53 +000010796 if (hasAnyUnrecoverableErrorsInThisFunction())
10797 DiscardCleanupsInEvaluationContext();
10798 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10799 PopExpressionEvaluationContext();
10800
Chris Lattnerab18c4c2007-07-24 16:58:17 +000010801 // FIXME: there are a variety of strange constraints to enforce here, for
10802 // example, it is not possible to goto into a stmt expression apparently.
10803 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +000010804
Stephen Hines651f13c2014-04-23 16:59:28 -070010805 // If there are sub-stmts in the compound stmt, take the type of the last one
Chris Lattnerab18c4c2007-07-24 16:58:17 +000010806 // as the type of the stmtexpr.
10807 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010808 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +000010809 if (!Compound->body_empty()) {
10810 Stmt *LastStmt = Compound->body_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010811 LabelStmt *LastLabelStmt = nullptr;
Chris Lattner611b2ec2008-07-26 19:51:01 +000010812 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010813 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10814 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +000010815 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010816 }
John McCallf85e1932011-06-15 23:02:42 +000010817
John Wiegley429bb272011-04-08 18:41:53 +000010818 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +000010819 // Do function/array conversion on the last expression, but not
10820 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +000010821 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10822 if (LastExpr.isInvalid())
10823 return ExprError();
10824 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +000010825
John Wiegley429bb272011-04-08 18:41:53 +000010826 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +000010827 // In ARC, if the final expression ends in a consume, splice
10828 // the consume out and bind it later. In the alternate case
10829 // (when dealing with a retainable type), the result
10830 // initialization will create a produce. In both cases the
10831 // result will be +1, and we'll need to balance that out with
10832 // a bind.
10833 if (Expr *rebuiltLastStmt
10834 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10835 LastExpr = rebuiltLastStmt;
10836 } else {
10837 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010838 InitializedEntity::InitializeResult(LPLoc,
10839 Ty,
10840 false),
10841 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +000010842 LastExpr);
10843 }
10844
John Wiegley429bb272011-04-08 18:41:53 +000010845 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010846 return ExprError();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010847 if (LastExpr.get() != nullptr) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010848 if (!LastLabelStmt)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010849 Compound->setLastStmt(LastExpr.get());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010850 else
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010851 LastLabelStmt->setSubStmt(LastExpr.get());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010852 StmtExprMayBindToTemp = true;
10853 }
10854 }
10855 }
Chris Lattner611b2ec2008-07-26 19:51:01 +000010856 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010857
Eli Friedmanb1d796d2009-03-23 00:24:07 +000010858 // FIXME: Check that expression type is complete/non-abstract; statement
10859 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +000010860 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10861 if (StmtExprMayBindToTemp)
10862 return MaybeBindToTemporary(ResStmtExpr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010863 return ResStmtExpr;
Chris Lattnerab18c4c2007-07-24 16:58:17 +000010864}
Steve Naroffd34e9152007-08-01 22:05:33 +000010865
John McCall60d7b3a2010-08-24 06:29:42 +000010866ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +000010867 TypeSourceInfo *TInfo,
10868 OffsetOfComponent *CompPtr,
10869 unsigned NumComponents,
10870 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010871 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +000010872 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010873 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010874
Chris Lattner73d0d4f2007-08-30 17:45:32 +000010875 // We must have at least one component that refers to the type, and the first
10876 // one is known to be a field designator. Verify that the ArgTy represents
10877 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +000010878 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010879 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10880 << ArgTy << TypeRange);
10881
10882 // Type must be complete per C99 7.17p3 because a declaring a variable
10883 // with an incomplete type would be ill-formed.
10884 if (!Dependent
10885 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010886 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010887 return ExprError();
10888
Chris Lattner9e2b75c2007-08-31 21:49:13 +000010889 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10890 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +000010891 // FIXME: This diagnostic isn't actually visible because the location is in
10892 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +000010893 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +000010894 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10895 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010896
10897 bool DidWarnAboutNonPOD = false;
10898 QualType CurrentType = ArgTy;
10899 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010900 SmallVector<OffsetOfNode, 4> Comps;
10901 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010902 for (unsigned i = 0; i != NumComponents; ++i) {
10903 const OffsetOfComponent &OC = CompPtr[i];
10904 if (OC.isBrackets) {
10905 // Offset of an array sub-field. TODO: Should we allow vector elements?
10906 if (!CurrentType->isDependentType()) {
10907 const ArrayType *AT = Context.getAsArrayType(CurrentType);
10908 if(!AT)
10909 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10910 << CurrentType);
10911 CurrentType = AT->getElementType();
10912 } else
10913 CurrentType = Context.DependentTy;
10914
Richard Smithea011432011-10-17 23:29:39 +000010915 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10916 if (IdxRval.isInvalid())
10917 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010918 Expr *Idx = IdxRval.get();
Richard Smithea011432011-10-17 23:29:39 +000010919
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010920 // The expression must be an integral expression.
10921 // FIXME: An integral constant expression?
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010922 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10923 !Idx->getType()->isIntegerType())
10924 return ExprError(Diag(Idx->getLocStart(),
10925 diag::err_typecheck_subscript_not_integer)
10926 << Idx->getSourceRange());
Richard Smithd82e5d32011-10-17 05:48:07 +000010927
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010928 // Record this array index.
10929 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smithea011432011-10-17 23:29:39 +000010930 Exprs.push_back(Idx);
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010931 continue;
10932 }
10933
10934 // Offset of a field.
10935 if (CurrentType->isDependentType()) {
10936 // We have the offset of a field, but we can't look into the dependent
10937 // type. Just record the identifier of the field.
10938 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10939 CurrentType = Context.DependentTy;
10940 continue;
10941 }
10942
10943 // We need to have a complete type to look into.
10944 if (RequireCompleteType(OC.LocStart, CurrentType,
10945 diag::err_offsetof_incomplete_type))
10946 return ExprError();
10947
10948 // Look for the designated field.
10949 const RecordType *RC = CurrentType->getAs<RecordType>();
10950 if (!RC)
10951 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10952 << CurrentType);
10953 RecordDecl *RD = RC->getDecl();
10954
10955 // C++ [lib.support.types]p5:
10956 // The macro offsetof accepts a restricted set of type arguments in this
10957 // International Standard. type shall be a POD structure or a POD union
10958 // (clause 9).
Benjamin Kramer98f71aa2012-04-28 11:14:51 +000010959 // C++11 [support.types]p4:
10960 // If type is not a standard-layout class (Clause 9), the results are
10961 // undefined.
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010962 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Richard Smith80ad52f2013-01-02 11:42:31 +000010963 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
Benjamin Kramer98f71aa2012-04-28 11:14:51 +000010964 unsigned DiagID =
Stephen Hines176edba2014-12-01 14:53:08 -080010965 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10966 : diag::ext_offsetof_non_pod_type;
Benjamin Kramer98f71aa2012-04-28 11:14:51 +000010967
10968 if (!IsSafe && !DidWarnAboutNonPOD &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010969 DiagRuntimeBehavior(BuiltinLoc, nullptr,
Benjamin Kramer98f71aa2012-04-28 11:14:51 +000010970 PDiag(DiagID)
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010971 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10972 << CurrentType))
10973 DidWarnAboutNonPOD = true;
10974 }
10975
10976 // Look for the field.
10977 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10978 LookupQualifiedName(R, RD);
10979 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010980 IndirectFieldDecl *IndirectMemberDecl = nullptr;
Francois Pichet87c2e122010-11-21 06:08:52 +000010981 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +000010982 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +000010983 MemberDecl = IndirectMemberDecl->getAnonField();
10984 }
10985
Douglas Gregor8ecdb652010-04-28 22:16:22 +000010986 if (!MemberDecl)
10987 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10988 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10989 OC.LocEnd));
10990
Douglas Gregor9d5d60f2010-04-28 22:36:06 +000010991 // C99 7.17p3:
10992 // (If the specified member is a bit-field, the behavior is undefined.)
10993 //
10994 // We diagnose this as an error.
Richard Smitha6b8b2c2011-10-10 18:28:20 +000010995 if (MemberDecl->isBitField()) {
Douglas Gregor9d5d60f2010-04-28 22:36:06 +000010996 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10997 << MemberDecl->getDeclName()
10998 << SourceRange(BuiltinLoc, RParenLoc);
10999 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11000 return ExprError();
11001 }
Eli Friedman19410a72010-08-05 10:11:36 +000011002
11003 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +000011004 if (IndirectMemberDecl)
11005 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +000011006
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000011007 // If the member was found in a base class, introduce OffsetOfNodes for
11008 // the base class indirections.
David Majnemeredb5fdf2013-10-15 06:28:23 +000011009 CXXBasePaths Paths;
Eli Friedman19410a72010-08-05 10:11:36 +000011010 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
David Majnemeredb5fdf2013-10-15 06:28:23 +000011011 if (Paths.getDetectedVirtual()) {
11012 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11013 << MemberDecl->getDeclName()
11014 << SourceRange(BuiltinLoc, RParenLoc);
11015 return ExprError();
11016 }
11017
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000011018 CXXBasePath &Path = Paths.front();
11019 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
11020 B != BEnd; ++B)
11021 Comps.push_back(OffsetOfNode(B->Base));
11022 }
Eli Friedman19410a72010-08-05 10:11:36 +000011023
Francois Pichet87c2e122010-11-21 06:08:52 +000011024 if (IndirectMemberDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011025 for (auto *FI : IndirectMemberDecl->chain()) {
11026 assert(isa<FieldDecl>(FI));
Francois Pichet87c2e122010-11-21 06:08:52 +000011027 Comps.push_back(OffsetOfNode(OC.LocStart,
Stephen Hines651f13c2014-04-23 16:59:28 -070011028 cast<FieldDecl>(FI), OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +000011029 }
11030 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +000011031 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +000011032
Douglas Gregor8ecdb652010-04-28 22:16:22 +000011033 CurrentType = MemberDecl->getType().getNonReferenceType();
11034 }
11035
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011036 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11037 Comps, Exprs, RParenLoc);
Douglas Gregor8ecdb652010-04-28 22:16:22 +000011038}
Mike Stumpeed9cac2009-02-19 03:04:26 +000011039
John McCall60d7b3a2010-08-24 06:29:42 +000011040ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +000011041 SourceLocation BuiltinLoc,
11042 SourceLocation TypeLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011043 ParsedType ParsedArgTy,
John McCall2cd11fe2010-10-12 02:09:17 +000011044 OffsetOfComponent *CompPtr,
11045 unsigned NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +000011046 SourceLocation RParenLoc) {
John McCall2cd11fe2010-10-12 02:09:17 +000011047
Douglas Gregor8ecdb652010-04-28 22:16:22 +000011048 TypeSourceInfo *ArgTInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +000011049 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor8ecdb652010-04-28 22:16:22 +000011050 if (ArgTy.isNull())
11051 return ExprError();
11052
Eli Friedman5a15dc12010-08-05 10:15:45 +000011053 if (!ArgTInfo)
11054 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11055
11056 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuccd891a2011-09-09 01:45:06 +000011057 RParenLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +000011058}
11059
11060
John McCall60d7b3a2010-08-24 06:29:42 +000011061ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +000011062 Expr *CondExpr,
11063 Expr *LHSExpr, Expr *RHSExpr,
11064 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +000011065 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11066
John McCallf89e55a2010-11-18 06:31:45 +000011067 ExprValueKind VK = VK_RValue;
11068 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +000011069 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +000011070 bool ValueDependent = false;
Eli Friedmana5e66012013-07-20 00:40:58 +000011071 bool CondIsTrue = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +000011072 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +000011073 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +000011074 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +000011075 } else {
11076 // The conditional expression is required to be a constant expression.
11077 llvm::APSInt condEval(32);
Douglas Gregorab41fe92012-05-04 22:38:52 +000011078 ExprResult CondICE
11079 = VerifyIntegerConstantExpression(CondExpr, &condEval,
11080 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smith282e7e62012-02-04 09:53:13 +000011081 if (CondICE.isInvalid())
11082 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011083 CondExpr = CondICE.get();
Eli Friedmana5e66012013-07-20 00:40:58 +000011084 CondIsTrue = condEval.getZExtValue();
Steve Naroffd04fdd52007-08-03 21:21:27 +000011085
Sebastian Redl28507842009-02-26 14:39:58 +000011086 // If the condition is > zero, then the AST type is the same as the LSHExpr.
Eli Friedmana5e66012013-07-20 00:40:58 +000011087 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
John McCallf89e55a2010-11-18 06:31:45 +000011088
11089 resType = ActiveExpr->getType();
11090 ValueDependent = ActiveExpr->isValueDependent();
11091 VK = ActiveExpr->getValueKind();
11092 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +000011093 }
11094
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011095 return new (Context)
11096 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11097 CondIsTrue, resType->isDependentType(), ValueDependent);
Steve Naroffd04fdd52007-08-03 21:21:27 +000011098}
11099
Steve Naroff4eb206b2008-09-03 18:15:37 +000011100//===----------------------------------------------------------------------===//
11101// Clang Extensions.
11102//===----------------------------------------------------------------------===//
11103
11104/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuccd891a2011-09-09 01:45:06 +000011105void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000011106 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Eli Friedman07369dd2013-07-01 20:22:57 +000011107
Eli Friedman0f115b32013-09-12 22:36:24 +000011108 if (LangOpts.CPlusPlus) {
Eli Friedman07369dd2013-07-01 20:22:57 +000011109 Decl *ManglingContextDecl;
11110 if (MangleNumberingContext *MCtx =
11111 getCurrentMangleNumberContext(Block->getDeclContext(),
11112 ManglingContextDecl)) {
11113 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11114 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11115 }
11116 }
11117
Richard Trieuccd891a2011-09-09 01:45:06 +000011118 PushBlockScope(CurScope, Block);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000011119 CurContext->addDecl(Block);
Richard Trieuccd891a2011-09-09 01:45:06 +000011120 if (CurScope)
11121 PushDeclContext(CurScope, Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +000011122 else
11123 CurContext = Block;
John McCall538773c2011-11-11 03:19:12 +000011124
Eli Friedman84b007f2012-01-26 03:00:14 +000011125 getCurBlock()->HasImplicitReturnType = true;
11126
John McCall538773c2011-11-11 03:19:12 +000011127 // Enter a new evaluation context to insulate the block from any
11128 // cleanups from the enclosing full-expression.
11129 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff090276f2008-10-10 01:28:17 +000011130}
11131
Douglas Gregor03f1eb02012-06-15 16:59:29 +000011132void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11133 Scope *CurScope) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011134 assert(ParamInfo.getIdentifier() == nullptr &&
11135 "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +000011136 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000011137 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011138
John McCallbf1a0282010-06-04 23:28:52 +000011139 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +000011140 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +000011141
Douglas Gregor03f1eb02012-06-15 16:59:29 +000011142 // FIXME: We should allow unexpanded parameter packs here, but that would,
11143 // in turn, make the block expression contain unexpanded parameter packs.
11144 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11145 // Drop the parameters.
11146 FunctionProtoType::ExtProtoInfo EPI;
11147 EPI.HasTrailingReturn = false;
11148 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko55431692013-05-05 00:41:58 +000011149 T = Context.getFunctionType(Context.DependentTy, None, EPI);
Douglas Gregor03f1eb02012-06-15 16:59:29 +000011150 Sig = Context.getTrivialTypeSourceInfo(T);
11151 }
11152
John McCall711c52b2011-01-05 12:14:39 +000011153 // GetTypeForDeclarator always produces a function type for a block
11154 // literal signature. Furthermore, it is always a FunctionProtoType
11155 // unless the function was written with a typedef.
11156 assert(T->isFunctionType() &&
11157 "GetTypeForDeclarator made a non-function block signature");
11158
11159 // Look for an explicit signature in that function type.
11160 FunctionProtoTypeLoc ExplicitSignature;
11161
11162 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +000011163 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
John McCall711c52b2011-01-05 12:14:39 +000011164
11165 // Check whether that explicit signature was synthesized by
11166 // GetTypeForDeclarator. If so, don't save that as part of the
11167 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +000011168 if (ExplicitSignature.getLocalRangeBegin() ==
11169 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +000011170 // This would be much cheaper if we stored TypeLocs instead of
11171 // TypeSourceInfos.
Stephen Hines651f13c2014-04-23 16:59:28 -070011172 TypeLoc Result = ExplicitSignature.getReturnLoc();
John McCall711c52b2011-01-05 12:14:39 +000011173 unsigned Size = Result.getFullDataSize();
11174 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11175 Sig->getTypeLoc().initializeFullCopy(Result, Size);
11176
11177 ExplicitSignature = FunctionProtoTypeLoc();
11178 }
John McCall82dc0092010-06-04 11:21:44 +000011179 }
Mike Stump1eb44332009-09-09 15:08:12 +000011180
John McCall711c52b2011-01-05 12:14:39 +000011181 CurBlock->TheDecl->setSignatureAsWritten(Sig);
11182 CurBlock->FunctionType = T;
11183
11184 const FunctionType *Fn = T->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -070011185 QualType RetTy = Fn->getReturnType();
John McCall711c52b2011-01-05 12:14:39 +000011186 bool isVariadic =
11187 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11188
John McCallc71a4912010-06-04 19:02:56 +000011189 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +000011190
John McCall82dc0092010-06-04 11:21:44 +000011191 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +000011192 // return type. TODO: what should we do with declarators like:
11193 // ^ * { ... }
11194 // If the answer is "apply template argument deduction"....
Fariborz Jahanian05865202011-12-03 17:47:53 +000011195 if (RetTy != Context.DependentTy) {
John McCall82dc0092010-06-04 11:21:44 +000011196 CurBlock->ReturnType = RetTy;
Fariborz Jahanian05865202011-12-03 17:47:53 +000011197 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman84b007f2012-01-26 03:00:14 +000011198 CurBlock->HasImplicitReturnType = false;
Fariborz Jahanian05865202011-12-03 17:47:53 +000011199 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000011200
John McCall82dc0092010-06-04 11:21:44 +000011201 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +000011202 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +000011203 if (ExplicitSignature) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011204 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11205 ParmVarDecl *Param = ExplicitSignature.getParam(I);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011206 if (Param->getIdentifier() == nullptr &&
Fariborz Jahanian9a66c302010-02-12 21:53:14 +000011207 !Param->isImplicit() &&
11208 !Param->isInvalidDecl() &&
David Blaikie4e4d0842012-03-11 07:00:24 +000011209 !getLangOpts().CPlusPlus)
Fariborz Jahanian9a66c302010-02-12 21:53:14 +000011210 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +000011211 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +000011212 }
John McCall82dc0092010-06-04 11:21:44 +000011213
11214 // Fake up parameter variables if we have a typedef, like
11215 // ^ fntype { ... }
11216 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011217 for (const auto &I : Fn->param_types()) {
11218 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11219 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
John McCallc71a4912010-06-04 19:02:56 +000011220 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +000011221 }
Steve Naroff4eb206b2008-09-03 18:15:37 +000011222 }
John McCall82dc0092010-06-04 11:21:44 +000011223
John McCallc71a4912010-06-04 19:02:56 +000011224 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +000011225 if (!Params.empty()) {
David Blaikie4278c652011-09-21 18:16:56 +000011226 CurBlock->TheDecl->setParams(Params);
Douglas Gregor82aa7132010-11-01 18:37:59 +000011227 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11228 CurBlock->TheDecl->param_end(),
11229 /*CheckParameterNames=*/false);
11230 }
11231
John McCall82dc0092010-06-04 11:21:44 +000011232 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011233 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +000011234
Eli Friedman07369dd2013-07-01 20:22:57 +000011235 // Put the parameter variables in scope.
Stephen Hines651f13c2014-04-23 16:59:28 -070011236 for (auto AI : CurBlock->TheDecl->params()) {
11237 AI->setOwningFunction(CurBlock->TheDecl);
John McCall7a9813c2010-01-22 00:28:27 +000011238
Steve Naroff090276f2008-10-10 01:28:17 +000011239 // If this has an identifier, add it to the scope stack.
Stephen Hines651f13c2014-04-23 16:59:28 -070011240 if (AI->getIdentifier()) {
11241 CheckShadow(CurBlock->TheScope, AI);
John McCall053f4bd2010-03-22 09:20:08 +000011242
Stephen Hines651f13c2014-04-23 16:59:28 -070011243 PushOnScopeChains(AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +000011244 }
John McCall7a9813c2010-01-22 00:28:27 +000011245 }
Steve Naroff4eb206b2008-09-03 18:15:37 +000011246}
11247
11248/// ActOnBlockError - If there is an error parsing a block, this callback
11249/// is invoked to pop the information about the block from the action impl.
11250void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCall538773c2011-11-11 03:19:12 +000011251 // Leave the expression-evaluation context.
11252 DiscardCleanupsInEvaluationContext();
11253 PopExpressionEvaluationContext();
11254
Steve Naroff4eb206b2008-09-03 18:15:37 +000011255 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +000011256 PopDeclContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +000011257 PopFunctionScopeInfo();
Steve Naroff4eb206b2008-09-03 18:15:37 +000011258}
11259
11260/// ActOnBlockStmtExpr - This is called when the body of a block statement
11261/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +000011262ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +000011263 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +000011264 // If blocks are disabled, emit an error.
11265 if (!LangOpts.Blocks)
11266 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +000011267
John McCall538773c2011-11-11 03:19:12 +000011268 // Leave the expression-evaluation context.
John McCall1e5bc4f2012-03-08 22:00:17 +000011269 if (hasAnyUnrecoverableErrorsInThisFunction())
11270 DiscardCleanupsInEvaluationContext();
John McCall538773c2011-11-11 03:19:12 +000011271 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11272 PopExpressionEvaluationContext();
11273
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000011274 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Jordan Rose7dd900e2012-07-02 21:19:23 +000011275
11276 if (BSI->HasImplicitReturnType)
11277 deduceClosureReturnType(*BSI);
11278
Steve Naroff090276f2008-10-10 01:28:17 +000011279 PopDeclContext();
11280
Steve Naroff4eb206b2008-09-03 18:15:37 +000011281 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +000011282 if (!BSI->ReturnType.isNull())
11283 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +000011284
Stephen Hines651f13c2014-04-23 16:59:28 -070011285 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +000011286 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +000011287
John McCall469a1eb2011-02-02 13:00:07 +000011288 // Set the captured variables on the block.
Eli Friedmanb69b42c2012-01-11 02:36:31 +000011289 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11290 SmallVector<BlockDecl::Capture, 4> Captures;
11291 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
11292 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
11293 if (Cap.isThisCapture())
11294 continue;
Eli Friedmanb942cb22012-02-03 22:47:37 +000011295 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Richard Smith0d8e9642013-05-16 06:20:58 +000011296 Cap.isNested(), Cap.getInitExpr());
Eli Friedmanb69b42c2012-01-11 02:36:31 +000011297 Captures.push_back(NewCap);
11298 }
11299 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
11300 BSI->CXXThisCaptureIndex != 0);
John McCall469a1eb2011-02-02 13:00:07 +000011301
John McCallc71a4912010-06-04 19:02:56 +000011302 // If the user wrote a function type in some form, try to use that.
11303 if (!BSI->FunctionType.isNull()) {
11304 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11305
11306 FunctionType::ExtInfo Ext = FTy->getExtInfo();
11307 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11308
11309 // Turn protoless block types into nullary block types.
11310 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +000011311 FunctionProtoType::ExtProtoInfo EPI;
11312 EPI.ExtInfo = Ext;
Dmitri Gribenko55431692013-05-05 00:41:58 +000011313 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCallc71a4912010-06-04 19:02:56 +000011314
11315 // Otherwise, if we don't need to change anything about the function type,
11316 // preserve its sugar structure.
Stephen Hines651f13c2014-04-23 16:59:28 -070011317 } else if (FTy->getReturnType() == RetTy &&
John McCallc71a4912010-06-04 19:02:56 +000011318 (!NoReturn || FTy->getNoReturnAttr())) {
11319 BlockTy = BSI->FunctionType;
11320
11321 // Otherwise, make the minimal modifications to the function type.
11322 } else {
11323 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +000011324 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11325 EPI.TypeQuals = 0; // FIXME: silently?
11326 EPI.ExtInfo = Ext;
Stephen Hines651f13c2014-04-23 16:59:28 -070011327 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
John McCallc71a4912010-06-04 19:02:56 +000011328 }
11329
11330 // If we don't have a function type, just build one from nothing.
11331 } else {
John McCalle23cf432010-12-14 08:05:40 +000011332 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +000011333 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
Dmitri Gribenko55431692013-05-05 00:41:58 +000011334 BlockTy = Context.getFunctionType(RetTy, None, EPI);
John McCallc71a4912010-06-04 19:02:56 +000011335 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000011336
John McCallc71a4912010-06-04 19:02:56 +000011337 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11338 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +000011339 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +000011340
Chris Lattner17a78302009-04-19 05:28:12 +000011341 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +000011342 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor27bec772012-08-17 05:12:08 +000011343 !PP.isCodeCompletionEnabled())
John McCall9ae2f072010-08-23 23:25:46 +000011344 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +000011345
Chris Lattnere476bdc2011-02-17 23:58:47 +000011346 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011347
Jordan Rose7dd900e2012-07-02 21:19:23 +000011348 // Try to apply the named return value optimization. We have to check again
11349 // if we can do this, though, because blocks keep return statements around
11350 // to deduce an implicit return type.
11351 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11352 !BSI->TheDecl->isDependentContext())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011353 computeNRVO(Body, BSI);
Douglas Gregorf8b7f712011-09-06 20:46:03 +000011354
Benjamin Kramerd2486192011-07-12 14:11:05 +000011355 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
David Blaikie82b97092013-09-03 21:40:15 +000011356 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedmanec9ea722012-01-05 03:35:19 +000011357 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramerd2486192011-07-12 14:11:05 +000011358
John McCall80ee6e82011-11-10 05:35:25 +000011359 // If the block isn't obviously global, i.e. it captures anything at
John McCall97b57a22012-04-13 01:08:17 +000011360 // all, then we need to do a few things in the surrounding context:
John McCall80ee6e82011-11-10 05:35:25 +000011361 if (Result->getBlockDecl()->hasCaptures()) {
John McCall97b57a22012-04-13 01:08:17 +000011362 // First, this expression has a new cleanup object.
John McCall80ee6e82011-11-10 05:35:25 +000011363 ExprCleanupObjects.push_back(Result->getBlockDecl());
11364 ExprNeedsCleanups = true;
John McCall97b57a22012-04-13 01:08:17 +000011365
11366 // It also gets a branch-protected scope if any of the captured
11367 // variables needs destruction.
Stephen Hines651f13c2014-04-23 16:59:28 -070011368 for (const auto &CI : Result->getBlockDecl()->captures()) {
11369 const VarDecl *var = CI.getVariable();
John McCall97b57a22012-04-13 01:08:17 +000011370 if (var->getType().isDestructedType() != QualType::DK_none) {
11371 getCurFunction()->setHasBranchProtectedScope();
11372 break;
11373 }
11374 }
John McCall80ee6e82011-11-10 05:35:25 +000011375 }
Fariborz Jahanian27949f62012-03-06 18:41:35 +000011376
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011377 return Result;
Steve Naroff4eb206b2008-09-03 18:15:37 +000011378}
11379
John McCall60d7b3a2010-08-24 06:29:42 +000011380ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuccd891a2011-09-09 01:45:06 +000011381 Expr *E, ParsedType Ty,
Sebastian Redlf53597f2009-03-15 17:47:39 +000011382 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +000011383 TypeSourceInfo *TInfo;
Richard Trieuccd891a2011-09-09 01:45:06 +000011384 GetTypeFromParser(Ty, &TInfo);
11385 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +000011386}
11387
John McCall60d7b3a2010-08-24 06:29:42 +000011388ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +000011389 Expr *E, TypeSourceInfo *TInfo,
11390 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +000011391 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +000011392
Eli Friedmanc34bcde2008-08-09 23:32:40 +000011393 // Get the va_list type
11394 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +000011395 if (VaListType->isArrayType()) {
11396 // Deal with implicit array decay; for example, on x86-64,
11397 // va_list is an array, but it's supposed to decay to
11398 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +000011399 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +000011400 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +000011401 ExprResult Result = UsualUnaryConversions(E);
11402 if (Result.isInvalid())
11403 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011404 E = Result.get();
Logan Chienb687f3b2012-10-20 06:11:33 +000011405 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11406 // If va_list is a record type and we are compiling in C++ mode,
11407 // check the argument using reference binding.
11408 InitializedEntity Entity
11409 = InitializedEntity::InitializeParameter(Context,
11410 Context.getLValueReferenceType(VaListType), false);
11411 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11412 if (Init.isInvalid())
11413 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011414 E = Init.getAs<Expr>();
Eli Friedman5c091ba2009-05-16 12:46:54 +000011415 } else {
11416 // Otherwise, the va_list argument must be an l-value because
11417 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +000011418 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +000011419 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +000011420 return ExprError();
11421 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +000011422
Douglas Gregordd027302009-05-19 23:10:31 +000011423 if (!E->isTypeDependent() &&
11424 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +000011425 return ExprError(Diag(E->getLocStart(),
11426 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +000011427 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +000011428 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000011429
David Majnemer0adde122011-06-14 05:17:32 +000011430 if (!TInfo->getType()->isDependentType()) {
11431 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011432 diag::err_second_parameter_to_va_arg_incomplete,
11433 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +000011434 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +000011435
David Majnemer0adde122011-06-14 05:17:32 +000011436 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +000011437 TInfo->getType(),
11438 diag::err_second_parameter_to_va_arg_abstract,
11439 TInfo->getTypeLoc()))
David Majnemer0adde122011-06-14 05:17:32 +000011440 return ExprError();
11441
Douglas Gregor4eb75222011-07-30 06:45:27 +000011442 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +000011443 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +000011444 TInfo->getType()->isObjCLifetimeType()
11445 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11446 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +000011447 << TInfo->getType()
11448 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +000011449 }
Eli Friedman46d37c12011-07-11 21:45:59 +000011450
11451 // Check for va_arg where arguments of the given type will be promoted
11452 // (i.e. this va_arg is guaranteed to have undefined behavior).
11453 QualType PromoteType;
11454 if (TInfo->getType()->isPromotableIntegerType()) {
11455 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11456 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11457 PromoteType = QualType();
11458 }
11459 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11460 PromoteType = Context.DoubleTy;
11461 if (!PromoteType.isNull())
Ted Kremenekcbb99ef2013-01-08 01:50:40 +000011462 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11463 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11464 << TInfo->getType()
11465 << PromoteType
11466 << TInfo->getTypeLoc().getSourceRange());
David Majnemer0adde122011-06-14 05:17:32 +000011467 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000011468
Abramo Bagnara2cad9002010-08-10 10:06:15 +000011469 QualType T = TInfo->getType().getNonLValueExprType(Context);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011470 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
Anders Carlsson7c50aca2007-10-15 20:28:48 +000011471}
11472
John McCall60d7b3a2010-08-24 06:29:42 +000011473ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +000011474 // The type of __null will be int or long, depending on the size of
11475 // pointers on the target.
11476 QualType Ty;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000011477 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11478 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000011479 Ty = Context.IntTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000011480 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000011481 Ty = Context.LongTy;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000011482 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000011483 Ty = Context.LongLongTy;
11484 else {
David Blaikieb219cfc2011-09-23 05:06:16 +000011485 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000011486 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +000011487
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011488 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +000011489}
11490
Stephen Hines651f13c2014-04-23 16:59:28 -070011491bool
11492Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
11493 if (!getLangOpts().ObjC1)
11494 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011495
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000011496 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11497 if (!PT)
Stephen Hines651f13c2014-04-23 16:59:28 -070011498 return false;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000011499
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000011500 if (!PT->isObjCIdType()) {
11501 // Check if the destination is the 'NSString' interface.
11502 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11503 if (!ID || !ID->getIdentifier()->isStr("NSString"))
Stephen Hines651f13c2014-04-23 16:59:28 -070011504 return false;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000011505 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011506
John McCall4b9c2d22011-11-06 09:01:30 +000011507 // Ignore any parens, implicit casts (should only be
11508 // array-to-pointer decays), and not-so-opaque values. The last is
11509 // important for making this trigger for property assignments.
Stephen Hines651f13c2014-04-23 16:59:28 -070011510 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
John McCall4b9c2d22011-11-06 09:01:30 +000011511 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11512 if (OV->getSourceExpr())
11513 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11514
11515 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregor5cee1192011-07-27 05:40:30 +000011516 if (!SL || !SL->isAscii())
Stephen Hines651f13c2014-04-23 16:59:28 -070011517 return false;
11518 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11519 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011520 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
Stephen Hines651f13c2014-04-23 16:59:28 -070011521 return true;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000011522}
11523
Chris Lattner5cf216b2008-01-04 18:04:52 +000011524bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11525 SourceLocation Loc,
11526 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +000011527 Expr *SrcExpr, AssignmentAction Action,
11528 bool *Complained) {
11529 if (Complained)
11530 *Complained = false;
11531
Chris Lattner5cf216b2008-01-04 18:04:52 +000011532 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +000011533 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011534 bool isInvalid = false;
Eli Friedmanfd819782012-02-29 20:59:56 +000011535 unsigned DiagKind = 0;
Douglas Gregor849b2432010-03-31 17:46:05 +000011536 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +000011537 ConversionFixItGenerator ConvHints;
11538 bool MayHaveConvFixit = false;
Richard Trieu6efd4c52011-11-23 22:32:32 +000011539 bool MayHaveFunctionDiff = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011540 const ObjCInterfaceDecl *IFace = nullptr;
11541 const ObjCProtocolDecl *PDecl = nullptr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000011542
Chris Lattner5cf216b2008-01-04 18:04:52 +000011543 switch (ConvTy) {
Fariborz Jahanian379b2812012-07-17 18:00:08 +000011544 case Compatible:
Bill Wendlingf41e20a2013-11-19 18:41:11 +000011545 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11546 return false;
Fariborz Jahanian379b2812012-07-17 18:00:08 +000011547
Chris Lattnerb7b61152008-01-04 18:22:42 +000011548 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +000011549 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +000011550 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11551 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011552 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +000011553 case IntToPointer:
11554 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +000011555 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11556 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +000011557 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011558 case IncompatiblePointer:
Fariborz Jahanian3d672e42013-07-31 23:19:34 +000011559 DiagKind =
11560 (Action == AA_Passing_CFAudited ?
11561 diag::err_arc_typecheck_convert_incompatible_pointer :
11562 diag::ext_typecheck_convert_incompatible_pointer);
Douglas Gregor926df6c2011-06-11 01:09:30 +000011563 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11564 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +000011565 if (Hint.isNull() && !CheckInferredResultType) {
11566 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11567 }
Fariborz Jahanian443adec2013-04-30 00:30:48 +000011568 else if (CheckInferredResultType) {
11569 SrcType = SrcType.getUnqualifiedType();
11570 DstType = DstType.getUnqualifiedType();
11571 }
Anna Zaks67221552011-07-28 19:51:27 +000011572 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011573 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +000011574 case IncompatiblePointerSign:
11575 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11576 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011577 case FunctionVoidPointer:
11578 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11579 break;
John McCall86c05f32011-02-01 00:10:29 +000011580 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +000011581 // Perform array-to-pointer decay if necessary.
11582 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11583
John McCall86c05f32011-02-01 00:10:29 +000011584 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11585 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11586 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11587 DiagKind = diag::err_typecheck_incompatible_address_space;
11588 break;
John McCallf85e1932011-06-15 23:02:42 +000011589
11590
11591 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000011592 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +000011593 break;
John McCall86c05f32011-02-01 00:10:29 +000011594 }
11595
11596 llvm_unreachable("unknown error case for discarding qualifiers!");
11597 // fallthrough
11598 }
Chris Lattner5cf216b2008-01-04 18:04:52 +000011599 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +000011600 // If the qualifiers lost were because we were applying the
11601 // (deprecated) C++ conversion from a string literal to a char*
11602 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
11603 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +000011604 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +000011605 // bit of refactoring (so that the second argument is an
11606 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +000011607 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +000011608 // C++ semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000011609 if (getLangOpts().CPlusPlus &&
Douglas Gregor77a52232008-09-12 00:47:35 +000011610 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11611 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011612 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11613 break;
Sean Huntc9132b62009-11-08 07:46:34 +000011614 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +000011615 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +000011616 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +000011617 case IntToBlockPointer:
11618 DiagKind = diag::err_int_to_block_pointer;
11619 break;
11620 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +000011621 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +000011622 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011623 case IncompatibleObjCQualifiedId: {
11624 if (SrcType->isObjCQualifiedIdType()) {
11625 const ObjCObjectPointerType *srcOPT =
11626 SrcType->getAs<ObjCObjectPointerType>();
11627 for (auto *srcProto : srcOPT->quals()) {
11628 PDecl = srcProto;
11629 break;
11630 }
11631 if (const ObjCInterfaceType *IFaceT =
11632 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11633 IFace = IFaceT->getDecl();
11634 }
11635 else if (DstType->isObjCQualifiedIdType()) {
11636 const ObjCObjectPointerType *dstOPT =
11637 DstType->getAs<ObjCObjectPointerType>();
11638 for (auto *dstProto : dstOPT->quals()) {
11639 PDecl = dstProto;
11640 break;
11641 }
11642 if (const ObjCInterfaceType *IFaceT =
11643 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11644 IFace = IFaceT->getDecl();
11645 }
Steve Naroff39579072008-10-14 22:18:38 +000011646 DiagKind = diag::warn_incompatible_qualified_id;
11647 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011648 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +000011649 case IncompatibleVectors:
11650 DiagKind = diag::warn_incompatible_vectors;
11651 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +000011652 case IncompatibleObjCWeakRef:
11653 DiagKind = diag::err_arc_weak_unavailable_assign;
11654 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011655 case Incompatible:
11656 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +000011657 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11658 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011659 isInvalid = true;
Richard Trieu6efd4c52011-11-23 22:32:32 +000011660 MayHaveFunctionDiff = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011661 break;
11662 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000011663
Douglas Gregord4eea832010-04-09 00:35:39 +000011664 QualType FirstType, SecondType;
11665 switch (Action) {
11666 case AA_Assigning:
11667 case AA_Initializing:
11668 // The destination type comes first.
11669 FirstType = DstType;
11670 SecondType = SrcType;
11671 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000011672
Douglas Gregord4eea832010-04-09 00:35:39 +000011673 case AA_Returning:
11674 case AA_Passing:
Fariborz Jahanian3d672e42013-07-31 23:19:34 +000011675 case AA_Passing_CFAudited:
Douglas Gregord4eea832010-04-09 00:35:39 +000011676 case AA_Converting:
11677 case AA_Sending:
11678 case AA_Casting:
11679 // The source type comes first.
11680 FirstType = SrcType;
11681 SecondType = DstType;
11682 break;
11683 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000011684
Anna Zaks67221552011-07-28 19:51:27 +000011685 PartialDiagnostic FDiag = PDiag(DiagKind);
Fariborz Jahanian3d672e42013-07-31 23:19:34 +000011686 if (Action == AA_Passing_CFAudited)
Stephen Hines176edba2014-12-01 14:53:08 -080011687 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
Fariborz Jahanian3d672e42013-07-31 23:19:34 +000011688 else
11689 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
Anna Zaks67221552011-07-28 19:51:27 +000011690
11691 // If we can fix the conversion, suggest the FixIts.
11692 assert(ConvHints.isNull() || Hint.isNull());
11693 if (!ConvHints.isNull()) {
Benjamin Kramer1136ef02012-01-14 21:05:10 +000011694 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11695 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks67221552011-07-28 19:51:27 +000011696 FDiag << *HI;
11697 } else {
11698 FDiag << Hint;
11699 }
11700 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11701
Richard Trieu6efd4c52011-11-23 22:32:32 +000011702 if (MayHaveFunctionDiff)
11703 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11704
Anna Zaks67221552011-07-28 19:51:27 +000011705 Diag(Loc, FDiag);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011706 if (DiagKind == diag::warn_incompatible_qualified_id &&
11707 PDecl && IFace && !IFace->hasDefinition())
11708 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11709 << IFace->getName() << PDecl->getName();
11710
Richard Trieu6efd4c52011-11-23 22:32:32 +000011711 if (SecondType == Context.OverloadTy)
11712 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11713 FirstType);
11714
Douglas Gregor926df6c2011-06-11 01:09:30 +000011715 if (CheckInferredResultType)
11716 EmitRelatedResultTypeNote(SrcExpr);
John McCall7cca8212013-03-19 07:04:25 +000011717
11718 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11719 EmitRelatedResultTypeNoteForReturn(DstType);
Douglas Gregor926df6c2011-06-11 01:09:30 +000011720
Douglas Gregora41a8c52010-04-22 00:20:18 +000011721 if (Complained)
11722 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000011723 return isInvalid;
11724}
Anders Carlssone21555e2008-11-30 19:50:32 +000011725
Richard Smith282e7e62012-02-04 09:53:13 +000011726ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11727 llvm::APSInt *Result) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000011728 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11729 public:
Stephen Hines651f13c2014-04-23 16:59:28 -070011730 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregorab41fe92012-05-04 22:38:52 +000011731 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11732 }
11733 } Diagnoser;
11734
11735 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11736}
11737
11738ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11739 llvm::APSInt *Result,
11740 unsigned DiagID,
11741 bool AllowFold) {
11742 class IDDiagnoser : public VerifyICEDiagnoser {
11743 unsigned DiagID;
11744
11745 public:
11746 IDDiagnoser(unsigned DiagID)
11747 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11748
Stephen Hines651f13c2014-04-23 16:59:28 -070011749 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
Douglas Gregorab41fe92012-05-04 22:38:52 +000011750 S.Diag(Loc, DiagID) << SR;
11751 }
11752 } Diagnoser(DiagID);
11753
11754 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11755}
11756
11757void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11758 SourceRange SR) {
11759 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smith282e7e62012-02-04 09:53:13 +000011760}
11761
Benjamin Kramerd448ce02012-04-18 14:22:41 +000011762ExprResult
11763Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011764 VerifyICEDiagnoser &Diagnoser,
11765 bool AllowFold) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011766 SourceLocation DiagLoc = E->getLocStart();
Richard Smith282e7e62012-02-04 09:53:13 +000011767
Richard Smith80ad52f2013-01-02 11:42:31 +000011768 if (getLangOpts().CPlusPlus11) {
Richard Smith282e7e62012-02-04 09:53:13 +000011769 // C++11 [expr.const]p5:
11770 // If an expression of literal class type is used in a context where an
11771 // integral constant expression is required, then that class type shall
11772 // have a single non-explicit conversion function to an integral or
11773 // unscoped enumeration type
11774 ExprResult Converted;
Richard Smith097e0a22013-05-21 19:05:48 +000011775 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11776 public:
11777 CXX11ConvertDiagnoser(bool Silent)
11778 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11779 Silent, true) {}
Douglas Gregorab41fe92012-05-04 22:38:52 +000011780
Stephen Hines651f13c2014-04-23 16:59:28 -070011781 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11782 QualType T) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011783 return S.Diag(Loc, diag::err_ice_not_integral) << T;
11784 }
11785
Stephen Hines651f13c2014-04-23 16:59:28 -070011786 SemaDiagnosticBuilder diagnoseIncomplete(
11787 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011788 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11789 }
11790
Stephen Hines651f13c2014-04-23 16:59:28 -070011791 SemaDiagnosticBuilder diagnoseExplicitConv(
11792 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011793 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11794 }
11795
Stephen Hines651f13c2014-04-23 16:59:28 -070011796 SemaDiagnosticBuilder noteExplicitConv(
11797 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011798 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11799 << ConvTy->isEnumeralType() << ConvTy;
11800 }
11801
Stephen Hines651f13c2014-04-23 16:59:28 -070011802 SemaDiagnosticBuilder diagnoseAmbiguous(
11803 Sema &S, SourceLocation Loc, QualType T) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011804 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11805 }
11806
Stephen Hines651f13c2014-04-23 16:59:28 -070011807 SemaDiagnosticBuilder noteAmbiguous(
11808 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011809 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11810 << ConvTy->isEnumeralType() << ConvTy;
11811 }
11812
Stephen Hines651f13c2014-04-23 16:59:28 -070011813 SemaDiagnosticBuilder diagnoseConversion(
11814 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smith097e0a22013-05-21 19:05:48 +000011815 llvm_unreachable("conversion functions are permitted");
11816 }
11817 } ConvertDiagnoser(Diagnoser.Suppress);
11818
11819 Converted = PerformContextualImplicitConversion(DiagLoc, E,
11820 ConvertDiagnoser);
Richard Smith282e7e62012-02-04 09:53:13 +000011821 if (Converted.isInvalid())
11822 return Converted;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011823 E = Converted.get();
Richard Smith282e7e62012-02-04 09:53:13 +000011824 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11825 return ExprError();
11826 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11827 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregorab41fe92012-05-04 22:38:52 +000011828 if (!Diagnoser.Suppress)
11829 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith282e7e62012-02-04 09:53:13 +000011830 return ExprError();
11831 }
11832
Richard Smithdaaefc52011-12-14 23:32:26 +000011833 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11834 // in the non-ICE case.
Richard Smith80ad52f2013-01-02 11:42:31 +000011835 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
Richard Smith282e7e62012-02-04 09:53:13 +000011836 if (Result)
11837 *Result = E->EvaluateKnownConstInt(Context);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011838 return E;
Eli Friedman3b5ccca2009-04-25 22:26:58 +000011839 }
11840
Anders Carlssone21555e2008-11-30 19:50:32 +000011841 Expr::EvalResult EvalResult;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011842 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdd1f29b2011-12-12 09:28:41 +000011843 EvalResult.Diag = &Notes;
Anders Carlssone21555e2008-11-30 19:50:32 +000011844
Richard Smithdaaefc52011-12-14 23:32:26 +000011845 // Try to evaluate the expression, and produce diagnostics explaining why it's
11846 // not a constant expression as a side-effect.
11847 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11848 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11849
11850 // In C++11, we can rely on diagnostics being produced for any expression
11851 // which is not a constant expression. If no diagnostics were produced, then
11852 // this is a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +000011853 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
Richard Smithdaaefc52011-12-14 23:32:26 +000011854 if (Result)
11855 *Result = EvalResult.Val.getInt();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011856 return E;
Richard Smith282e7e62012-02-04 09:53:13 +000011857 }
11858
11859 // If our only note is the usual "invalid subexpression" note, just point
11860 // the caret at its location rather than producing an essentially
11861 // redundant note.
11862 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11863 diag::note_invalid_subexpr_in_const_expr) {
11864 DiagLoc = Notes[0].first;
11865 Notes.clear();
Richard Smithdaaefc52011-12-14 23:32:26 +000011866 }
11867
11868 if (!Folded || !AllowFold) {
Douglas Gregorab41fe92012-05-04 22:38:52 +000011869 if (!Diagnoser.Suppress) {
11870 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithdd1f29b2011-12-12 09:28:41 +000011871 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11872 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone21555e2008-11-30 19:50:32 +000011873 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000011874
Richard Smith282e7e62012-02-04 09:53:13 +000011875 return ExprError();
Anders Carlssone21555e2008-11-30 19:50:32 +000011876 }
11877
Douglas Gregorab41fe92012-05-04 22:38:52 +000011878 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith244ee7b2012-01-15 03:51:30 +000011879 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11880 Diag(Notes[I].first, Notes[I].second);
Mike Stumpeed9cac2009-02-19 03:04:26 +000011881
Anders Carlssone21555e2008-11-30 19:50:32 +000011882 if (Result)
11883 *Result = EvalResult.Val.getInt();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011884 return E;
Anders Carlssone21555e2008-11-30 19:50:32 +000011885}
Douglas Gregore0762c92009-06-19 23:52:42 +000011886
Eli Friedmanef331b72012-01-20 01:26:23 +000011887namespace {
11888 // Handle the case where we conclude a expression which we speculatively
11889 // considered to be unevaluated is actually evaluated.
11890 class TransformToPE : public TreeTransform<TransformToPE> {
11891 typedef TreeTransform<TransformToPE> BaseTransform;
11892
11893 public:
11894 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11895
11896 // Make sure we redo semantic analysis
11897 bool AlwaysRebuild() { return true; }
11898
Eli Friedman56ff2832012-02-06 23:29:57 +000011899 // Make sure we handle LabelStmts correctly.
11900 // FIXME: This does the right thing, but maybe we need a more general
11901 // fix to TreeTransform?
11902 StmtResult TransformLabelStmt(LabelStmt *S) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011903 S->getDecl()->setStmt(nullptr);
Eli Friedman56ff2832012-02-06 23:29:57 +000011904 return BaseTransform::TransformLabelStmt(S);
11905 }
11906
Eli Friedmanef331b72012-01-20 01:26:23 +000011907 // We need to special-case DeclRefExprs referring to FieldDecls which
11908 // are not part of a member pointer formation; normal TreeTransforming
11909 // doesn't catch this case because of the way we represent them in the AST.
11910 // FIXME: This is a bit ugly; is it really the best way to handle this
11911 // case?
11912 //
11913 // Error on DeclRefExprs referring to FieldDecls.
11914 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11915 if (isa<FieldDecl>(E->getDecl()) &&
David Blaikie71f55f72012-08-06 22:47:24 +000011916 !SemaRef.isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000011917 return SemaRef.Diag(E->getLocation(),
11918 diag::err_invalid_non_static_member_use)
11919 << E->getDecl() << E->getSourceRange();
11920
11921 return BaseTransform::TransformDeclRefExpr(E);
11922 }
11923
11924 // Exception: filter out member pointer formation
11925 ExprResult TransformUnaryOperator(UnaryOperator *E) {
11926 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11927 return E;
11928
11929 return BaseTransform::TransformUnaryOperator(E);
11930 }
11931
Douglas Gregore2c59132012-02-09 08:14:43 +000011932 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11933 // Lambdas never need to be transformed.
11934 return E;
11935 }
Eli Friedmanef331b72012-01-20 01:26:23 +000011936 };
Eli Friedman93c878e2012-01-18 01:05:54 +000011937}
11938
Benjamin Krameraccaf192012-11-14 15:08:31 +000011939ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
John McCallaeeacf72013-05-03 00:10:13 +000011940 assert(isUnevaluatedContext() &&
Eli Friedman72b8b1e2012-02-29 04:03:55 +000011941 "Should only transform unevaluated expressions");
Eli Friedmanef331b72012-01-20 01:26:23 +000011942 ExprEvalContexts.back().Context =
11943 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
John McCallaeeacf72013-05-03 00:10:13 +000011944 if (isUnevaluatedContext())
Eli Friedmanef331b72012-01-20 01:26:23 +000011945 return E;
11946 return TransformToPE(*this).TransformExpr(E);
Eli Friedman93c878e2012-01-18 01:05:54 +000011947}
11948
Douglas Gregor2afce722009-11-26 00:44:06 +000011949void
Douglas Gregorccc1b5e2012-02-21 00:37:24 +000011950Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smith76f3f692012-02-22 02:04:18 +000011951 Decl *LambdaContextDecl,
11952 bool IsDecltype) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070011953 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
11954 ExprNeedsCleanups, LambdaContextDecl,
11955 IsDecltype);
John McCallf85e1932011-06-15 23:02:42 +000011956 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000011957 if (!MaybeODRUseExprs.empty())
11958 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregorac7610d2009-06-22 20:57:11 +000011959}
11960
Eli Friedman80bfa3d2012-09-26 04:34:21 +000011961void
11962Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11963 ReuseLambdaContextDecl_t,
11964 bool IsDecltype) {
Eli Friedman07369dd2013-07-01 20:22:57 +000011965 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11966 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
Eli Friedman80bfa3d2012-09-26 04:34:21 +000011967}
11968
Richard Trieu67e29332011-08-02 04:35:43 +000011969void Sema::PopExpressionEvaluationContext() {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011970 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Stephen Hines176edba2014-12-01 14:53:08 -080011971 unsigned NumTypos = Rec.NumTypos;
Douglas Gregorac7610d2009-06-22 20:57:11 +000011972
Douglas Gregore2c59132012-02-09 08:14:43 +000011973 if (!Rec.Lambdas.empty()) {
David Majnemer9d33c402013-10-25 09:12:52 +000011974 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11975 unsigned D;
11976 if (Rec.isUnevaluated()) {
11977 // C++11 [expr.prim.lambda]p2:
11978 // A lambda-expression shall not appear in an unevaluated operand
11979 // (Clause 5).
11980 D = diag::err_lambda_unevaluated_operand;
11981 } else {
11982 // C++1y [expr.const]p2:
11983 // A conditional-expression e is a core constant expression unless the
11984 // evaluation of e, following the rules of the abstract machine, would
11985 // evaluate [...] a lambda-expression.
11986 D = diag::err_lambda_in_constant_expression;
11987 }
Stephen Hines176edba2014-12-01 14:53:08 -080011988 for (const auto *L : Rec.Lambdas)
11989 Diag(L->getLocStart(), D);
Douglas Gregore2c59132012-02-09 08:14:43 +000011990 } else {
11991 // Mark the capture expressions odr-used. This was deferred
11992 // during lambda expression creation.
Stephen Hines176edba2014-12-01 14:53:08 -080011993 for (auto *Lambda : Rec.Lambdas) {
11994 for (auto *C : Lambda->capture_inits())
11995 MarkDeclarationsReferencedInExpr(C);
Douglas Gregore2c59132012-02-09 08:14:43 +000011996 }
11997 }
11998 }
11999
Douglas Gregor2afce722009-11-26 00:44:06 +000012000 // When are coming out of an unevaluated context, clear out any
12001 // temporaries that we may have created as part of the evaluation of
12002 // the expression in that context: they aren't relevant because they
12003 // will never be constructed.
John McCallaeeacf72013-05-03 00:10:13 +000012004 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
John McCall80ee6e82011-11-10 05:35:25 +000012005 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12006 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000012007 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000012008 CleanupVarDeclMarking();
12009 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCallf85e1932011-06-15 23:02:42 +000012010 // Otherwise, merge the contexts together.
12011 } else {
12012 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedmand2cce132012-02-02 23:15:15 +000012013 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12014 Rec.SavedMaybeODRUseExprs.end());
John McCallf85e1932011-06-15 23:02:42 +000012015 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000012016
12017 // Pop the current expression evaluation context off the stack.
12018 ExprEvalContexts.pop_back();
Stephen Hines176edba2014-12-01 14:53:08 -080012019
12020 if (!ExprEvalContexts.empty())
12021 ExprEvalContexts.back().NumTypos += NumTypos;
12022 else
12023 assert(NumTypos == 0 && "There are outstanding typos after popping the "
12024 "last ExpressionEvaluationContextRecord");
Douglas Gregorac7610d2009-06-22 20:57:11 +000012025}
Douglas Gregore0762c92009-06-19 23:52:42 +000012026
John McCallf85e1932011-06-15 23:02:42 +000012027void Sema::DiscardCleanupsInEvaluationContext() {
John McCall80ee6e82011-11-10 05:35:25 +000012028 ExprCleanupObjects.erase(
12029 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12030 ExprCleanupObjects.end());
John McCallf85e1932011-06-15 23:02:42 +000012031 ExprNeedsCleanups = false;
Eli Friedmand2cce132012-02-02 23:15:15 +000012032 MaybeODRUseExprs.clear();
John McCallf85e1932011-06-15 23:02:42 +000012033}
12034
Eli Friedman71b8fb52012-01-21 01:01:51 +000012035ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12036 if (!E->getType()->isVariablyModifiedType())
12037 return E;
Benjamin Krameraccaf192012-11-14 15:08:31 +000012038 return TransformToPotentiallyEvaluated(E);
Eli Friedman71b8fb52012-01-21 01:01:51 +000012039}
12040
Benjamin Kramer5bbc3852012-02-06 11:13:08 +000012041static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregore0762c92009-06-19 23:52:42 +000012042 // Do not mark anything as "used" within a dependent context; wait for
12043 // an instantiation.
Eli Friedman5f2987c2012-02-02 03:46:19 +000012044 if (SemaRef.CurContext->isDependentContext())
12045 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012046
Eli Friedman5f2987c2012-02-02 03:46:19 +000012047 switch (SemaRef.ExprEvalContexts.back().Context) {
12048 case Sema::Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +000012049 case Sema::UnevaluatedAbstract:
Douglas Gregorac7610d2009-06-22 20:57:11 +000012050 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman78a54242012-01-21 04:44:06 +000012051 // (Depending on how you read the standard, we actually do need to do
12052 // something here for null pointer constants, but the standard's
12053 // definition of a null pointer constant is completely crazy.)
Eli Friedman5f2987c2012-02-02 03:46:19 +000012054 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012055
Eli Friedman5f2987c2012-02-02 03:46:19 +000012056 case Sema::ConstantEvaluated:
12057 case Sema::PotentiallyEvaluated:
Eli Friedman78a54242012-01-21 04:44:06 +000012058 // We are in a potentially evaluated expression (or a constant-expression
12059 // in C++03); we need to do implicit template instantiation, implicitly
12060 // define class members, and mark most declarations as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000012061 return true;
Mike Stump1eb44332009-09-09 15:08:12 +000012062
Eli Friedman5f2987c2012-02-02 03:46:19 +000012063 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000012064 // Referenced declarations will only be used if the construct in the
12065 // containing expression is used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000012066 return false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000012067 }
Matt Beaumont-Gay4f7dcdb2012-02-02 18:35:35 +000012068 llvm_unreachable("Invalid context");
Eli Friedman5f2987c2012-02-02 03:46:19 +000012069}
12070
12071/// \brief Mark a function referenced, and check whether it is odr-used
12072/// (C++ [basic.def.odr]p2, C99 6.9p3)
Stephen Hines176edba2014-12-01 14:53:08 -080012073void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12074 bool OdrUse) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012075 assert(Func && "No function?");
12076
12077 Func->setReferenced();
12078
Richard Smithce2661f2012-11-07 01:14:25 +000012079 // C++11 [basic.def.odr]p3:
12080 // A function whose name appears as a potentially-evaluated expression is
12081 // odr-used if it is the unique lookup result or the selected member of a
12082 // set of overloaded functions [...].
12083 //
12084 // We (incorrectly) mark overload resolution as an unevaluated context, so we
12085 // can just check that here. Skip the rest of this function if we've already
12086 // marked the function as used.
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012087 if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12088 !IsPotentiallyEvaluatedContext(*this)) {
Richard Smithce2661f2012-11-07 01:14:25 +000012089 // C++11 [temp.inst]p3:
12090 // Unless a function template specialization has been explicitly
12091 // instantiated or explicitly specialized, the function template
12092 // specialization is implicitly instantiated when the specialization is
12093 // referenced in a context that requires a function definition to exist.
12094 //
12095 // We consider constexpr function templates to be referenced in a context
12096 // that requires a definition to exist whenever they are referenced.
12097 //
12098 // FIXME: This instantiates constexpr functions too frequently. If this is
12099 // really an unevaluated context (and we're not just in the definition of a
12100 // function template or overload resolution or other cases which we
12101 // incorrectly consider to be unevaluated contexts), and we're not in a
12102 // subexpression which we actually need to evaluate (for instance, a
12103 // template argument, array bound or an expression in a braced-init-list),
12104 // we are not permitted to instantiate this constexpr function definition.
12105 //
12106 // FIXME: This also implicitly defines special members too frequently. They
12107 // are only supposed to be implicitly defined if they are odr-used, but they
12108 // are not odr-used from constant expressions in unevaluated contexts.
12109 // However, they cannot be referenced if they are deleted, and they are
12110 // deleted whenever the implicit definition of the special member would
12111 // fail.
David Majnemer645526c2013-10-23 21:31:20 +000012112 if (!Func->isConstexpr() || Func->getBody())
Richard Smithce2661f2012-11-07 01:14:25 +000012113 return;
12114 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12115 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12116 return;
12117 }
Mike Stump1eb44332009-09-09 15:08:12 +000012118
Douglas Gregore0762c92009-06-19 23:52:42 +000012119 // Note that this declaration has been used.
Eli Friedman5f2987c2012-02-02 03:46:19 +000012120 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012121 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
Richard Smith03f68782012-02-26 07:51:39 +000012122 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012123 if (Constructor->isDefaultConstructor()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012124 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012125 return;
Stephen Hines651f13c2014-04-23 16:59:28 -070012126 DefineImplicitDefaultConstructor(Loc, Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012127 } else if (Constructor->isCopyConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012128 DefineImplicitCopyConstructor(Loc, Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012129 } else if (Constructor->isMoveConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012130 DefineImplicitMoveConstructor(Loc, Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012131 }
Richard Smith07b0fdc2013-03-18 21:12:30 +000012132 } else if (Constructor->getInheritedConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012133 DefineInheritingConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +000012134 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000012135 } else if (CXXDestructorDecl *Destructor =
12136 dyn_cast<CXXDestructorDecl>(Func)) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012137 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070012138 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12139 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12140 return;
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000012141 DefineImplicitDestructor(Loc, Destructor);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070012142 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012143 if (Destructor->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012144 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedman5f2987c2012-02-02 03:46:19 +000012145 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012146 if (MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000012147 MethodDecl->getOverloadedOperator() == OO_Equal) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012148 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12149 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012150 if (MethodDecl->isCopyAssignmentOperator())
12151 DefineImplicitCopyAssignment(Loc, MethodDecl);
12152 else
12153 DefineImplicitMoveAssignment(Loc, MethodDecl);
12154 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000012155 } else if (isa<CXXConversionDecl>(MethodDecl) &&
12156 MethodDecl->getParent()->isLambda()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012157 CXXConversionDecl *Conversion =
12158 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
Douglas Gregorf6e2e022012-02-16 01:06:16 +000012159 if (Conversion->isLambdaToBlockPointerConversion())
12160 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12161 else
12162 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012163 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012164 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000012165 }
John McCall15e310a2011-02-19 02:53:41 +000012166
Eli Friedman5f2987c2012-02-02 03:46:19 +000012167 // Recursive functions should be marked when used from another function.
12168 // FIXME: Is this really right?
12169 if (CurContext == Func) return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000012170
Richard Smithb9d0b762012-07-27 04:22:15 +000012171 // Resolve the exception specification for any function which is
Richard Smithe6975e92012-04-17 00:58:00 +000012172 // used: CodeGen will need it.
Richard Smith13bffc52012-04-19 00:08:28 +000012173 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +000012174 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12175 ResolveExceptionSpec(Loc, FPT);
Richard Smithe6975e92012-04-17 00:58:00 +000012176
Stephen Hines176edba2014-12-01 14:53:08 -080012177 if (!OdrUse) return;
12178
Eli Friedman5f2987c2012-02-02 03:46:19 +000012179 // Implicit instantiation of function templates and member functions of
12180 // class templates.
12181 if (Func->isImplicitlyInstantiable()) {
12182 bool AlreadyInstantiated = false;
Richard Smith57b9c4e2012-02-14 22:25:15 +000012183 SourceLocation PointOfInstantiation = Loc;
Eli Friedman5f2987c2012-02-02 03:46:19 +000012184 if (FunctionTemplateSpecializationInfo *SpecInfo
12185 = Func->getTemplateSpecializationInfo()) {
12186 if (SpecInfo->getPointOfInstantiation().isInvalid())
12187 SpecInfo->setPointOfInstantiation(Loc);
12188 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000012189 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012190 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000012191 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12192 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000012193 } else if (MemberSpecializationInfo *MSInfo
12194 = Func->getMemberSpecializationInfo()) {
12195 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000012196 MSInfo->setPointOfInstantiation(Loc);
Eli Friedman5f2987c2012-02-02 03:46:19 +000012197 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith57b9c4e2012-02-14 22:25:15 +000012198 == TSK_ImplicitInstantiation) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012199 AlreadyInstantiated = true;
Richard Smith57b9c4e2012-02-14 22:25:15 +000012200 PointOfInstantiation = MSInfo->getPointOfInstantiation();
12201 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000012202 }
Mike Stump1eb44332009-09-09 15:08:12 +000012203
David Majnemer645526c2013-10-23 21:31:20 +000012204 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012205 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
Faisal Vali86648b12013-06-26 02:34:24 +000012206 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12207 ActiveTemplateInstantiations.size())
Richard Smith57b9c4e2012-02-14 22:25:15 +000012208 PendingLocalImplicitInstantiations.push_back(
12209 std::make_pair(Func, PointOfInstantiation));
David Majnemer645526c2013-10-23 21:31:20 +000012210 else if (Func->isConstexpr())
Eli Friedman5f2987c2012-02-02 03:46:19 +000012211 // Do not defer instantiations of constexpr functions, to avoid the
12212 // expression evaluator needing to call back into Sema if it sees a
12213 // call to such a function.
Richard Smith57b9c4e2012-02-14 22:25:15 +000012214 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000012215 else {
Richard Smith57b9c4e2012-02-14 22:25:15 +000012216 PendingInstantiations.push_back(std::make_pair(Func,
12217 PointOfInstantiation));
Argyrios Kyrtzidis6d968362012-02-10 20:10:44 +000012218 // Notify the consumer that a function was implicitly instantiated.
12219 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12220 }
John McCall15e310a2011-02-19 02:53:41 +000012221 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000012222 } else {
12223 // Walk redefinitions, as some of them may be instantiable.
Stephen Hines651f13c2014-04-23 16:59:28 -070012224 for (auto i : Func->redecls()) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012225 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Stephen Hines651f13c2014-04-23 16:59:28 -070012226 MarkFunctionReferenced(Loc, i);
Eli Friedman5f2987c2012-02-02 03:46:19 +000012227 }
Sam Weinigcce6ebc2009-09-11 03:29:30 +000012228 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000012229
12230 // Keep track of used but undefined functions.
Nick Lewyckycd0655b2013-02-01 08:13:20 +000012231 if (!Func->isDefined()) {
Rafael Espindola2d1b0962013-03-14 03:07:35 +000012232 if (mightHaveNonExternalLinkage(Func))
Nick Lewyckycd0655b2013-02-01 08:13:20 +000012233 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12234 else if (Func->getMostRecentDecl()->isInlined() &&
12235 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
12236 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12237 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
Eli Friedman5f2987c2012-02-02 03:46:19 +000012238 }
12239
Rafael Espindolaa36ddbe2013-10-19 02:06:23 +000012240 // Normally the most current decl is marked used while processing the use and
Rafael Espindolab9725cf2013-01-08 19:43:34 +000012241 // any subsequent decls are marked used by decl merging. This fails with
12242 // template instantiation since marking can happen at the end of the file
12243 // and, because of the two phase lookup, this function is called with at
12244 // decl in the middle of a decl chain. We loop to maintain the invariant
12245 // that once a decl is used, all decls after it are also used.
Rafael Espindolaa6d20202013-01-08 19:58:34 +000012246 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
Eli Friedman86164e82013-09-05 00:02:25 +000012247 F->markUsed(Context);
Rafael Espindolab9725cf2013-01-08 19:43:34 +000012248 if (F == Func)
12249 break;
Rafael Espindolab9725cf2013-01-08 19:43:34 +000012250 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000012251}
12252
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012253static void
12254diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12255 VarDecl *var, DeclContext *DC) {
Eli Friedman0a294222012-02-07 00:15:00 +000012256 DeclContext *VarDC = var->getDeclContext();
12257
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012258 // If the parameter still belongs to the translation unit, then
12259 // we're actually just using one parameter in the declaration of
12260 // the next.
12261 if (isa<ParmVarDecl>(var) &&
Eli Friedman0a294222012-02-07 00:15:00 +000012262 isa<TranslationUnitDecl>(VarDC))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012263 return;
12264
Eli Friedman0a294222012-02-07 00:15:00 +000012265 // For C code, don't diagnose about capture if we're not actually in code
12266 // right now; it's impossible to write a non-constant expression outside of
12267 // function context, so we'll get other (more useful) diagnostics later.
12268 //
12269 // For C++, things get a bit more nasty... it would be nice to suppress this
12270 // diagnostic for certain cases like using a local variable in an array bound
12271 // for a member of a local class, but the correct predicate is not obvious.
David Blaikie4e4d0842012-03-11 07:00:24 +000012272 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012273 return;
12274
Eli Friedman0a294222012-02-07 00:15:00 +000012275 if (isa<CXXMethodDecl>(VarDC) &&
12276 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12277 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12278 << var->getIdentifier();
12279 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12280 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12281 << var->getIdentifier() << fn->getDeclName();
12282 } else if (isa<BlockDecl>(VarDC)) {
12283 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12284 << var->getIdentifier();
12285 } else {
12286 // FIXME: Is there any other context where a local variable can be
12287 // declared?
12288 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12289 << var->getIdentifier();
12290 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012291
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012292 S.Diag(var->getLocation(), diag::note_entity_declared_at)
12293 << var->getIdentifier();
Eli Friedman0a294222012-02-07 00:15:00 +000012294
12295 // FIXME: Add additional diagnostic info about class etc. which prevents
12296 // capture.
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012297}
12298
Faisal Vali02d831c2013-10-07 05:13:48 +000012299
12300static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12301 bool &SubCapturesAreNested,
12302 QualType &CaptureType,
12303 QualType &DeclRefType) {
12304 // Check whether we've already captured it.
12305 if (CSI->CaptureMap.count(Var)) {
12306 // If we found a capture, any subcaptures are nested.
12307 SubCapturesAreNested = true;
12308
12309 // Retrieve the capture type for this variable.
12310 CaptureType = CSI->getCapture(Var).getCaptureType();
12311
12312 // Compute the type of an expression that refers to this variable.
12313 DeclRefType = CaptureType.getNonReferenceType();
12314
12315 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12316 if (Cap.isCopyCapture() &&
12317 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
12318 DeclRefType.addConst();
12319 return true;
12320 }
12321 return false;
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000012322}
12323
Faisal Vali02d831c2013-10-07 05:13:48 +000012324// Only block literals, captured statements, and lambda expressions can
12325// capture; other scopes don't work.
12326static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12327 SourceLocation Loc,
12328 const bool Diagnose, Sema &S) {
Faisal Valic00e4192013-11-07 05:17:06 +000012329 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12330 return getLambdaAwareParentOfDeclContext(DC);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012331 else if (Var->hasLocalStorage()) {
Faisal Vali02d831c2013-10-07 05:13:48 +000012332 if (Diagnose)
12333 diagnoseUncapturableValueReference(S, Loc, Var, DC);
12334 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012335 return nullptr;
Faisal Vali02d831c2013-10-07 05:13:48 +000012336}
12337
12338// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12339// certain types of variables (unnamed, variably modified types etc.)
12340// so check for eligibility.
12341static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12342 SourceLocation Loc,
12343 const bool Diagnose, Sema &S) {
12344
12345 bool IsBlock = isa<BlockScopeInfo>(CSI);
12346 bool IsLambda = isa<LambdaScopeInfo>(CSI);
12347
12348 // Lambdas are not allowed to capture unnamed variables
12349 // (e.g. anonymous unions).
12350 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12351 // assuming that's the intent.
12352 if (IsLambda && !Var->getDeclName()) {
12353 if (Diagnose) {
12354 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12355 S.Diag(Var->getLocation(), diag::note_declared_at);
12356 }
12357 return false;
12358 }
12359
Stephen Hines176edba2014-12-01 14:53:08 -080012360 // Prohibit variably-modified types in blocks; they're difficult to deal with.
12361 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
Faisal Vali02d831c2013-10-07 05:13:48 +000012362 if (Diagnose) {
Stephen Hines176edba2014-12-01 14:53:08 -080012363 S.Diag(Loc, diag::err_ref_vm_type);
Faisal Vali02d831c2013-10-07 05:13:48 +000012364 S.Diag(Var->getLocation(), diag::note_previous_decl)
12365 << Var->getDeclName();
12366 }
12367 return false;
12368 }
12369 // Prohibit structs with flexible array members too.
12370 // We cannot capture what is in the tail end of the struct.
12371 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12372 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12373 if (Diagnose) {
12374 if (IsBlock)
12375 S.Diag(Loc, diag::err_ref_flexarray_type);
12376 else
12377 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12378 << Var->getDeclName();
12379 S.Diag(Var->getLocation(), diag::note_previous_decl)
12380 << Var->getDeclName();
12381 }
12382 return false;
12383 }
12384 }
12385 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12386 // Lambdas and captured statements are not allowed to capture __block
12387 // variables; they don't support the expected semantics.
12388 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12389 if (Diagnose) {
12390 S.Diag(Loc, diag::err_capture_block_variable)
12391 << Var->getDeclName() << !IsLambda;
12392 S.Diag(Var->getLocation(), diag::note_previous_decl)
12393 << Var->getDeclName();
12394 }
12395 return false;
12396 }
12397
12398 return true;
12399}
12400
12401// Returns true if the capture by block was successful.
12402static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12403 SourceLocation Loc,
12404 const bool BuildAndDiagnose,
12405 QualType &CaptureType,
12406 QualType &DeclRefType,
12407 const bool Nested,
12408 Sema &S) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012409 Expr *CopyExpr = nullptr;
Faisal Vali02d831c2013-10-07 05:13:48 +000012410 bool ByRef = false;
12411
12412 // Blocks are not allowed to capture arrays.
12413 if (CaptureType->isArrayType()) {
12414 if (BuildAndDiagnose) {
12415 S.Diag(Loc, diag::err_ref_array_type);
12416 S.Diag(Var->getLocation(), diag::note_previous_decl)
12417 << Var->getDeclName();
12418 }
12419 return false;
12420 }
12421
12422 // Forbid the block-capture of autoreleasing variables.
12423 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12424 if (BuildAndDiagnose) {
12425 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12426 << /*block*/ 0;
12427 S.Diag(Var->getLocation(), diag::note_previous_decl)
12428 << Var->getDeclName();
12429 }
12430 return false;
12431 }
12432 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12433 if (HasBlocksAttr || CaptureType->isReferenceType()) {
12434 // Block capture by reference does not change the capture or
12435 // declaration reference types.
12436 ByRef = true;
12437 } else {
12438 // Block capture by copy introduces 'const'.
12439 CaptureType = CaptureType.getNonReferenceType().withConst();
12440 DeclRefType = CaptureType;
12441
12442 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12443 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12444 // The capture logic needs the destructor, so make sure we mark it.
12445 // Usually this is unnecessary because most local variables have
12446 // their destructors marked at declaration time, but parameters are
12447 // an exception because it's technically only the call site that
12448 // actually requires the destructor.
12449 if (isa<ParmVarDecl>(Var))
12450 S.FinalizeVarWithDestructor(Var, Record);
12451
12452 // Enter a new evaluation context to insulate the copy
12453 // full-expression.
12454 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12455
12456 // According to the blocks spec, the capture of a variable from
12457 // the stack requires a const copy constructor. This is not true
12458 // of the copy/move done to move a __block variable to the heap.
12459 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12460 DeclRefType.withConst(),
12461 VK_LValue, Loc);
12462
12463 ExprResult Result
12464 = S.PerformCopyInitialization(
12465 InitializedEntity::InitializeBlock(Var->getLocation(),
12466 CaptureType, false),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012467 Loc, DeclRef);
Faisal Vali02d831c2013-10-07 05:13:48 +000012468
12469 // Build a full-expression copy expression if initialization
12470 // succeeded and used a non-trivial constructor. Recover from
12471 // errors by pretending that the copy isn't necessary.
12472 if (!Result.isInvalid() &&
12473 !cast<CXXConstructExpr>(Result.get())->getConstructor()
12474 ->isTrivial()) {
12475 Result = S.MaybeCreateExprWithCleanups(Result);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012476 CopyExpr = Result.get();
Faisal Vali02d831c2013-10-07 05:13:48 +000012477 }
12478 }
12479 }
12480 }
12481
12482 // Actually capture the variable.
12483 if (BuildAndDiagnose)
12484 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12485 SourceLocation(), CaptureType, CopyExpr);
12486
12487 return true;
12488
12489}
12490
12491
12492/// \brief Capture the given variable in the captured region.
12493static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12494 VarDecl *Var,
12495 SourceLocation Loc,
12496 const bool BuildAndDiagnose,
12497 QualType &CaptureType,
12498 QualType &DeclRefType,
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012499 const bool RefersToCapturedVariable,
Faisal Vali02d831c2013-10-07 05:13:48 +000012500 Sema &S) {
12501
12502 // By default, capture variables by reference.
12503 bool ByRef = true;
12504 // Using an LValue reference type is consistent with Lambdas (see below).
12505 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012506 Expr *CopyExpr = nullptr;
Faisal Vali02d831c2013-10-07 05:13:48 +000012507 if (BuildAndDiagnose) {
12508 // The current implementation assumes that all variables are captured
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012509 // by references. Since there is no capture by copy, no expression
12510 // evaluation will be needed.
Faisal Vali02d831c2013-10-07 05:13:48 +000012511 RecordDecl *RD = RSI->TheRecordDecl;
12512
12513 FieldDecl *Field
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012514 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
Faisal Vali02d831c2013-10-07 05:13:48 +000012515 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012516 nullptr, false, ICIS_NoInit);
Faisal Vali02d831c2013-10-07 05:13:48 +000012517 Field->setImplicit(true);
12518 Field->setAccess(AS_private);
12519 RD->addDecl(Field);
12520
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012521 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
Faisal Vali02d831c2013-10-07 05:13:48 +000012522 DeclRefType, VK_LValue, Loc);
12523 Var->setReferenced(true);
12524 Var->markUsed(S.Context);
12525 }
12526
12527 // Actually capture the variable.
12528 if (BuildAndDiagnose)
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012529 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
Faisal Vali02d831c2013-10-07 05:13:48 +000012530 SourceLocation(), CaptureType, CopyExpr);
12531
12532
12533 return true;
12534}
12535
12536/// \brief Create a field within the lambda class for the variable
12537/// being captured. Handle Array captures.
12538static ExprResult addAsFieldToClosureType(Sema &S,
12539 LambdaScopeInfo *LSI,
Douglas Gregor999713e2012-02-18 09:37:24 +000012540 VarDecl *Var, QualType FieldType,
12541 QualType DeclRefType,
Douglas Gregord57f52c2012-05-16 17:01:33 +000012542 SourceLocation Loc,
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012543 bool RefersToCapturedVariable) {
Douglas Gregorf8af9822012-02-12 18:42:33 +000012544 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregorf8af9822012-02-12 18:42:33 +000012545
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012546 // Build the non-static data member.
12547 FieldDecl *Field
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012548 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012549 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012550 nullptr, false, ICIS_NoInit);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012551 Field->setImplicit(true);
12552 Field->setAccess(AS_private);
Douglas Gregor20f87a42012-02-09 02:12:34 +000012553 Lambda->addDecl(Field);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012554
12555 // C++11 [expr.prim.lambda]p21:
12556 // When the lambda-expression is evaluated, the entities that
12557 // are captured by copy are used to direct-initialize each
12558 // corresponding non-static data member of the resulting closure
12559 // object. (For array members, the array elements are
12560 // direct-initialized in increasing subscript order.) These
12561 // initializations are performed in the (unspecified) order in
12562 // which the non-static data members are declared.
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012563
Douglas Gregore2c59132012-02-09 08:14:43 +000012564 // Introduce a new evaluation context for the initialization, so
12565 // that temporaries introduced as part of the capture are retained
12566 // to be re-"exported" from the lambda expression itself.
John McCallb760f112013-03-22 02:10:40 +000012567 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012568
Douglas Gregor73d90922012-02-10 09:26:04 +000012569 // C++ [expr.prim.labda]p12:
12570 // An entity captured by a lambda-expression is odr-used (3.2) in
12571 // the scope containing the lambda-expression.
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012572 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
Douglas Gregord57f52c2012-05-16 17:01:33 +000012573 DeclRefType, VK_LValue, Loc);
Eli Friedman88530d52012-03-01 21:32:56 +000012574 Var->setReferenced(true);
Eli Friedman86164e82013-09-05 00:02:25 +000012575 Var->markUsed(S.Context);
Douglas Gregor18fe0842012-02-09 02:45:47 +000012576
12577 // When the field has array type, create index variables for each
12578 // dimension of the array. We use these index variables to subscript
12579 // the source array, and other clients (e.g., CodeGen) will perform
12580 // the necessary iteration with these index variables.
12581 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor18fe0842012-02-09 02:45:47 +000012582 QualType BaseType = FieldType;
12583 QualType SizeType = S.Context.getSizeType();
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000012584 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor18fe0842012-02-09 02:45:47 +000012585 while (const ConstantArrayType *Array
12586 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor18fe0842012-02-09 02:45:47 +000012587 // Create the iteration variable for this array index.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012588 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor18fe0842012-02-09 02:45:47 +000012589 {
12590 SmallString<8> Str;
12591 llvm::raw_svector_ostream OS(Str);
12592 OS << "__i" << IndexVariables.size();
12593 IterationVarName = &S.Context.Idents.get(OS.str());
12594 }
12595 VarDecl *IterationVar
12596 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
12597 IterationVarName, SizeType,
12598 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +000012599 SC_None);
Douglas Gregor18fe0842012-02-09 02:45:47 +000012600 IndexVariables.push_back(IterationVar);
Douglas Gregor9daa7bf2012-02-13 16:35:30 +000012601 LSI->ArrayIndexVars.push_back(IterationVar);
12602
Douglas Gregor18fe0842012-02-09 02:45:47 +000012603 // Create a reference to the iteration variable.
12604 ExprResult IterationVarRef
12605 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
12606 assert(!IterationVarRef.isInvalid() &&
12607 "Reference to invented variable cannot fail!");
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012608 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
Douglas Gregor18fe0842012-02-09 02:45:47 +000012609 assert(!IterationVarRef.isInvalid() &&
12610 "Conversion of invented variable cannot fail!");
12611
12612 // Subscript the array with this iteration variable.
12613 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012614 Ref, Loc, IterationVarRef.get(), Loc);
Douglas Gregor18fe0842012-02-09 02:45:47 +000012615 if (Subscript.isInvalid()) {
12616 S.CleanupVarDeclMarking();
12617 S.DiscardCleanupsInEvaluationContext();
Douglas Gregor18fe0842012-02-09 02:45:47 +000012618 return ExprError();
12619 }
12620
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012621 Ref = Subscript.get();
Douglas Gregor18fe0842012-02-09 02:45:47 +000012622 BaseType = Array->getElementType();
12623 }
12624
12625 // Construct the entity that we will be initializing. For an array, this
12626 // will be first element in the array, which may require several levels
12627 // of array-subscript entities.
12628 SmallVector<InitializedEntity, 4> Entities;
12629 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor47736542012-02-15 16:57:26 +000012630 Entities.push_back(
Bill Wendling2434dcf2013-12-05 05:25:04 +000012631 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
12632 Field->getType(), Loc));
Douglas Gregor18fe0842012-02-09 02:45:47 +000012633 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
12634 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
12635 0,
12636 Entities.back()));
12637
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012638 InitializationKind InitKind
12639 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000012640 InitializationSequence Init(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012641 ExprResult Result(true);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000012642 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
Benjamin Kramer5354e772012-08-23 23:38:35 +000012643 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012644
12645 // If this initialization requires any cleanups (e.g., due to a
12646 // default argument to a copy constructor), note that for the
12647 // lambda.
12648 if (S.ExprNeedsCleanups)
12649 LSI->ExprNeedsCleanups = true;
12650
12651 // Exit the expression evaluation context used for the capture.
12652 S.CleanupVarDeclMarking();
12653 S.DiscardCleanupsInEvaluationContext();
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012654 return Result;
Douglas Gregor18fe0842012-02-09 02:45:47 +000012655}
Douglas Gregor1f9a5db2012-02-09 01:56:40 +000012656
Faisal Vali02d831c2013-10-07 05:13:48 +000012657
12658
12659/// \brief Capture the given variable in the lambda.
12660static bool captureInLambda(LambdaScopeInfo *LSI,
12661 VarDecl *Var,
12662 SourceLocation Loc,
12663 const bool BuildAndDiagnose,
12664 QualType &CaptureType,
12665 QualType &DeclRefType,
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012666 const bool RefersToCapturedVariable,
Faisal Vali02d831c2013-10-07 05:13:48 +000012667 const Sema::TryCaptureKind Kind,
12668 SourceLocation EllipsisLoc,
12669 const bool IsTopScope,
12670 Sema &S) {
12671
12672 // Determine whether we are capturing by reference or by value.
12673 bool ByRef = false;
12674 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12675 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12676 } else {
12677 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12678 }
12679
12680 // Compute the type of the field that will capture this variable.
12681 if (ByRef) {
12682 // C++11 [expr.prim.lambda]p15:
12683 // An entity is captured by reference if it is implicitly or
12684 // explicitly captured but not captured by copy. It is
12685 // unspecified whether additional unnamed non-static data
12686 // members are declared in the closure type for entities
12687 // captured by reference.
12688 //
12689 // FIXME: It is not clear whether we want to build an lvalue reference
12690 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12691 // to do the former, while EDG does the latter. Core issue 1249 will
12692 // clarify, but for now we follow GCC because it's a more permissive and
12693 // easily defensible position.
12694 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12695 } else {
12696 // C++11 [expr.prim.lambda]p14:
12697 // For each entity captured by copy, an unnamed non-static
12698 // data member is declared in the closure type. The
12699 // declaration order of these members is unspecified. The type
12700 // of such a data member is the type of the corresponding
12701 // captured entity if the entity is not a reference to an
12702 // object, or the referenced type otherwise. [Note: If the
12703 // captured entity is a reference to a function, the
12704 // corresponding data member is also a reference to a
12705 // function. - end note ]
12706 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12707 if (!RefType->getPointeeType()->isFunctionType())
12708 CaptureType = RefType->getPointeeType();
12709 }
12710
12711 // Forbid the lambda copy-capture of autoreleasing variables.
12712 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12713 if (BuildAndDiagnose) {
12714 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12715 S.Diag(Var->getLocation(), diag::note_previous_decl)
12716 << Var->getDeclName();
12717 }
12718 return false;
12719 }
Douglas Gregor730a2c22013-10-11 04:25:21 +000012720
Stephen Hines651f13c2014-04-23 16:59:28 -070012721 // Make sure that by-copy captures are of a complete and non-abstract type.
12722 if (BuildAndDiagnose) {
12723 if (!CaptureType->isDependentType() &&
12724 S.RequireCompleteType(Loc, CaptureType,
12725 diag::err_capture_of_incomplete_type,
12726 Var->getDeclName()))
12727 return false;
12728
12729 if (S.RequireNonAbstractType(Loc, CaptureType,
12730 diag::err_capture_of_abstract_type))
12731 return false;
12732 }
Faisal Vali02d831c2013-10-07 05:13:48 +000012733 }
12734
12735 // Capture this variable in the lambda.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012736 Expr *CopyExpr = nullptr;
Faisal Vali02d831c2013-10-07 05:13:48 +000012737 if (BuildAndDiagnose) {
12738 ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12739 CaptureType, DeclRefType, Loc,
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012740 RefersToCapturedVariable);
Faisal Vali02d831c2013-10-07 05:13:48 +000012741 if (!Result.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012742 CopyExpr = Result.get();
Faisal Vali02d831c2013-10-07 05:13:48 +000012743 }
12744
12745 // Compute the type of a reference to this captured variable.
12746 if (ByRef)
12747 DeclRefType = CaptureType.getNonReferenceType();
12748 else {
12749 // C++ [expr.prim.lambda]p5:
12750 // The closure type for a lambda-expression has a public inline
12751 // function call operator [...]. This function call operator is
12752 // declared const (9.3.1) if and only if the lambda-expression’s
12753 // parameter-declaration-clause is not followed by mutable.
12754 DeclRefType = CaptureType.getNonReferenceType();
12755 if (!LSI->Mutable && !CaptureType->isReferenceType())
12756 DeclRefType.addConst();
12757 }
12758
12759 // Add the capture.
12760 if (BuildAndDiagnose)
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012761 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
Faisal Vali02d831c2013-10-07 05:13:48 +000012762 Loc, EllipsisLoc, CaptureType, CopyExpr);
12763
12764 return true;
12765}
12766
Faisal Vali02d831c2013-10-07 05:13:48 +000012767bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
Douglas Gregor999713e2012-02-18 09:37:24 +000012768 TryCaptureKind Kind, SourceLocation EllipsisLoc,
12769 bool BuildAndDiagnose,
12770 QualType &CaptureType,
Faisal Valic00e4192013-11-07 05:17:06 +000012771 QualType &DeclRefType,
12772 const unsigned *const FunctionScopeIndexToStopAt) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012773 bool Nested = Var->isInitCapture();
Douglas Gregorf8af9822012-02-12 18:42:33 +000012774
Eli Friedmanb942cb22012-02-03 22:47:37 +000012775 DeclContext *DC = CurContext;
Faisal Valic00e4192013-11-07 05:17:06 +000012776 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12777 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12778 // We need to sync up the Declaration Context with the
12779 // FunctionScopeIndexToStopAt
12780 if (FunctionScopeIndexToStopAt) {
12781 unsigned FSIndex = FunctionScopes.size() - 1;
12782 while (FSIndex != MaxFunctionScopesIndex) {
12783 DC = getLambdaAwareParentOfDeclContext(DC);
12784 --FSIndex;
12785 }
12786 }
Faisal Vali02d831c2013-10-07 05:13:48 +000012787
Faisal Valic00e4192013-11-07 05:17:06 +000012788
Faisal Vali02d831c2013-10-07 05:13:48 +000012789 // If the variable is declared in the current context (and is not an
12790 // init-capture), there is no need to capture it.
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012791 if (!Nested && Var->getDeclContext() == DC) return true;
12792
12793 // Capture global variables if it is required to use private copy of this
12794 // variable.
12795 bool IsGlobal = !Var->hasLocalStorage();
12796 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
12797 return true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012798
Douglas Gregor999713e2012-02-18 09:37:24 +000012799 // Walk up the stack to determine whether we can capture the variable,
12800 // performing the "simple" checks that don't depend on type. We stop when
12801 // we've either hit the declared scope of the variable or find an existing
Faisal Vali02d831c2013-10-07 05:13:48 +000012802 // capture of that variable. We start from the innermost capturing-entity
12803 // (the DC) and ensure that all intervening capturing-entities
12804 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12805 // declcontext can either capture the variable or have already captured
12806 // the variable.
Douglas Gregor999713e2012-02-18 09:37:24 +000012807 CaptureType = Var->getType();
12808 DeclRefType = CaptureType.getNonReferenceType();
12809 bool Explicit = (Kind != TryCapture_Implicit);
Faisal Vali02d831c2013-10-07 05:13:48 +000012810 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012811 do {
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000012812 // Only block literals, captured statements, and lambda expressions can
12813 // capture; other scopes don't work.
Faisal Vali02d831c2013-10-07 05:13:48 +000012814 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12815 ExprLoc,
12816 BuildAndDiagnose,
12817 *this);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070012818 // We need to check for the parent *first* because, if we *have*
12819 // private-captured a global variable, we need to recursively capture it in
12820 // intermediate blocks, lambdas, etc.
12821 if (!ParentDC) {
12822 if (IsGlobal) {
12823 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
12824 break;
12825 }
12826 return true;
12827 }
12828
Faisal Vali02d831c2013-10-07 05:13:48 +000012829 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
12830 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012831
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012832
Eli Friedmanb942cb22012-02-03 22:47:37 +000012833 // Check whether we've already captured it.
Faisal Vali02d831c2013-10-07 05:13:48 +000012834 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12835 DeclRefType))
Eli Friedman3c0e80e2012-02-03 02:04:35 +000012836 break;
Faisal Valic00e4192013-11-07 05:17:06 +000012837 // If we are instantiating a generic lambda call operator body,
12838 // we do not want to capture new variables. What was captured
12839 // during either a lambdas transformation or initial parsing
12840 // should be used.
12841 if (isGenericLambdaCallOperatorSpecialization(DC)) {
12842 if (BuildAndDiagnose) {
12843 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12844 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12845 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12846 Diag(Var->getLocation(), diag::note_previous_decl)
12847 << Var->getDeclName();
12848 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12849 } else
12850 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12851 }
12852 return true;
12853 }
Faisal Vali02d831c2013-10-07 05:13:48 +000012854 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12855 // certain types of variables (unnamed, variably modified types etc.)
12856 // so check for eligibility.
12857 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012858 return true;
12859
12860 // Try to capture variable-length arrays types.
12861 if (Var->getType()->isVariablyModifiedType()) {
12862 // We're going to walk down into the type and look for VLA
12863 // expressions.
12864 QualType QTy = Var->getType();
12865 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12866 QTy = PVD->getOriginalType();
12867 do {
12868 const Type *Ty = QTy.getTypePtr();
12869 switch (Ty->getTypeClass()) {
12870#define TYPE(Class, Base)
12871#define ABSTRACT_TYPE(Class, Base)
12872#define NON_CANONICAL_TYPE(Class, Base)
12873#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12874#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12875#include "clang/AST/TypeNodes.def"
12876 QTy = QualType();
12877 break;
12878 // These types are never variably-modified.
12879 case Type::Builtin:
12880 case Type::Complex:
12881 case Type::Vector:
12882 case Type::ExtVector:
12883 case Type::Record:
12884 case Type::Enum:
12885 case Type::Elaborated:
12886 case Type::TemplateSpecialization:
12887 case Type::ObjCObject:
12888 case Type::ObjCInterface:
12889 case Type::ObjCObjectPointer:
12890 llvm_unreachable("type class is never variably-modified!");
12891 case Type::Adjusted:
12892 QTy = cast<AdjustedType>(Ty)->getOriginalType();
12893 break;
12894 case Type::Decayed:
12895 QTy = cast<DecayedType>(Ty)->getPointeeType();
12896 break;
12897 case Type::Pointer:
12898 QTy = cast<PointerType>(Ty)->getPointeeType();
12899 break;
12900 case Type::BlockPointer:
12901 QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12902 break;
12903 case Type::LValueReference:
12904 case Type::RValueReference:
12905 QTy = cast<ReferenceType>(Ty)->getPointeeType();
12906 break;
12907 case Type::MemberPointer:
12908 QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12909 break;
12910 case Type::ConstantArray:
12911 case Type::IncompleteArray:
12912 // Losing element qualification here is fine.
12913 QTy = cast<ArrayType>(Ty)->getElementType();
12914 break;
12915 case Type::VariableArray: {
12916 // Losing element qualification here is fine.
Stephen Hines176edba2014-12-01 14:53:08 -080012917 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012918
12919 // Unknown size indication requires no size computation.
12920 // Otherwise, evaluate and record it.
Stephen Hines176edba2014-12-01 14:53:08 -080012921 if (auto Size = VAT->getSizeExpr()) {
12922 if (!CSI->isVLATypeCaptured(VAT)) {
12923 RecordDecl *CapRecord = nullptr;
12924 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12925 CapRecord = LSI->Lambda;
12926 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12927 CapRecord = CRSI->TheRecordDecl;
12928 }
12929 if (CapRecord) {
12930 auto ExprLoc = Size->getExprLoc();
12931 auto SizeType = Context.getSizeType();
12932 // Build the non-static data member.
12933 auto Field = FieldDecl::Create(
12934 Context, CapRecord, ExprLoc, ExprLoc,
12935 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12936 /*BW*/ nullptr, /*Mutable*/ false,
12937 /*InitStyle*/ ICIS_NoInit);
12938 Field->setImplicit(true);
12939 Field->setAccess(AS_private);
12940 Field->setCapturedVLAType(VAT);
12941 CapRecord->addDecl(Field);
12942
12943 CSI->addVLATypeCapture(ExprLoc, SizeType);
12944 }
12945 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012946 }
Stephen Hines176edba2014-12-01 14:53:08 -080012947 QTy = VAT->getElementType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012948 break;
12949 }
12950 case Type::FunctionProto:
12951 case Type::FunctionNoProto:
12952 QTy = cast<FunctionType>(Ty)->getReturnType();
12953 break;
12954 case Type::Paren:
12955 case Type::TypeOf:
12956 case Type::UnaryTransform:
12957 case Type::Attributed:
12958 case Type::SubstTemplateTypeParm:
12959 case Type::PackExpansion:
12960 // Keep walking after single level desugaring.
12961 QTy = QTy.getSingleStepDesugaredType(getASTContext());
12962 break;
12963 case Type::Typedef:
12964 QTy = cast<TypedefType>(Ty)->desugar();
12965 break;
12966 case Type::Decltype:
12967 QTy = cast<DecltypeType>(Ty)->desugar();
12968 break;
12969 case Type::Auto:
12970 QTy = cast<AutoType>(Ty)->getDeducedType();
12971 break;
12972 case Type::TypeOfExpr:
12973 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12974 break;
12975 case Type::Atomic:
12976 QTy = cast<AtomicType>(Ty)->getValueType();
12977 break;
12978 }
12979 } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12980 }
12981
Douglas Gregorf8af9822012-02-12 18:42:33 +000012982 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
Faisal Vali02d831c2013-10-07 05:13:48 +000012983 // No capture-default, and this is not an explicit capture
12984 // so cannot capture this variable.
Douglas Gregor999713e2012-02-18 09:37:24 +000012985 if (BuildAndDiagnose) {
Faisal Vali02d831c2013-10-07 05:13:48 +000012986 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
Douglas Gregorf8af9822012-02-12 18:42:33 +000012987 Diag(Var->getLocation(), diag::note_previous_decl)
12988 << Var->getDeclName();
12989 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12990 diag::note_lambda_decl);
Faisal Valic00e4192013-11-07 05:17:06 +000012991 // FIXME: If we error out because an outer lambda can not implicitly
12992 // capture a variable that an inner lambda explicitly captures, we
12993 // should have the inner lambda do the explicit capture - because
12994 // it makes for cleaner diagnostics later. This would purely be done
12995 // so that the diagnostic does not misleadingly claim that a variable
12996 // can not be captured by a lambda implicitly even though it is captured
12997 // explicitly. Suggestion:
12998 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12999 // at the function head
13000 // - cache the StartingDeclContext - this must be a lambda
13001 // - captureInLambda in the innermost lambda the variable.
Douglas Gregorf8af9822012-02-12 18:42:33 +000013002 }
Douglas Gregor999713e2012-02-18 09:37:24 +000013003 return true;
Douglas Gregorf8af9822012-02-12 18:42:33 +000013004 }
13005
13006 FunctionScopesIndex--;
13007 DC = ParentDC;
13008 Explicit = false;
13009 } while (!Var->getDeclContext()->Equals(DC));
13010
Faisal Vali02d831c2013-10-07 05:13:48 +000013011 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13012 // computing the type of the capture at each step, checking type-specific
13013 // requirements, and adding captures if requested.
13014 // If the variable had already been captured previously, we start capturing
13015 // at the lambda nested within that one.
13016 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
Douglas Gregor999713e2012-02-18 09:37:24 +000013017 ++I) {
13018 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor68932842012-02-18 05:51:20 +000013019
Faisal Vali02d831c2013-10-07 05:13:48 +000013020 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13021 if (!captureInBlock(BSI, Var, ExprLoc,
13022 BuildAndDiagnose, CaptureType,
13023 DeclRefType, Nested, *this))
Douglas Gregor999713e2012-02-18 09:37:24 +000013024 return true;
Douglas Gregor999713e2012-02-18 09:37:24 +000013025 Nested = true;
Faisal Vali02d831c2013-10-07 05:13:48 +000013026 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13027 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13028 BuildAndDiagnose, CaptureType,
13029 DeclRefType, Nested, *this))
John McCall100c6492012-03-30 05:23:48 +000013030 return true;
Faisal Vali02d831c2013-10-07 05:13:48 +000013031 Nested = true;
13032 } else {
13033 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13034 if (!captureInLambda(LSI, Var, ExprLoc,
13035 BuildAndDiagnose, CaptureType,
13036 DeclRefType, Nested, Kind, EllipsisLoc,
13037 /*IsTopScope*/I == N - 1, *this))
13038 return true;
13039 Nested = true;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000013040 }
Eli Friedman3c0e80e2012-02-03 02:04:35 +000013041 }
Douglas Gregor999713e2012-02-18 09:37:24 +000013042 return false;
13043}
13044
13045bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13046 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13047 QualType CaptureType;
13048 QualType DeclRefType;
13049 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13050 /*BuildAndDiagnose=*/true, CaptureType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013051 DeclRefType, nullptr);
Douglas Gregor999713e2012-02-18 09:37:24 +000013052}
13053
Stephen Hines0e2c34f2015-03-23 12:09:02 -070013054bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13055 QualType CaptureType;
13056 QualType DeclRefType;
13057 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13058 /*BuildAndDiagnose=*/false, CaptureType,
13059 DeclRefType, nullptr);
13060}
13061
Douglas Gregor999713e2012-02-18 09:37:24 +000013062QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13063 QualType CaptureType;
13064 QualType DeclRefType;
13065
13066 // Determine whether we can capture this variable.
13067 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
Faisal Valic00e4192013-11-07 05:17:06 +000013068 /*BuildAndDiagnose=*/false, CaptureType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013069 DeclRefType, nullptr))
Douglas Gregor999713e2012-02-18 09:37:24 +000013070 return QualType();
13071
13072 return DeclRefType;
Eli Friedman3c0e80e2012-02-03 02:04:35 +000013073}
13074
Eli Friedmand2cce132012-02-02 23:15:15 +000013075
Eli Friedman3c0e80e2012-02-03 02:04:35 +000013076
Faisal Valic00e4192013-11-07 05:17:06 +000013077// If either the type of the variable or the initializer is dependent,
13078// return false. Otherwise, determine whether the variable is a constant
13079// expression. Use this if you need to know if a variable that might or
13080// might not be dependent is truly a constant expression.
13081static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13082 ASTContext &Context) {
13083
13084 if (Var->getType()->isDependentType())
13085 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013086 const VarDecl *DefVD = nullptr;
Faisal Valic00e4192013-11-07 05:17:06 +000013087 Var->getAnyInitializer(DefVD);
13088 if (!DefVD)
13089 return false;
13090 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13091 Expr *Init = cast<Expr>(Eval->Value);
13092 if (Init->isValueDependent())
13093 return false;
13094 return IsVariableAConstantExpression(Var, Context);
Eli Friedmand2cce132012-02-02 23:15:15 +000013095}
13096
Faisal Valic00e4192013-11-07 05:17:06 +000013097
Eli Friedmand2cce132012-02-02 23:15:15 +000013098void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13099 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13100 // an object that satisfies the requirements for appearing in a
13101 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13102 // is immediately applied." This function handles the lvalue-to-rvalue
13103 // conversion part.
13104 MaybeODRUseExprs.erase(E->IgnoreParens());
Faisal Valic00e4192013-11-07 05:17:06 +000013105
13106 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13107 // to a variable that is a constant expression, and if so, identify it as
13108 // a reference to a variable that does not involve an odr-use of that
13109 // variable.
13110 if (LambdaScopeInfo *LSI = getCurLambda()) {
13111 Expr *SansParensExpr = E->IgnoreParens();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013112 VarDecl *Var = nullptr;
Faisal Valic00e4192013-11-07 05:17:06 +000013113 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13114 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13115 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13116 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13117
13118 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13119 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13120 }
Eli Friedmand2cce132012-02-02 23:15:15 +000013121}
13122
Eli Friedmanac626012012-02-29 03:16:56 +000013123ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
Stephen Hines176edba2014-12-01 14:53:08 -080013124 Res = CorrectDelayedTyposInExpr(Res);
13125
Eli Friedmanac626012012-02-29 03:16:56 +000013126 if (!Res.isUsable())
13127 return Res;
13128
13129 // If a constant-expression is a reference to a variable where we delay
13130 // deciding whether it is an odr-use, just assume we will apply the
13131 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
13132 // (a non-type template argument), we have special handling anyway.
13133 UpdateMarkingForLValueToRValue(Res.get());
13134 return Res;
13135}
13136
Eli Friedmand2cce132012-02-02 23:15:15 +000013137void Sema::CleanupVarDeclMarking() {
13138 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
13139 e = MaybeODRUseExprs.end();
13140 i != e; ++i) {
13141 VarDecl *Var;
13142 SourceLocation Loc;
John McCallf4b88a42012-03-10 09:33:50 +000013143 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedmand2cce132012-02-02 23:15:15 +000013144 Var = cast<VarDecl>(DRE->getDecl());
13145 Loc = DRE->getLocation();
13146 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
13147 Var = cast<VarDecl>(ME->getMemberDecl());
13148 Loc = ME->getMemberLoc();
13149 } else {
Stephen Hines176edba2014-12-01 14:53:08 -080013150 llvm_unreachable("Unexpected expression");
Eli Friedmand2cce132012-02-02 23:15:15 +000013151 }
13152
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013153 MarkVarDeclODRUsed(Var, Loc, *this,
13154 /*MaxFunctionScopeIndex Pointer*/ nullptr);
Eli Friedmand2cce132012-02-02 23:15:15 +000013155 }
13156
13157 MaybeODRUseExprs.clear();
13158}
13159
Faisal Valic00e4192013-11-07 05:17:06 +000013160
Eli Friedmand2cce132012-02-02 23:15:15 +000013161static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13162 VarDecl *Var, Expr *E) {
Benjamin Kramer3efb8e82013-11-07 11:03:53 +000013163 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13164 "Invalid Expr argument to DoMarkVarDeclReferenced");
Eli Friedman5f2987c2012-02-02 03:46:19 +000013165 Var->setReferenced();
13166
Stephen Hines176edba2014-12-01 14:53:08 -080013167 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13168 bool MarkODRUsed = true;
13169
Stephen Hines651f13c2014-04-23 16:59:28 -070013170 // If the context is not potentially evaluated, this is not an odr-use and
13171 // does not trigger instantiation.
Faisal Valic00e4192013-11-07 05:17:06 +000013172 if (!IsPotentiallyEvaluatedContext(SemaRef)) {
Stephen Hines651f13c2014-04-23 16:59:28 -070013173 if (SemaRef.isUnevaluatedContext())
13174 return;
Faisal Valic00e4192013-11-07 05:17:06 +000013175
Stephen Hines651f13c2014-04-23 16:59:28 -070013176 // If we don't yet know whether this context is going to end up being an
13177 // evaluated context, and we're referencing a variable from an enclosing
13178 // scope, add a potential capture.
13179 //
13180 // FIXME: Is this necessary? These contexts are only used for default
13181 // arguments, where local variables can't be used.
13182 const bool RefersToEnclosingScope =
13183 (SemaRef.CurContext != Var->getDeclContext() &&
Stephen Hines176edba2014-12-01 14:53:08 -080013184 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13185 if (RefersToEnclosingScope) {
13186 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13187 // If a variable could potentially be odr-used, defer marking it so
13188 // until we finish analyzing the full expression for any
13189 // lvalue-to-rvalue
13190 // or discarded value conversions that would obviate odr-use.
13191 // Add it to the list of potential captures that will be analyzed
13192 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13193 // unless the variable is a reference that was initialized by a constant
13194 // expression (this will never need to be captured or odr-used).
13195 assert(E && "Capture variable should be used in an expression.");
13196 if (!Var->getType()->isReferenceType() ||
13197 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13198 LSI->addPotentialCapture(E->IgnoreParens());
13199 }
Stephen Hines651f13c2014-04-23 16:59:28 -070013200 }
Stephen Hines176edba2014-12-01 14:53:08 -080013201
13202 if (!isTemplateInstantiation(TSK))
13203 return;
13204
13205 // Instantiate, but do not mark as odr-used, variable templates.
13206 MarkODRUsed = false;
Faisal Valic00e4192013-11-07 05:17:06 +000013207 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000013208
Larisse Voufoef4579c2013-08-06 01:03:05 +000013209 VarTemplateSpecializationDecl *VarSpec =
13210 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smithd0629eb2013-09-27 20:14:12 +000013211 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13212 "Can't instantiate a partial template specialization.");
Larisse Voufoef4579c2013-08-06 01:03:05 +000013213
Stephen Hines651f13c2014-04-23 16:59:28 -070013214 // Perform implicit instantiation of static data members, static data member
13215 // templates of class templates, and variable template specializations. Delay
13216 // instantiations of variable templates, except for those that could be used
13217 // in a constant expression.
Richard Smithd0629eb2013-09-27 20:14:12 +000013218 if (isTemplateInstantiation(TSK)) {
13219 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
Larisse Voufoef4579c2013-08-06 01:03:05 +000013220
Richard Smithd0629eb2013-09-27 20:14:12 +000013221 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13222 if (Var->getPointOfInstantiation().isInvalid()) {
13223 // This is a modification of an existing AST node. Notify listeners.
13224 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13225 L->StaticDataMemberInstantiated(Var);
13226 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13227 // Don't bother trying to instantiate it again, unless we might need
13228 // its initializer before we get to the end of the TU.
13229 TryInstantiating = false;
Larisse Voufoef4579c2013-08-06 01:03:05 +000013230 }
13231
Richard Smithd0629eb2013-09-27 20:14:12 +000013232 if (Var->getPointOfInstantiation().isInvalid())
13233 Var->setTemplateSpecializationKind(TSK, Loc);
13234
13235 if (TryInstantiating) {
13236 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
Larisse Voufoef4579c2013-08-06 01:03:05 +000013237 bool InstantiationDependent = false;
13238 bool IsNonDependent =
13239 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13240 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13241 : true;
13242
13243 // Do not instantiate specializations that are still type-dependent.
13244 if (IsNonDependent) {
13245 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13246 // Do not defer instantiations of variables which could be used in a
13247 // constant expression.
13248 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13249 } else {
13250 SemaRef.PendingInstantiations
13251 .push_back(std::make_pair(Var, PointOfInstantiation));
13252 }
Richard Smith37ce0102012-02-15 02:42:50 +000013253 }
Eli Friedman5f2987c2012-02-02 03:46:19 +000013254 }
13255 }
Stephen Hines651f13c2014-04-23 16:59:28 -070013256
Stephen Hines176edba2014-12-01 14:53:08 -080013257 if(!MarkODRUsed) return;
13258
Richard Smith5016a702012-10-20 01:38:33 +000013259 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13260 // the requirements for appearing in a constant expression (5.19) and, if
13261 // it is an object, the lvalue-to-rvalue conversion (4.1)
Eli Friedmand2cce132012-02-02 23:15:15 +000013262 // is immediately applied." We check the first part here, and
13263 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13264 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith5016a702012-10-20 01:38:33 +000013265 // C++03 depends on whether we get the C++03 version correct. The second
13266 // part does not apply to references, since they are not objects.
Faisal Valic00e4192013-11-07 05:17:06 +000013267 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
Stephen Hines651f13c2014-04-23 16:59:28 -070013268 // A reference initialized by a constant expression can never be
Faisal Valic00e4192013-11-07 05:17:06 +000013269 // odr-used, so simply ignore it.
Richard Smith5016a702012-10-20 01:38:33 +000013270 if (!Var->getType()->isReferenceType())
13271 SemaRef.MaybeODRUseExprs.insert(E);
Stephen Hines651f13c2014-04-23 16:59:28 -070013272 } else
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013273 MarkVarDeclODRUsed(Var, Loc, SemaRef,
13274 /*MaxFunctionScopeIndex ptr*/ nullptr);
Eli Friedmand2cce132012-02-02 23:15:15 +000013275}
Eli Friedman5f2987c2012-02-02 03:46:19 +000013276
Eli Friedmand2cce132012-02-02 23:15:15 +000013277/// \brief Mark a variable referenced, and check whether it is odr-used
13278/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
13279/// used directly for normal expressions referring to VarDecl.
13280void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013281 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
Eli Friedman5f2987c2012-02-02 03:46:19 +000013282}
13283
13284static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013285 Decl *D, Expr *E, bool OdrUse) {
Eli Friedmand2cce132012-02-02 23:15:15 +000013286 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13287 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13288 return;
13289 }
13290
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013291 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
Rafael Espindola0b4fe502012-06-26 17:45:31 +000013292
13293 // If this is a call to a method via a cast, also mark the method in the
13294 // derived class used in case codegen can devirtualize the call.
13295 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13296 if (!ME)
13297 return;
13298 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13299 if (!MD)
13300 return;
Stephen Hines176edba2014-12-01 14:53:08 -080013301 // Only attempt to devirtualize if this is truly a virtual call.
13302 bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
13303 if (!IsVirtualCall)
13304 return;
Rafael Espindola0b4fe502012-06-26 17:45:31 +000013305 const Expr *Base = ME->getBase();
Rafael Espindola8d852e32012-06-27 18:18:05 +000013306 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000013307 if (!MostDerivedClassDecl)
13308 return;
13309 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
Nick Lewyckyd3b4f0e2013-02-14 00:55:17 +000013310 if (!DM || DM->isPure())
Rafael Espindola0713d992012-06-27 17:44:39 +000013311 return;
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013312 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000013313}
Eli Friedman5f2987c2012-02-02 03:46:19 +000013314
Eli Friedman5f2987c2012-02-02 03:46:19 +000013315/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13316void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013317 // TODO: update this with DR# once a defect report is filed.
13318 // C++11 defect. The address of a pure member should not be an ODR use, even
13319 // if it's a qualified reference.
13320 bool OdrUse = true;
13321 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
Nick Lewycky7cea1482013-02-05 06:20:31 +000013322 if (Method->isVirtual())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013323 OdrUse = false;
13324 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
Eli Friedman5f2987c2012-02-02 03:46:19 +000013325}
13326
13327/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13328void Sema::MarkMemberReferenced(MemberExpr *E) {
Nick Lewycky869709c2013-01-31 03:15:20 +000013329 // C++11 [basic.def.odr]p2:
Nick Lewycky4ceaf332013-01-31 01:34:31 +000013330 // A non-overloaded function whose name appears as a potentially-evaluated
13331 // expression or a member of a set of candidate functions, if selected by
13332 // overload resolution when referred to from a potentially-evaluated
13333 // expression, is odr-used, unless it is a pure virtual function and its
13334 // name is not explicitly qualified.
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013335 bool OdrUse = true;
Nick Lewycky4ceaf332013-01-31 01:34:31 +000013336 if (!E->hasQualifier()) {
13337 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13338 if (Method->isPure())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013339 OdrUse = false;
Nick Lewycky4ceaf332013-01-31 01:34:31 +000013340 }
Nick Lewycky3c86a5c2013-02-12 08:08:54 +000013341 SourceLocation Loc = E->getMemberLoc().isValid() ?
13342 E->getMemberLoc() : E->getLocStart();
13343 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
Eli Friedman5f2987c2012-02-02 03:46:19 +000013344}
13345
Douglas Gregor73d90922012-02-10 09:26:04 +000013346/// \brief Perform marking for a reference to an arbitrary declaration. It
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013347/// marks the declaration referenced, and performs odr-use checking for
13348/// functions and variables. This method should not be used when building a
13349/// normal expression which refers to a variable.
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013350void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13351 if (OdrUse) {
Stephen Hines176edba2014-12-01 14:53:08 -080013352 if (auto *VD = dyn_cast<VarDecl>(D)) {
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013353 MarkVariableReferenced(Loc, VD);
13354 return;
13355 }
Stephen Hines176edba2014-12-01 14:53:08 -080013356 }
13357 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13358 MarkFunctionReferenced(Loc, FD, OdrUse);
13359 return;
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013360 }
13361 D->setReferenced();
Douglas Gregore0762c92009-06-19 23:52:42 +000013362}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000013363
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013364namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013365 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013366 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013367 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013368 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13369 Sema &S;
13370 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013371
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013372 public:
13373 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013374
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013375 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013376
13377 bool TraverseTemplateArgument(const TemplateArgument &Arg);
13378 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013379 };
13380}
13381
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013382bool MarkReferencedDecls::TraverseTemplateArgument(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013383 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013384 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregord2008e22012-04-06 22:40:38 +000013385 if (Decl *D = Arg.getAsDecl())
Nick Lewyckyb7e5eec2013-02-02 00:25:55 +000013386 S.MarkAnyDeclReferenced(Loc, D, true);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013387 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013388
13389 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013390}
13391
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013392bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013393 if (ClassTemplateSpecializationDecl *Spec
13394 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13395 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000013396 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013397 }
13398
Chandler Carruthe3e210c2010-06-10 10:31:57 +000013399 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013400}
13401
13402void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13403 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000013404 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000013405}
13406
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013407namespace {
13408 /// \brief Helper class that marks all of the declarations referenced by
13409 /// potentially-evaluated subexpressions as "referenced".
13410 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13411 Sema &S;
Douglas Gregorf4b7de12012-02-21 19:11:17 +000013412 bool SkipLocalVariables;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013413
13414 public:
13415 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13416
Douglas Gregorf4b7de12012-02-21 19:11:17 +000013417 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13418 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013419
13420 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +000013421 // If we were asked not to visit local variables, don't.
13422 if (SkipLocalVariables) {
13423 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13424 if (VD->hasLocalStorage())
13425 return;
13426 }
13427
Eli Friedman5f2987c2012-02-02 03:46:19 +000013428 S.MarkDeclRefReferenced(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013429 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013430
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013431 void VisitMemberExpr(MemberExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000013432 S.MarkMemberReferenced(E);
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000013433 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013434 }
13435
John McCall80ee6e82011-11-10 05:35:25 +000013436 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000013437 S.MarkFunctionReferenced(E->getLocStart(),
John McCall80ee6e82011-11-10 05:35:25 +000013438 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13439 Visit(E->getSubExpr());
13440 }
13441
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013442 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013443 if (E->getOperatorNew())
Eli Friedman5f2987c2012-02-02 03:46:19 +000013444 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013445 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000013446 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000013447 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013448 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +000013449
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013450 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13451 if (E->getOperatorDelete())
Eli Friedman5f2987c2012-02-02 03:46:19 +000013452 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000013453 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13454 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13455 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedman5f2987c2012-02-02 03:46:19 +000013456 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor5833b0b2010-09-14 22:55:20 +000013457 S.LookupDestructor(Record));
13458 }
13459
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000013460 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013461 }
13462
13463 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000013464 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000013465 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013466 }
13467
Douglas Gregor102ff972010-10-19 17:17:35 +000013468 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13469 Visit(E->getExpr());
13470 }
Eli Friedmand2cce132012-02-02 23:15:15 +000013471
13472 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13473 Inherited::VisitImplicitCastExpr(E);
13474
13475 if (E->getCastKind() == CK_LValueToRValue)
13476 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13477 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013478 };
13479}
13480
13481/// \brief Mark any declarations that appear within this expression or any
13482/// potentially-evaluated subexpressions as "referenced".
Douglas Gregorf4b7de12012-02-21 19:11:17 +000013483///
13484/// \param SkipLocalVariables If true, don't mark local variables as
13485/// 'referenced'.
13486void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13487 bool SkipLocalVariables) {
13488 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013489}
13490
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013491/// \brief Emit a diagnostic that describes an effect on the run-time behavior
13492/// of the program being compiled.
13493///
13494/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000013495/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013496/// possibility that the code will actually be executable. Code in sizeof()
13497/// expressions, code used only during overload resolution, etc., are not
13498/// potentially evaluated. This routine will suppress such diagnostics or,
13499/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000013500/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013501/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000013502///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013503/// This routine should be used for all diagnostics that describe the run-time
13504/// behavior of a program, such as passing a non-POD value through an ellipsis.
13505/// Failure to do so will likely result in spurious diagnostics or failures
13506/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuccd891a2011-09-09 01:45:06 +000013507bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013508 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000013509 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013510 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +000013511 case UnevaluatedAbstract:
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013512 // The argument will never be evaluated, so don't complain.
13513 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000013514
Richard Smithf6702a32011-12-20 02:08:33 +000013515 case ConstantEvaluated:
13516 // Relevant diagnostics should be produced by constant evaluation.
13517 break;
13518
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013519 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000013520 case PotentiallyEvaluatedIfUsed:
Richard Trieuccd891a2011-09-09 01:45:06 +000013521 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek351ba912011-02-23 01:52:04 +000013522 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuccd891a2011-09-09 01:45:06 +000013523 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek351ba912011-02-23 01:52:04 +000013524 }
13525 else
13526 Diag(Loc, PD);
13527
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013528 return true;
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000013529 }
13530
13531 return false;
13532}
13533
Anders Carlsson8c8d9192009-10-09 23:51:55 +000013534bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13535 CallExpr *CE, FunctionDecl *FD) {
13536 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13537 return false;
13538
Richard Smith76f3f692012-02-22 02:04:18 +000013539 // If we're inside a decltype's expression, don't check for a valid return
13540 // type or construct temporaries until we know whether this is the last call.
13541 if (ExprEvalContexts.back().IsDecltype) {
13542 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13543 return false;
13544 }
13545
Douglas Gregorf502d8e2012-05-04 16:48:41 +000013546 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +000013547 FunctionDecl *FD;
13548 CallExpr *CE;
13549
13550 public:
13551 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13552 : FD(FD), CE(CE) { }
Stephen Hines651f13c2014-04-23 16:59:28 -070013553
13554 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregord10099e2012-05-04 16:32:21 +000013555 if (!FD) {
13556 S.Diag(Loc, diag::err_call_incomplete_return)
13557 << T << CE->getSourceRange();
13558 return;
13559 }
13560
13561 S.Diag(Loc, diag::err_call_function_incomplete_return)
13562 << CE->getSourceRange() << FD->getDeclName() << T;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013563 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13564 << FD->getDeclName();
Douglas Gregord10099e2012-05-04 16:32:21 +000013565 }
13566 } Diagnoser(FD, CE);
13567
13568 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson8c8d9192009-10-09 23:51:55 +000013569 return true;
13570
13571 return false;
13572}
13573
Douglas Gregor92c3a042011-01-19 16:50:08 +000013574// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000013575// will prevent this condition from triggering, which is what we want.
13576void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13577 SourceLocation Loc;
13578
John McCalla52ef082009-11-11 02:41:58 +000013579 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000013580 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000013581
Chandler Carruthb33c19f2011-08-16 22:30:10 +000013582 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000013583 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000013584 return;
13585
Douglas Gregor92c3a042011-01-19 16:50:08 +000013586 IsOrAssign = Op->getOpcode() == BO_OrAssign;
13587
John McCallc8d8ac52009-11-12 00:06:05 +000013588 // Greylist some idioms by putting them into a warning subcategory.
13589 if (ObjCMessageExpr *ME
13590 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13591 Selector Sel = ME->getSelector();
13592
John McCallc8d8ac52009-11-12 00:06:05 +000013593 // self = [<foo> init...]
Jean-Daniel Dupas8df014e2013-07-17 18:17:14 +000013594 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
John McCallc8d8ac52009-11-12 00:06:05 +000013595 diagnostic = diag::warn_condition_is_idiomatic_assignment;
13596
13597 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000013598 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000013599 diagnostic = diag::warn_condition_is_idiomatic_assignment;
13600 }
John McCalla52ef082009-11-11 02:41:58 +000013601
John McCall5a881bb2009-10-12 21:59:07 +000013602 Loc = Op->getOperatorLoc();
Chandler Carruthb33c19f2011-08-16 22:30:10 +000013603 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor92c3a042011-01-19 16:50:08 +000013604 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000013605 return;
13606
Douglas Gregor92c3a042011-01-19 16:50:08 +000013607 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000013608 Loc = Op->getOperatorLoc();
Fariborz Jahaniana414a2f2012-08-29 17:17:11 +000013609 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13610 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13611 else {
John McCall5a881bb2009-10-12 21:59:07 +000013612 // Not an assignment.
13613 return;
13614 }
13615
Douglas Gregor55b38842010-04-14 16:09:52 +000013616 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000013617
Daniel Dunbar96a00142012-03-09 18:35:03 +000013618 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000013619 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
13620 Diag(Loc, diag::note_condition_assign_silence)
13621 << FixItHint::CreateInsertion(Open, "(")
13622 << FixItHint::CreateInsertion(Close, ")");
13623
Douglas Gregor92c3a042011-01-19 16:50:08 +000013624 if (IsOrAssign)
13625 Diag(Loc, diag::note_condition_or_assign_to_comparison)
13626 << FixItHint::CreateReplacement(Loc, "!=");
13627 else
13628 Diag(Loc, diag::note_condition_assign_to_comparison)
13629 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000013630}
13631
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000013632/// \brief Redundant parentheses over an equality comparison can indicate
13633/// that the user intended an assignment used as condition.
Richard Trieuccd891a2011-09-09 01:45:06 +000013634void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000013635 // Don't warn if the parens came from a macro.
Richard Trieuccd891a2011-09-09 01:45:06 +000013636 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000013637 if (parenLoc.isInvalid() || parenLoc.isMacroID())
13638 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000013639 // Don't warn for dependent expressions.
Richard Trieuccd891a2011-09-09 01:45:06 +000013640 if (ParenE->isTypeDependent())
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000013641 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000013642
Richard Trieuccd891a2011-09-09 01:45:06 +000013643 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000013644
13645 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000013646 if (opE->getOpcode() == BO_EQ &&
13647 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13648 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000013649 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000013650
Ted Kremenekf7275cd2011-02-02 02:20:30 +000013651 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +000013652 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000013653 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar96a00142012-03-09 18:35:03 +000013654 << FixItHint::CreateRemoval(ParenERange.getBegin())
13655 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000013656 Diag(Loc, diag::note_equality_comparison_to_assign)
13657 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000013658 }
13659}
13660
John Wiegley429bb272011-04-08 18:41:53 +000013661ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000013662 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000013663 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13664 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000013665
John McCall864c0412011-04-26 20:42:42 +000013666 ExprResult result = CheckPlaceholderExpr(E);
13667 if (result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013668 E = result.get();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000013669
John McCall864c0412011-04-26 20:42:42 +000013670 if (!E->isTypeDependent()) {
David Blaikie4e4d0842012-03-11 07:00:24 +000013671 if (getLangOpts().CPlusPlus)
John McCallf6a16482010-12-04 03:47:34 +000013672 return CheckCXXBooleanCondition(E); // C++ 6.4p4
13673
John Wiegley429bb272011-04-08 18:41:53 +000013674 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13675 if (ERes.isInvalid())
13676 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013677 E = ERes.get();
John McCallabc56c72010-12-04 06:09:13 +000013678
13679 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000013680 if (!T->isScalarType()) { // C99 6.8.4.1p1
13681 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13682 << T << E->getSourceRange();
13683 return ExprError();
13684 }
Stephen Hines176edba2014-12-01 14:53:08 -080013685 CheckBoolLikeConversion(E, Loc);
John McCall5a881bb2009-10-12 21:59:07 +000013686 }
13687
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013688 return E;
John McCall5a881bb2009-10-12 21:59:07 +000013689}
Douglas Gregor586596f2010-05-06 17:25:47 +000013690
John McCall60d7b3a2010-08-24 06:29:42 +000013691ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuccd891a2011-09-09 01:45:06 +000013692 Expr *SubExpr) {
13693 if (!SubExpr)
Douglas Gregor586596f2010-05-06 17:25:47 +000013694 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000013695
Richard Trieuccd891a2011-09-09 01:45:06 +000013696 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000013697}
John McCall2a984ca2010-10-12 00:20:44 +000013698
John McCall1de4d4e2011-04-07 08:22:57 +000013699namespace {
John McCall755d8492011-04-12 00:42:48 +000013700 /// A visitor for rebuilding a call to an __unknown_any expression
13701 /// to have an appropriate type.
13702 struct RebuildUnknownAnyFunction
13703 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13704
13705 Sema &S;
13706
13707 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13708
13709 ExprResult VisitStmt(Stmt *S) {
13710 llvm_unreachable("unexpected statement!");
John McCall755d8492011-04-12 00:42:48 +000013711 }
13712
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013713 ExprResult VisitExpr(Expr *E) {
13714 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13715 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000013716 return ExprError();
13717 }
13718
13719 /// Rebuild an expression which simply semantically wraps another
13720 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013721 template <class T> ExprResult rebuildSugarExpr(T *E) {
13722 ExprResult SubResult = Visit(E->getSubExpr());
13723 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000013724
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013725 Expr *SubExpr = SubResult.get();
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013726 E->setSubExpr(SubExpr);
13727 E->setType(SubExpr->getType());
13728 E->setValueKind(SubExpr->getValueKind());
13729 assert(E->getObjectKind() == OK_Ordinary);
13730 return E;
John McCall755d8492011-04-12 00:42:48 +000013731 }
13732
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013733 ExprResult VisitParenExpr(ParenExpr *E) {
13734 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000013735 }
13736
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013737 ExprResult VisitUnaryExtension(UnaryOperator *E) {
13738 return rebuildSugarExpr(E);
John McCall755d8492011-04-12 00:42:48 +000013739 }
13740
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013741 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13742 ExprResult SubResult = Visit(E->getSubExpr());
13743 if (SubResult.isInvalid()) return ExprError();
John McCall755d8492011-04-12 00:42:48 +000013744
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013745 Expr *SubExpr = SubResult.get();
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013746 E->setSubExpr(SubExpr);
13747 E->setType(S.Context.getPointerType(SubExpr->getType()));
13748 assert(E->getValueKind() == VK_RValue);
13749 assert(E->getObjectKind() == OK_Ordinary);
13750 return E;
John McCall755d8492011-04-12 00:42:48 +000013751 }
13752
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013753 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13754 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall755d8492011-04-12 00:42:48 +000013755
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013756 E->setType(VD->getType());
John McCall755d8492011-04-12 00:42:48 +000013757
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013758 assert(E->getValueKind() == VK_RValue);
David Blaikie4e4d0842012-03-11 07:00:24 +000013759 if (S.getLangOpts().CPlusPlus &&
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013760 !(isa<CXXMethodDecl>(VD) &&
13761 cast<CXXMethodDecl>(VD)->isInstance()))
13762 E->setValueKind(VK_LValue);
John McCall755d8492011-04-12 00:42:48 +000013763
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013764 return E;
John McCall755d8492011-04-12 00:42:48 +000013765 }
13766
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013767 ExprResult VisitMemberExpr(MemberExpr *E) {
13768 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000013769 }
13770
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013771 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13772 return resolveDecl(E, E->getDecl());
John McCall755d8492011-04-12 00:42:48 +000013773 }
13774 };
13775}
13776
13777/// Given a function expression of unknown-any type, try to rebuild it
13778/// to have a function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013779static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13780 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13781 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013782 return S.DefaultFunctionArrayConversion(Result.get());
John McCall755d8492011-04-12 00:42:48 +000013783}
13784
13785namespace {
John McCall379b5152011-04-11 07:02:50 +000013786 /// A visitor for rebuilding an expression of type __unknown_anytype
13787 /// into one which resolves the type directly on the referring
13788 /// expression. Strict preservation of the original source
13789 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000013790 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000013791 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000013792
13793 Sema &S;
13794
13795 /// The current destination type.
13796 QualType DestType;
13797
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013798 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13799 : S(S), DestType(CastType) {}
John McCall1de4d4e2011-04-07 08:22:57 +000013800
John McCalla5fc4722011-04-09 22:50:59 +000013801 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000013802 llvm_unreachable("unexpected statement!");
John McCall1de4d4e2011-04-07 08:22:57 +000013803 }
13804
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013805 ExprResult VisitExpr(Expr *E) {
13806 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13807 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000013808 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000013809 }
13810
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013811 ExprResult VisitCallExpr(CallExpr *E);
13812 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall379b5152011-04-11 07:02:50 +000013813
John McCalla5fc4722011-04-09 22:50:59 +000013814 /// Rebuild an expression which simply semantically wraps another
13815 /// expression which it shares the type and value kind of.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013816 template <class T> ExprResult rebuildSugarExpr(T *E) {
13817 ExprResult SubResult = Visit(E->getSubExpr());
13818 if (SubResult.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013819 Expr *SubExpr = SubResult.get();
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013820 E->setSubExpr(SubExpr);
13821 E->setType(SubExpr->getType());
13822 E->setValueKind(SubExpr->getValueKind());
13823 assert(E->getObjectKind() == OK_Ordinary);
13824 return E;
John McCalla5fc4722011-04-09 22:50:59 +000013825 }
John McCall1de4d4e2011-04-07 08:22:57 +000013826
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013827 ExprResult VisitParenExpr(ParenExpr *E) {
13828 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000013829 }
13830
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013831 ExprResult VisitUnaryExtension(UnaryOperator *E) {
13832 return rebuildSugarExpr(E);
John McCalla5fc4722011-04-09 22:50:59 +000013833 }
13834
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013835 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13836 const PointerType *Ptr = DestType->getAs<PointerType>();
13837 if (!Ptr) {
13838 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13839 << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000013840 return ExprError();
13841 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013842 assert(E->getValueKind() == VK_RValue);
13843 assert(E->getObjectKind() == OK_Ordinary);
13844 E->setType(DestType);
John McCall755d8492011-04-12 00:42:48 +000013845
13846 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013847 DestType = Ptr->getPointeeType();
13848 ExprResult SubResult = Visit(E->getSubExpr());
13849 if (SubResult.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013850 E->setSubExpr(SubResult.get());
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013851 return E;
John McCall755d8492011-04-12 00:42:48 +000013852 }
13853
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013854 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCalla5fc4722011-04-09 22:50:59 +000013855
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013856 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCalla5fc4722011-04-09 22:50:59 +000013857
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013858 ExprResult VisitMemberExpr(MemberExpr *E) {
13859 return resolveDecl(E, E->getMemberDecl());
John McCall755d8492011-04-12 00:42:48 +000013860 }
John McCalla5fc4722011-04-09 22:50:59 +000013861
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013862 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13863 return resolveDecl(E, E->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000013864 }
13865 };
13866}
13867
John McCall379b5152011-04-11 07:02:50 +000013868/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013869ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13870 Expr *CalleeExpr = E->getCallee();
John McCall379b5152011-04-11 07:02:50 +000013871
13872 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000013873 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000013874 FK_FunctionPointer,
13875 FK_BlockPointer
13876 };
13877
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013878 FnKind Kind;
13879 QualType CalleeType = CalleeExpr->getType();
13880 if (CalleeType == S.Context.BoundMemberTy) {
13881 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13882 Kind = FK_MemberFunction;
13883 CalleeType = Expr::findBoundMemberType(CalleeExpr);
13884 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13885 CalleeType = Ptr->getPointeeType();
13886 Kind = FK_FunctionPointer;
John McCall379b5152011-04-11 07:02:50 +000013887 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013888 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13889 Kind = FK_BlockPointer;
John McCall379b5152011-04-11 07:02:50 +000013890 }
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013891 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall379b5152011-04-11 07:02:50 +000013892
13893 // Verify that this is a legal result type of a function.
13894 if (DestType->isArrayType() || DestType->isFunctionType()) {
13895 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013896 if (Kind == FK_BlockPointer)
John McCall379b5152011-04-11 07:02:50 +000013897 diagID = diag::err_block_returning_array_function;
13898
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013899 S.Diag(E->getExprLoc(), diagID)
John McCall379b5152011-04-11 07:02:50 +000013900 << DestType->isFunctionType() << DestType;
13901 return ExprError();
13902 }
13903
13904 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013905 E->setType(DestType.getNonLValueExprType(S.Context));
13906 E->setValueKind(Expr::getValueKindForType(DestType));
13907 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000013908
13909 // Rebuild the function type, replacing the result type with DestType.
John McCall02a01fa2013-06-27 22:43:24 +000013910 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13911 if (Proto) {
13912 // __unknown_anytype(...) is a special case used by the debugger when
13913 // it has no idea what a function's signature is.
13914 //
13915 // We want to build this call essentially under the K&R
13916 // unprototyped rules, but making a FunctionNoProtoType in C++
13917 // would foul up all sorts of assumptions. However, we cannot
13918 // simply pass all arguments as variadic arguments, nor can we
13919 // portably just call the function under a non-variadic type; see
13920 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13921 // However, it turns out that in practice it is generally safe to
13922 // call a function declared as "A foo(B,C,D);" under the prototype
13923 // "A foo(B,C,D,...);". The only known exception is with the
13924 // Windows ABI, where any variadic function is implicitly cdecl
13925 // regardless of its normal CC. Therefore we change the parameter
13926 // types to match the types of the arguments.
13927 //
13928 // This is a hack, but it is far superior to moving the
13929 // corresponding target-specific code from IR-gen to Sema/AST.
13930
Stephen Hines651f13c2014-04-23 16:59:28 -070013931 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
John McCall02a01fa2013-06-27 22:43:24 +000013932 SmallVector<QualType, 8> ArgTypes;
13933 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13934 ArgTypes.reserve(E->getNumArgs());
13935 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13936 Expr *Arg = E->getArg(i);
13937 QualType ArgType = Arg->getType();
13938 if (E->isLValue()) {
13939 ArgType = S.Context.getLValueReferenceType(ArgType);
13940 } else if (E->isXValue()) {
13941 ArgType = S.Context.getRValueReferenceType(ArgType);
13942 }
13943 ArgTypes.push_back(ArgType);
13944 }
13945 ParamTypes = ArgTypes;
13946 }
13947 DestType = S.Context.getFunctionType(DestType, ParamTypes,
Reid Kleckner0567a792013-06-10 20:51:09 +000013948 Proto->getExtProtoInfo());
John McCall02a01fa2013-06-27 22:43:24 +000013949 } else {
John McCall379b5152011-04-11 07:02:50 +000013950 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013951 FnType->getExtInfo());
John McCall02a01fa2013-06-27 22:43:24 +000013952 }
John McCall379b5152011-04-11 07:02:50 +000013953
13954 // Rebuild the appropriate pointer-to-function type.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013955 switch (Kind) {
John McCallf5307512011-04-27 00:36:17 +000013956 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000013957 // Nothing to do.
13958 break;
13959
13960 case FK_FunctionPointer:
13961 DestType = S.Context.getPointerType(DestType);
13962 break;
13963
13964 case FK_BlockPointer:
13965 DestType = S.Context.getBlockPointerType(DestType);
13966 break;
13967 }
13968
13969 // Finally, we can recurse.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013970 ExprResult CalleeResult = Visit(CalleeExpr);
13971 if (!CalleeResult.isUsable()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013972 E->setCallee(CalleeResult.get());
John McCall379b5152011-04-11 07:02:50 +000013973
13974 // Bind a temporary if necessary.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013975 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000013976}
13977
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013978ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000013979 // Verify that this is a legal result type of a call.
13980 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013981 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall755d8492011-04-12 00:42:48 +000013982 << DestType->isFunctionType() << DestType;
13983 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000013984 }
13985
John McCall48218c62011-07-13 17:56:40 +000013986 // Rewrite the method result type if available.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013987 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070013988 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13989 Method->setReturnType(DestType);
John McCall48218c62011-07-13 17:56:40 +000013990 }
John McCall755d8492011-04-12 00:42:48 +000013991
John McCall379b5152011-04-11 07:02:50 +000013992 // Change the type of the message.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013993 E->setType(DestType.getNonReferenceType());
13994 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000013995
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013996 return S.MaybeBindToTemporary(E);
John McCall379b5152011-04-11 07:02:50 +000013997}
13998
Richard Trieu5e4c80b2011-09-09 03:59:41 +000013999ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall755d8492011-04-12 00:42:48 +000014000 // The only case we should ever see here is a function-to-pointer decay.
Sean Callananba66c6c2012-03-06 23:12:57 +000014001 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanance9c8312012-03-06 21:34:12 +000014002 assert(E->getValueKind() == VK_RValue);
14003 assert(E->getObjectKind() == OK_Ordinary);
14004
14005 E->setType(DestType);
14006
14007 // Rebuild the sub-expression as the pointee (function) type.
14008 DestType = DestType->castAs<PointerType>()->getPointeeType();
14009
14010 ExprResult Result = Visit(E->getSubExpr());
14011 if (!Result.isUsable()) return ExprError();
14012
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014013 E->setSubExpr(Result.get());
14014 return E;
Sean Callananba66c6c2012-03-06 23:12:57 +000014015 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanance9c8312012-03-06 21:34:12 +000014016 assert(E->getValueKind() == VK_RValue);
14017 assert(E->getObjectKind() == OK_Ordinary);
John McCall379b5152011-04-11 07:02:50 +000014018
Sean Callanance9c8312012-03-06 21:34:12 +000014019 assert(isa<BlockPointerType>(E->getType()));
John McCall755d8492011-04-12 00:42:48 +000014020
Sean Callanance9c8312012-03-06 21:34:12 +000014021 E->setType(DestType);
John McCall379b5152011-04-11 07:02:50 +000014022
Sean Callanance9c8312012-03-06 21:34:12 +000014023 // The sub-expression has to be a lvalue reference, so rebuild it as such.
14024 DestType = S.Context.getLValueReferenceType(DestType);
John McCall379b5152011-04-11 07:02:50 +000014025
Sean Callanance9c8312012-03-06 21:34:12 +000014026 ExprResult Result = Visit(E->getSubExpr());
14027 if (!Result.isUsable()) return ExprError();
14028
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014029 E->setSubExpr(Result.get());
14030 return E;
Sean Callananba66c6c2012-03-06 23:12:57 +000014031 } else {
Sean Callanance9c8312012-03-06 21:34:12 +000014032 llvm_unreachable("Unhandled cast type!");
14033 }
John McCall379b5152011-04-11 07:02:50 +000014034}
14035
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014036ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14037 ExprValueKind ValueKind = VK_LValue;
14038 QualType Type = DestType;
John McCall379b5152011-04-11 07:02:50 +000014039
14040 // We know how to make this work for certain kinds of decls:
14041
14042 // - functions
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014043 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14044 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14045 DestType = Ptr->getPointeeType();
14046 ExprResult Result = resolveDecl(E, VD);
14047 if (Result.isInvalid()) return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014048 return S.ImpCastExprToType(Result.get(), Type,
John McCalla19950e2011-08-10 04:12:23 +000014049 CK_FunctionToPointerDecay, VK_RValue);
14050 }
14051
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014052 if (!Type->isFunctionType()) {
14053 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14054 << VD << E->getSourceRange();
John McCalla19950e2011-08-10 04:12:23 +000014055 return ExprError();
14056 }
Stephen Hines176edba2014-12-01 14:53:08 -080014057 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14058 // We must match the FunctionDecl's type to the hack introduced in
14059 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14060 // type. See the lengthy commentary in that routine.
14061 QualType FDT = FD->getType();
14062 const FunctionType *FnType = FDT->castAs<FunctionType>();
14063 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14064 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14065 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14066 SourceLocation Loc = FD->getLocation();
14067 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14068 FD->getDeclContext(),
14069 Loc, Loc, FD->getNameInfo().getName(),
14070 DestType, FD->getTypeSourceInfo(),
14071 SC_None, false/*isInlineSpecified*/,
14072 FD->hasPrototype(),
14073 false/*isConstexprSpecified*/);
14074
14075 if (FD->getQualifier())
14076 NewFD->setQualifierInfo(FD->getQualifierLoc());
14077
14078 SmallVector<ParmVarDecl*, 16> Params;
14079 for (const auto &AI : FT->param_types()) {
14080 ParmVarDecl *Param =
14081 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14082 Param->setScopeInfo(0, Params.size());
14083 Params.push_back(Param);
14084 }
14085 NewFD->setParams(Params);
14086 DRE->setDecl(NewFD);
14087 VD = DRE->getDecl();
14088 }
14089 }
John McCall379b5152011-04-11 07:02:50 +000014090
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014091 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14092 if (MD->isInstance()) {
14093 ValueKind = VK_RValue;
14094 Type = S.Context.BoundMemberTy;
John McCallf5307512011-04-27 00:36:17 +000014095 }
14096
John McCall379b5152011-04-11 07:02:50 +000014097 // Function references aren't l-values in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000014098 if (!S.getLangOpts().CPlusPlus)
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014099 ValueKind = VK_RValue;
John McCall379b5152011-04-11 07:02:50 +000014100
14101 // - variables
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014102 } else if (isa<VarDecl>(VD)) {
14103 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14104 Type = RefTy->getPointeeType();
14105 } else if (Type->isFunctionType()) {
14106 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14107 << VD << E->getSourceRange();
John McCall755d8492011-04-12 00:42:48 +000014108 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000014109 }
14110
14111 // - nothing else
14112 } else {
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014113 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14114 << VD << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000014115 return ExprError();
14116 }
14117
John McCall02a01fa2013-06-27 22:43:24 +000014118 // Modifying the declaration like this is friendly to IR-gen but
14119 // also really dangerous.
Richard Trieu5e4c80b2011-09-09 03:59:41 +000014120 VD->setType(DestType);
14121 E->setType(Type);
14122 E->setValueKind(ValueKind);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014123 return E;
John McCall379b5152011-04-11 07:02:50 +000014124}
14125
John McCall1de4d4e2011-04-07 08:22:57 +000014126/// Check a cast of an unknown-any type. We intentionally only
14127/// trigger this for C-style casts.
Richard Trieuccd891a2011-09-09 01:45:06 +000014128ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14129 Expr *CastExpr, CastKind &CastKind,
14130 ExprValueKind &VK, CXXCastPath &Path) {
John McCall1de4d4e2011-04-07 08:22:57 +000014131 // Rewrite the casted expression from scratch.
Richard Trieuccd891a2011-09-09 01:45:06 +000014132 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCalla5fc4722011-04-09 22:50:59 +000014133 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000014134
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014135 CastExpr = result.get();
Richard Trieuccd891a2011-09-09 01:45:06 +000014136 VK = CastExpr->getValueKind();
14137 CastKind = CK_NoOp;
John McCalla5fc4722011-04-09 22:50:59 +000014138
Richard Trieuccd891a2011-09-09 01:45:06 +000014139 return CastExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000014140}
14141
Douglas Gregorf1d1ca52011-12-01 01:37:36 +000014142ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14143 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14144}
14145
John McCall48f90422013-03-04 07:34:02 +000014146ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14147 Expr *arg, QualType &paramType) {
14148 // If the syntactic form of the argument is not an explicit cast of
14149 // any sort, just do default argument promotion.
14150 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14151 if (!castArg) {
14152 ExprResult result = DefaultArgumentPromotion(arg);
14153 if (result.isInvalid()) return ExprError();
14154 paramType = result.get()->getType();
14155 return result;
John McCallb8a8de32012-11-14 00:49:39 +000014156 }
14157
John McCall48f90422013-03-04 07:34:02 +000014158 // Otherwise, use the type that was written in the explicit cast.
14159 assert(!arg->hasPlaceholderType());
14160 paramType = castArg->getTypeAsWritten();
14161
14162 // Copy-initialize a parameter of that type.
14163 InitializedEntity entity =
14164 InitializedEntity::InitializeParameter(Context, paramType,
14165 /*consumed*/ false);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014166 return PerformCopyInitialization(entity, callLoc, arg);
John McCallb8a8de32012-11-14 00:49:39 +000014167}
14168
Richard Trieuccd891a2011-09-09 01:45:06 +000014169static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14170 Expr *orig = E;
John McCall379b5152011-04-11 07:02:50 +000014171 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000014172 while (true) {
Richard Trieuccd891a2011-09-09 01:45:06 +000014173 E = E->IgnoreParenImpCasts();
14174 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14175 E = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000014176 diagID = diag::err_uncasted_call_of_unknown_any;
14177 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000014178 break;
John McCall379b5152011-04-11 07:02:50 +000014179 }
John McCall1de4d4e2011-04-07 08:22:57 +000014180 }
14181
John McCall379b5152011-04-11 07:02:50 +000014182 SourceLocation loc;
14183 NamedDecl *d;
Richard Trieuccd891a2011-09-09 01:45:06 +000014184 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000014185 loc = ref->getLocation();
14186 d = ref->getDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000014187 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000014188 loc = mem->getMemberLoc();
14189 d = mem->getMemberDecl();
Richard Trieuccd891a2011-09-09 01:45:06 +000014190 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall379b5152011-04-11 07:02:50 +000014191 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +000014192 loc = msg->getSelectorStartLoc();
John McCall379b5152011-04-11 07:02:50 +000014193 d = msg->getMethodDecl();
John McCall819e7452011-08-31 20:57:36 +000014194 if (!d) {
14195 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14196 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14197 << orig->getSourceRange();
14198 return ExprError();
14199 }
John McCall379b5152011-04-11 07:02:50 +000014200 } else {
Richard Trieuccd891a2011-09-09 01:45:06 +000014201 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14202 << E->getSourceRange();
John McCall379b5152011-04-11 07:02:50 +000014203 return ExprError();
14204 }
14205
14206 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000014207
14208 // Never recoverable.
14209 return ExprError();
14210}
14211
John McCall2a984ca2010-10-12 00:20:44 +000014212/// Check for operands with placeholder types and complain if found.
14213/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000014214ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -070014215 if (!getLangOpts().CPlusPlus) {
14216 // C cannot handle TypoExpr nodes on either side of a binop because it
14217 // doesn't handle dependent types properly, so make sure any TypoExprs have
14218 // been dealt with before checking the operands.
14219 ExprResult Result = CorrectDelayedTyposInExpr(E);
14220 if (!Result.isUsable()) return ExprError();
14221 E = Result.get();
14222 }
14223
John McCall5acb0c92011-10-17 18:40:02 +000014224 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014225 if (!placeholderType) return E;
John McCall5acb0c92011-10-17 18:40:02 +000014226
14227 switch (placeholderType->getKind()) {
John McCall2a984ca2010-10-12 00:20:44 +000014228
John McCall1de4d4e2011-04-07 08:22:57 +000014229 // Overloaded expressions.
John McCall5acb0c92011-10-17 18:40:02 +000014230 case BuiltinType::Overload: {
John McCall6dbba4f2011-10-11 23:14:30 +000014231 // Try to resolve a single function template specialization.
14232 // This is obligatory.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014233 ExprResult result = E;
John McCall6dbba4f2011-10-11 23:14:30 +000014234 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14235 return result;
14236
14237 // If that failed, try to recover with a call.
14238 } else {
14239 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14240 /*complain*/ true);
14241 return result;
14242 }
14243 }
John McCall1de4d4e2011-04-07 08:22:57 +000014244
John McCall864c0412011-04-26 20:42:42 +000014245 // Bound member functions.
John McCall5acb0c92011-10-17 18:40:02 +000014246 case BuiltinType::BoundMember: {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014247 ExprResult result = E;
Stephen Hines0e2c34f2015-03-23 12:09:02 -070014248 const Expr *BME = E->IgnoreParens();
14249 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14250 // Try to give a nicer diagnostic if it is a bound member that we recognize.
14251 if (isa<CXXPseudoDestructorExpr>(BME)) {
14252 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14253 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14254 if (ME->getMemberNameInfo().getName().getNameKind() ==
14255 DeclarationName::CXXDestructorName)
14256 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14257 }
14258 tryToRecoverWithCall(result, PD,
John McCall6dbba4f2011-10-11 23:14:30 +000014259 /*complain*/ true);
14260 return result;
John McCall5acb0c92011-10-17 18:40:02 +000014261 }
14262
14263 // ARC unbridged casts.
14264 case BuiltinType::ARCUnbridgedCast: {
14265 Expr *realCast = stripARCUnbridgedCast(E);
14266 diagnoseARCUnbridgedCast(realCast);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014267 return realCast;
John McCall5acb0c92011-10-17 18:40:02 +000014268 }
John McCall864c0412011-04-26 20:42:42 +000014269
John McCall1de4d4e2011-04-07 08:22:57 +000014270 // Expressions of unknown type.
John McCall5acb0c92011-10-17 18:40:02 +000014271 case BuiltinType::UnknownAny:
John McCall1de4d4e2011-04-07 08:22:57 +000014272 return diagnoseUnknownAnyExpr(*this, E);
14273
John McCall3c3b7f92011-10-25 17:37:35 +000014274 // Pseudo-objects.
14275 case BuiltinType::PseudoObject:
14276 return checkPseudoObjectRValue(E);
14277
Stephen Hines176edba2014-12-01 14:53:08 -080014278 case BuiltinType::BuiltinFn: {
14279 // Accept __noop without parens by implicitly converting it to a call expr.
14280 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14281 if (DRE) {
14282 auto *FD = cast<FunctionDecl>(DRE->getDecl());
14283 if (FD->getBuiltinID() == Builtin::BI__noop) {
14284 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14285 CK_BuiltinFnToFnPtr).get();
14286 return new (Context) CallExpr(Context, E, None, Context.IntTy,
14287 VK_RValue, SourceLocation());
14288 }
14289 }
14290
Eli Friedmana6c66ce2012-08-31 00:14:07 +000014291 Diag(E->getLocStart(), diag::err_builtin_fn_use);
14292 return ExprError();
Stephen Hines176edba2014-12-01 14:53:08 -080014293 }
Eli Friedmana6c66ce2012-08-31 00:14:07 +000014294
John McCalle0a22d02011-10-18 21:02:43 +000014295 // Everything else should be impossible.
14296#define BUILTIN_TYPE(Id, SingletonId) \
14297 case BuiltinType::Id:
14298#define PLACEHOLDER_TYPE(Id, SingletonId)
14299#include "clang/AST/BuiltinTypes.def"
John McCall5acb0c92011-10-17 18:40:02 +000014300 break;
14301 }
14302
14303 llvm_unreachable("invalid placeholder type!");
John McCall2a984ca2010-10-12 00:20:44 +000014304}
Richard Trieubb9b80c2011-04-21 21:44:26 +000014305
Richard Trieuccd891a2011-09-09 01:45:06 +000014306bool Sema::CheckCaseExpression(Expr *E) {
14307 if (E->isTypeDependent())
Richard Trieubb9b80c2011-04-21 21:44:26 +000014308 return true;
Richard Trieuccd891a2011-09-09 01:45:06 +000014309 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14310 return E->getType()->isIntegralOrEnumerationType();
Richard Trieubb9b80c2011-04-21 21:44:26 +000014311 return false;
14312}
Ted Kremenekebcb57a2012-03-06 20:05:56 +000014313
14314/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14315ExprResult
14316Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14317 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14318 "Unknown Objective-C Boolean value!");
Fariborz Jahanian96171302012-08-30 18:49:41 +000014319 QualType BoolT = Context.ObjCBuiltinBoolTy;
14320 if (!Context.getBOOLDecl()) {
Fariborz Jahanian1c9a2da2012-10-16 17:08:11 +000014321 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
Fariborz Jahanian96171302012-08-30 18:49:41 +000014322 Sema::LookupOrdinaryName);
Fariborz Jahanian9f5933a2012-10-16 16:21:20 +000014323 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
Fariborz Jahanian96171302012-08-30 18:49:41 +000014324 NamedDecl *ND = Result.getFoundDecl();
14325 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14326 Context.setBOOLDecl(TD);
14327 }
14328 }
14329 if (Context.getBOOLDecl())
14330 BoolT = Context.getBOOLType();
Stephen Hinesc568f1e2014-07-21 00:47:37 -070014331 return new (Context)
14332 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000014333}