blob: cdca6827049074ba78f9c3ffea5f8f35923a226b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
192 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
197 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return rhs;
199 }
200 // We have two real floating types, float/complex combos were handled above.
201 // Convert the smaller operand to the bigger result.
202 int result = Context.getFloatingTypeOrder(lhs, rhs);
203
204 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000205 return lhs;
206 }
207 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000208 return rhs;
209 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000211 }
212 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
213 // Handle GCC complex int extension.
214 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
215 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
216
217 if (lhsComplexInt && rhsComplexInt) {
218 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
219 rhsComplexInt->getElementType()) >= 0) {
220 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000221 return lhs;
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 return rhs;
224 } else if (lhsComplexInt && rhs->isIntegerType()) {
225 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000226 return lhs;
227 } else if (rhsComplexInt && lhs->isIntegerType()) {
228 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return rhs;
230 }
231 }
232 // Finally, we have two differing integer types.
233 // The rules for this case are in C99 6.3.1.8
234 int compare = Context.getIntegerTypeOrder(lhs, rhs);
235 bool lhsSigned = lhs->isSignedIntegerType(),
236 rhsSigned = rhs->isSignedIntegerType();
237 QualType destType;
238 if (lhsSigned == rhsSigned) {
239 // Same signedness; use the higher-ranked type
240 destType = compare >= 0 ? lhs : rhs;
241 } else if (compare != (lhsSigned ? 1 : -1)) {
242 // The unsigned type has greater than or equal rank to the
243 // signed type, so use the unsigned type
244 destType = lhsSigned ? rhs : lhs;
245 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
246 // The two types are different widths; if we are here, that
247 // means the signed type is larger than the unsigned type, so
248 // use the signed type.
249 destType = lhsSigned ? lhs : rhs;
250 } else {
251 // The signed type is higher-ranked than the unsigned type,
252 // but isn't actually any bigger (like unsigned int and long
253 // on most 32-bit systems). Use the unsigned type corresponding
254 // to the signed type.
255 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
256 }
Chris Lattner299b8842008-07-25 21:10:04 +0000257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Naroff87d58b42007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
268/// multiple tokens. However, the common case is that StringToks points to one
269/// string.
270///
271Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 assert(NumStringToks && "Must have at least one string!");
274
275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
276 if (Literal.hadError)
277 return ExprResult(true);
278
279 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
280 for (unsigned i = 0; i != NumStringToks; ++i)
281 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
286 << SourceRange(StringToks[0].getLocation(),
287 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000288
Chris Lattnera6dcce32008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000292
293 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
294 if (getLangOptions().CPlusPlus)
295 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000296
297 // Get an array type for the string, according to C99 6.4.5. This includes
298 // the nul terminator character as well as the string length for pascal
299 // strings.
300 StrTy = Context.getConstantArrayType(StrTy,
301 llvm::APInt(32, Literal.GetStringLength()+1),
302 ArrayType::Normal, 0);
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000307 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000308 StringToks[NumStringToks-1].getLocation());
309}
310
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000311/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
312/// CurBlock to VD should cause it to be snapshotted (as we do for auto
313/// variables defined outside the block) or false if this is not needed (e.g.
314/// for values inside the block or for globals).
315///
316/// FIXME: This will create BlockDeclRefExprs for global variables,
317/// function references, etc which is suboptimal :) and breaks
318/// things like "integer constant expression" tests.
319static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
320 ValueDecl *VD) {
321 // If the value is defined inside the block, we couldn't snapshot it even if
322 // we wanted to.
323 if (CurBlock->TheDecl == VD->getDeclContext())
324 return false;
325
326 // If this is an enum constant or function, it is constant, don't snapshot.
327 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
328 return false;
329
330 // If this is a reference to an extern, static, or global variable, no need to
331 // snapshot it.
332 // FIXME: What about 'const' variables in C++?
333 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
334 return Var->hasLocalStorage();
335
336 return true;
337}
338
339
340
Steve Naroff0acc9c92007-09-15 18:49:24 +0000341/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000343/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000344/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
345/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000347 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000348 bool HasTrailingLParen,
349 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000350 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
351}
352
353/// ActOnDeclarationNameExpr - The parser has read some kind of name
354/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
355/// performs lookup on that name and returns an expression that refers
356/// to that name. This routine isn't directly called from the parser,
357/// because the parser doesn't know about DeclarationName. Rather,
358/// this routine is called by ActOnIdentifierExpr,
359/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
360/// which form the DeclarationName from the corresponding syntactic
361/// forms.
362///
363/// HasTrailingLParen indicates whether this identifier is used in a
364/// function call context. LookupCtx is only used for a C++
365/// qualified-id (foo::bar) to indicate the class or namespace that
366/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000367///
368/// If ForceResolution is true, then we will attempt to resolve the
369/// name even if it looks like a dependent name. This option is off by
370/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000371Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
372 DeclarationName Name,
373 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000374 const CXXScopeSpec *SS,
375 bool ForceResolution) {
376 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
377 HasTrailingLParen && !SS && !ForceResolution) {
378 // We've seen something of the form
379 // identifier(
380 // and we are in a template, so it is likely that 's' is a
381 // dependent name. However, we won't know until we've parsed all
382 // of the call arguments. So, build a CXXDependentNameExpr node
383 // to represent this name. Then, if it turns out that none of the
384 // arguments are type-dependent, we'll force the resolution of the
385 // dependent name at that point.
386 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
387 Context.DependentTy, Loc);
388 }
389
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000390 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000391 Decl *D;
392 if (SS && !SS->isEmpty()) {
393 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
394 if (DC == 0)
395 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000396 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000397 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000398 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000399
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000400 // If this reference is in an Objective-C method, then ivar lookup happens as
401 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000402 IdentifierInfo *II = Name.getAsIdentifierInfo();
403 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000404 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000405 // There are two cases to handle here. 1) scoped lookup could have failed,
406 // in which case we should look for an ivar. 2) scoped lookup could have
407 // found a decl, but that decl is outside the current method (i.e. a global
408 // variable). In these two cases, we do a lookup for an ivar with this
409 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000410 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000411 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000412 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 // FIXME: This should use a new expr for a direct reference, don't turn
414 // this into Self->ivar, just return a BareIVarExpr or something.
415 IdentifierInfo &II = Context.Idents.get("self");
416 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
417 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
418 static_cast<Expr*>(SelfExpr.Val), true, true);
419 }
420 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000421 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000422 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000423 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000424 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000425 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000426 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000427 }
Chris Lattner4b009652007-07-25 00:24:17 +0000428 if (D == 0) {
429 // Otherwise, this could be an implicitly declared function reference (legal
430 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000431 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000432 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000434 else {
435 // If this name wasn't predeclared and if this is not a function call,
436 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000437 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000438 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000439 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000440 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
441 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000442 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000443 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000444 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000445 }
446 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000447
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000448 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
449 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
450 if (MD->isStatic())
451 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000453 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000454 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
455 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000456 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000457 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000458
459 if (FD->isInvalidDecl())
460 return true;
461
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000462 // FIXME: Handle 'mutable'.
463 return new DeclRefExpr(FD,
464 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000465 }
466
Chris Lattner271d4c22008-11-24 05:29:24 +0000467 return Diag(Loc, diag::err_invalid_non_static_member_use)
468 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000469 }
Chris Lattner4b009652007-07-25 00:24:17 +0000470 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000471 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000472 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000473 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000474 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000475 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000476
Steve Naroffd6163f32008-09-05 22:11:13 +0000477 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000478 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
479 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
480
Steve Naroffd6163f32008-09-05 22:11:13 +0000481 ValueDecl *VD = cast<ValueDecl>(D);
482
483 // check if referencing an identifier with __attribute__((deprecated)).
484 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000485 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Steve Naroffd6163f32008-09-05 22:11:13 +0000486
487 // Only create DeclRefExpr's for valid Decl's.
488 if (VD->isInvalidDecl())
489 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000490
491 // If the identifier reference is inside a block, and it refers to a value
492 // that is outside the block, create a BlockDeclRefExpr instead of a
493 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
494 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000495 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000496 // We do not do this for things like enum constants, global variables, etc,
497 // as they do not get snapshotted.
498 //
499 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000500 // The BlocksAttr indicates the variable is bound by-reference.
501 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000502 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
503 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000504
505 // Variable will be bound by-copy, make it const within the closure.
506 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000507 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
508 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000509 }
510 // If this reference is not in a block or if the referenced variable is
511 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000512
513 // C++ [temp.dep.expr]p3:
514 // An id-expression is type-dependent if it contains:
515 bool TypeDependent = false;
516
517 // - an identifier that was declared with a dependent type,
518 if (VD->getType()->isDependentType())
519 TypeDependent = true;
520 // - FIXME: a template-id that is dependent,
521 // - a conversion-function-id that specifies a dependent type,
522 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
523 Name.getCXXNameType()->isDependentType())
524 TypeDependent = true;
525 // - a nested-name-specifier that contains a class-name that
526 // names a dependent type.
527 else if (SS && !SS->isEmpty()) {
528 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
529 DC; DC = DC->getParent()) {
530 // FIXME: could stop early at namespace scope.
531 if (DC->isCXXRecord()) {
532 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
533 if (Context.getTypeDeclType(Record)->isDependentType()) {
534 TypeDependent = true;
535 break;
536 }
537 }
538 }
539 }
540
541 // C++ [temp.dep.constexpr]p2:
542 //
543 // An identifier is value-dependent if it is:
544 bool ValueDependent = false;
545
546 // - a name declared with a dependent type,
547 if (TypeDependent)
548 ValueDependent = true;
549 // - the name of a non-type template parameter,
550 else if (isa<NonTypeTemplateParmDecl>(VD))
551 ValueDependent = true;
552 // - a constant with integral or enumeration type and is
553 // initialized with an expression that is value-dependent
554 // (FIXME!).
555
556 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
557 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000558}
559
Chris Lattner69909292008-08-10 01:53:14 +0000560Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000561 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000562 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000563
564 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000565 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000566 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
567 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
568 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000569 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000570
571 // Verify that this is in a function context.
Chris Lattnere5cb5862008-12-04 23:50:19 +0000572 if (getCurFunctionOrMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000573 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000574
Chris Lattner7e637512008-01-12 08:14:25 +0000575 // Pre-defined identifiers are of type char[x], where x is the length of the
576 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000577 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000578 if (FunctionDecl *FD = getCurFunctionDecl())
579 Length = FD->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000580 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000581 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000582
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000583 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000584 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000585 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000586 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000587}
588
Steve Naroff87d58b42007-09-16 03:34:24 +0000589Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000590 llvm::SmallString<16> CharBuffer;
591 CharBuffer.resize(Tok.getLength());
592 const char *ThisTokBegin = &CharBuffer[0];
593 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
594
595 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
596 Tok.getLocation(), PP);
597 if (Literal.hadError())
598 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000599
600 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
601
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000602 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
603 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000604}
605
Steve Naroff87d58b42007-09-16 03:34:24 +0000606Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000607 // fast path for a single digit (which is quite common). A single digit
608 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
609 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000610 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000611
Chris Lattner8cd0e932008-03-05 18:54:05 +0000612 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000613 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000614 Context.IntTy,
615 Tok.getLocation()));
616 }
617 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000618 // Add padding so that NumericLiteralParser can overread by one character.
619 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000620 const char *ThisTokBegin = &IntegerBuffer[0];
621
622 // Get the spelling of the token, which eliminates trigraphs, etc.
623 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000624
Chris Lattner4b009652007-07-25 00:24:17 +0000625 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
626 Tok.getLocation(), PP);
627 if (Literal.hadError)
628 return ExprResult(true);
629
Chris Lattner1de66eb2007-08-26 03:42:43 +0000630 Expr *Res;
631
632 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000633 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000634 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000635 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000636 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000637 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000638 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000639 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000640
641 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
642
Ted Kremenekddedbe22007-11-29 00:56:49 +0000643 // isExact will be set by GetFloatValue().
644 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000645 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000646 Ty, Tok.getLocation());
647
Chris Lattner1de66eb2007-08-26 03:42:43 +0000648 } else if (!Literal.isIntegerLiteral()) {
649 return ExprResult(true);
650 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000651 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000652
Neil Booth7421e9c2007-08-29 22:00:19 +0000653 // long long is a C99 feature.
654 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000655 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000656 Diag(Tok.getLocation(), diag::ext_longlong);
657
Chris Lattner4b009652007-07-25 00:24:17 +0000658 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000659 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000660
661 if (Literal.GetIntegerValue(ResultVal)) {
662 // If this value didn't fit into uintmax_t, warn and force to ull.
663 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000664 Ty = Context.UnsignedLongLongTy;
665 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000666 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000667 } else {
668 // If this value fits into a ULL, try to figure out what else it fits into
669 // according to the rules of C99 6.4.4.1p5.
670
671 // Octal, Hexadecimal, and integers with a U suffix are allowed to
672 // be an unsigned int.
673 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
674
675 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000676 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000677 if (!Literal.isLong && !Literal.isLongLong) {
678 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000679 unsigned IntSize = Context.Target.getIntWidth();
680
Chris Lattner4b009652007-07-25 00:24:17 +0000681 // Does it fit in a unsigned int?
682 if (ResultVal.isIntN(IntSize)) {
683 // Does it fit in a signed int?
684 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000685 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000686 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000687 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000688 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000689 }
Chris Lattner4b009652007-07-25 00:24:17 +0000690 }
691
692 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000693 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000694 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000695
696 // Does it fit in a unsigned long?
697 if (ResultVal.isIntN(LongSize)) {
698 // Does it fit in a signed long?
699 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000700 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000701 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000702 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000703 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000704 }
Chris Lattner4b009652007-07-25 00:24:17 +0000705 }
706
707 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000708 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000709 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000710
711 // Does it fit in a unsigned long long?
712 if (ResultVal.isIntN(LongLongSize)) {
713 // Does it fit in a signed long long?
714 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000715 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000716 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000717 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000718 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000719 }
720 }
721
722 // If we still couldn't decide a type, we probably have something that
723 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000724 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000725 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000726 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000727 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000728 }
Chris Lattnere4068872008-05-09 05:59:00 +0000729
730 if (ResultVal.getBitWidth() != Width)
731 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000732 }
733
Chris Lattner48d7f382008-04-02 04:24:33 +0000734 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000735 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000736
737 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
738 if (Literal.isImaginary)
739 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
740
741 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000742}
743
Steve Naroff87d58b42007-09-16 03:34:24 +0000744Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000745 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000746 Expr *E = (Expr *)Val;
747 assert((E != 0) && "ActOnParenExpr() missing expr");
748 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000749}
750
751/// The UsualUnaryConversions() function is *not* called by this routine.
752/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000753bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
754 SourceLocation OpLoc,
755 const SourceRange &ExprRange,
756 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000757 // C99 6.5.3.4p1:
758 if (isa<FunctionType>(exprType) && isSizeof)
759 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000760 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000761 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000762 Diag(OpLoc, diag::ext_sizeof_void_type)
763 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
764 else if (exprType->isIncompleteType())
765 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
766 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000767 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000768
769 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000770}
771
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000772/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
773/// the same for @c alignof and @c __alignof
774/// Note that the ArgRange is invalid if isType is false.
775Action::ExprResult
776Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
777 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000778 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000779 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000780
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000781 QualType ArgTy;
782 SourceRange Range;
783 if (isType) {
784 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
785 Range = ArgRange;
786 } else {
787 // Get the end location.
788 Expr *ArgEx = (Expr *)TyOrEx;
789 Range = ArgEx->getSourceRange();
790 ArgTy = ArgEx->getType();
791 }
792
793 // Verify that the operand is valid.
794 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000795 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000796
797 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
798 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
799 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000800}
801
Chris Lattner5110ad52007-08-24 21:41:10 +0000802QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000803 DefaultFunctionArrayConversion(V);
804
Chris Lattnera16e42d2007-08-26 05:39:26 +0000805 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000806 if (const ComplexType *CT = V->getType()->getAsComplexType())
807 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000808
809 // Otherwise they pass through real integer and floating point types here.
810 if (V->getType()->isArithmeticType())
811 return V->getType();
812
813 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000814 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000815 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000816}
817
818
Chris Lattner4b009652007-07-25 00:24:17 +0000819
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000820Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000821 tok::TokenKind Kind,
822 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000823 Expr *Arg = (Expr *)Input;
824
Chris Lattner4b009652007-07-25 00:24:17 +0000825 UnaryOperator::Opcode Opc;
826 switch (Kind) {
827 default: assert(0 && "Unknown unary op!");
828 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
829 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
830 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000831
832 if (getLangOptions().CPlusPlus &&
833 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
834 // Which overloaded operator?
835 OverloadedOperatorKind OverOp =
836 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
837
838 // C++ [over.inc]p1:
839 //
840 // [...] If the function is a member function with one
841 // parameter (which shall be of type int) or a non-member
842 // function with two parameters (the second of which shall be
843 // of type int), it defines the postfix increment operator ++
844 // for objects of that type. When the postfix increment is
845 // called as a result of using the ++ operator, the int
846 // argument will have value zero.
847 Expr *Args[2] = {
848 Arg,
849 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
850 /*isSigned=*/true),
851 Context.IntTy, SourceLocation())
852 };
853
854 // Build the candidate set for overloading
855 OverloadCandidateSet CandidateSet;
856 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
857
858 // Perform overload resolution.
859 OverloadCandidateSet::iterator Best;
860 switch (BestViableFunction(CandidateSet, Best)) {
861 case OR_Success: {
862 // We found a built-in operator or an overloaded operator.
863 FunctionDecl *FnDecl = Best->Function;
864
865 if (FnDecl) {
866 // We matched an overloaded operator. Build a call to that
867 // operator.
868
869 // Convert the arguments.
870 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
871 if (PerformObjectArgumentInitialization(Arg, Method))
872 return true;
873 } else {
874 // Convert the arguments.
875 if (PerformCopyInitialization(Arg,
876 FnDecl->getParamDecl(0)->getType(),
877 "passing"))
878 return true;
879 }
880
881 // Determine the result type
882 QualType ResultTy
883 = FnDecl->getType()->getAsFunctionType()->getResultType();
884 ResultTy = ResultTy.getNonReferenceType();
885
886 // Build the actual expression node.
887 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
888 SourceLocation());
889 UsualUnaryConversions(FnExpr);
890
891 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
892 } else {
893 // We matched a built-in operator. Convert the arguments, then
894 // break out so that we will build the appropriate built-in
895 // operator node.
896 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
897 "passing"))
898 return true;
899
900 break;
901 }
902 }
903
904 case OR_No_Viable_Function:
905 // No viable function; fall through to handling this as a
906 // built-in operator, which will produce an error message for us.
907 break;
908
909 case OR_Ambiguous:
910 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
911 << UnaryOperator::getOpcodeStr(Opc)
912 << Arg->getSourceRange();
913 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
914 return true;
915 }
916
917 // Either we found no viable overloaded operator or we matched a
918 // built-in operator. In either case, fall through to trying to
919 // build a built-in operation.
920 }
921
922 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000923 if (result.isNull())
924 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000925 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000926}
927
928Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000929ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000930 ExprTy *Idx, SourceLocation RLoc) {
931 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
932
Douglas Gregor80723c52008-11-19 17:17:41 +0000933 if (getLangOptions().CPlusPlus &&
934 LHSExp->getType()->isRecordType() ||
935 LHSExp->getType()->isEnumeralType() ||
936 RHSExp->getType()->isRecordType() ||
Sebastian Redle5edfce2008-12-03 16:32:40 +0000937 RHSExp->getType()->isEnumeralType()) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000938 // Add the appropriate overloaded operators (C++ [over.match.oper])
939 // to the candidate set.
940 OverloadCandidateSet CandidateSet;
941 Expr *Args[2] = { LHSExp, RHSExp };
942 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
943
944 // Perform overload resolution.
945 OverloadCandidateSet::iterator Best;
946 switch (BestViableFunction(CandidateSet, Best)) {
947 case OR_Success: {
948 // We found a built-in operator or an overloaded operator.
949 FunctionDecl *FnDecl = Best->Function;
950
951 if (FnDecl) {
952 // We matched an overloaded operator. Build a call to that
953 // operator.
954
955 // Convert the arguments.
956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
957 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
958 PerformCopyInitialization(RHSExp,
959 FnDecl->getParamDecl(0)->getType(),
960 "passing"))
961 return true;
962 } else {
963 // Convert the arguments.
964 if (PerformCopyInitialization(LHSExp,
965 FnDecl->getParamDecl(0)->getType(),
966 "passing") ||
967 PerformCopyInitialization(RHSExp,
968 FnDecl->getParamDecl(1)->getType(),
969 "passing"))
970 return true;
971 }
972
973 // Determine the result type
974 QualType ResultTy
975 = FnDecl->getType()->getAsFunctionType()->getResultType();
976 ResultTy = ResultTy.getNonReferenceType();
977
978 // Build the actual expression node.
979 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
980 SourceLocation());
981 UsualUnaryConversions(FnExpr);
982
983 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
984 } else {
985 // We matched a built-in operator. Convert the arguments, then
986 // break out so that we will build the appropriate built-in
987 // operator node.
988 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
989 "passing") ||
990 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
991 "passing"))
992 return true;
993
994 break;
995 }
996 }
997
998 case OR_No_Viable_Function:
999 // No viable function; fall through to handling this as a
1000 // built-in operator, which will produce an error message for us.
1001 break;
1002
1003 case OR_Ambiguous:
1004 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1005 << "[]"
1006 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1007 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1008 return true;
1009 }
1010
1011 // Either we found no viable overloaded operator or we matched a
1012 // built-in operator. In either case, fall through to trying to
1013 // build a built-in operation.
1014 }
1015
Chris Lattner4b009652007-07-25 00:24:17 +00001016 // Perform default conversions.
1017 DefaultFunctionArrayConversion(LHSExp);
1018 DefaultFunctionArrayConversion(RHSExp);
1019
1020 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1021
1022 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001023 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001024 // in the subscript position. As a result, we need to derive the array base
1025 // and index from the expression types.
1026 Expr *BaseExpr, *IndexExpr;
1027 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001028 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001029 BaseExpr = LHSExp;
1030 IndexExpr = RHSExp;
1031 // FIXME: need to deal with const...
1032 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001033 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001034 // Handle the uncommon case of "123[Ptr]".
1035 BaseExpr = RHSExp;
1036 IndexExpr = LHSExp;
1037 // FIXME: need to deal with const...
1038 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001039 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1040 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001041 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001042
1043 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001044 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1045 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001046 return Diag(LLoc, diag::err_ext_vector_component_access)
1047 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001048 // FIXME: need to deal with const...
1049 ResultType = VTy->getElementType();
1050 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001051 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1052 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001053 }
1054 // C99 6.5.2.1p1
1055 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001056 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1057 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001058
1059 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1060 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001061 // void (*)(int)) and pointers to incomplete types. Functions are not
1062 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001063 if (!ResultType->isObjectType())
1064 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001065 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001066 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001067
1068 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1069}
1070
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001071QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001072CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001073 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001074 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001075
1076 // This flag determines whether or not the component is to be treated as a
1077 // special name, or a regular GLSL-style component access.
1078 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001079
1080 // The vector accessor can't exceed the number of elements.
1081 const char *compStr = CompName.getName();
1082 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001083 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001084 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001085 return QualType();
1086 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001087
1088 // Check that we've found one of the special components, or that the component
1089 // names must come from the same set.
1090 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1091 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1092 SpecialComponent = true;
1093 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001094 do
1095 compStr++;
1096 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1097 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1098 do
1099 compStr++;
1100 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1101 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1102 do
1103 compStr++;
1104 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1105 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001106
Nate Begemanc8e51f82008-05-09 06:41:27 +00001107 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001108 // We didn't get to the end of the string. This means the component names
1109 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001110 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1111 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001112 return QualType();
1113 }
1114 // Each component accessor can't exceed the vector type.
1115 compStr = CompName.getName();
1116 while (*compStr) {
1117 if (vecType->isAccessorWithinNumElements(*compStr))
1118 compStr++;
1119 else
1120 break;
1121 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001122 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001123 // We didn't get to the end of the string. This means a component accessor
1124 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001125 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001126 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001127 return QualType();
1128 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001129
1130 // If we have a special component name, verify that the current vector length
1131 // is an even number, since all special component names return exactly half
1132 // the elements.
1133 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001134 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001135 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001136 return QualType();
1137 }
1138
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001139 // The component accessor looks fine - now we need to compute the actual type.
1140 // The vector type is implied by the component accessor. For example,
1141 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001142 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1143 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001144 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001145 if (CompSize == 1)
1146 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001147
Nate Begemanaf6ed502008-04-18 23:10:10 +00001148 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001149 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001150 // diagostics look bad. We want extended vector types to appear built-in.
1151 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1152 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1153 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001154 }
1155 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001156}
1157
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001158/// constructSetterName - Return the setter name for the given
1159/// identifier, i.e. "set" + Name where the initial character of Name
1160/// has been capitalized.
1161// FIXME: Merge with same routine in Parser. But where should this
1162// live?
1163static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1164 const IdentifierInfo *Name) {
1165 llvm::SmallString<100> SelectorName;
1166 SelectorName = "set";
1167 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1168 SelectorName[3] = toupper(SelectorName[3]);
1169 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1170}
1171
Chris Lattner4b009652007-07-25 00:24:17 +00001172Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001173ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001174 tok::TokenKind OpKind, SourceLocation MemberLoc,
1175 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001176 Expr *BaseExpr = static_cast<Expr *>(Base);
1177 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001178
1179 // Perform default conversions.
1180 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001181
Steve Naroff2cb66382007-07-26 03:11:44 +00001182 QualType BaseType = BaseExpr->getType();
1183 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001184
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001185 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1186 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001187 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001188 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001189 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001190 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1191 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001192 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001193 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001194 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001196
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001197 // Handle field access to simple records. This also handles access to fields
1198 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001199 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001200 RecordDecl *RDecl = RTy->getDecl();
1201 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001202 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001203 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001204 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001205 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1206 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001207 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001208 << &Member << BaseExpr->getSourceRange();
Eli Friedman76b49832008-02-06 22:48:16 +00001209
1210 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001211 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001212 QualType MemberType = MemberDecl->getType();
1213 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001214 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001215 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1216 if (CXXMember->isMutable())
1217 combinedQualifiers &= ~QualType::Const;
1218 }
Eli Friedman76b49832008-02-06 22:48:16 +00001219 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1220
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001221 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001222 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001223 }
1224
Chris Lattnere9d71612008-07-21 04:59:05 +00001225 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1226 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001227 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1228 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001229 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001230 OpKind == tok::arrow);
Chris Lattner8ba580c2008-11-19 05:08:23 +00001231 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001232 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001233 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001234 }
1235
Chris Lattnere9d71612008-07-21 04:59:05 +00001236 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1237 // pointer to a (potentially qualified) interface type.
1238 const PointerType *PTy;
1239 const ObjCInterfaceType *IFTy;
1240 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1241 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1242 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001243
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001244 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001245 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1246 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1247
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001248 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001249 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1250 E = IFTy->qual_end(); I != E; ++I)
1251 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1252 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001253
1254 // If that failed, look for an "implicit" property by seeing if the nullary
1255 // selector is implemented.
1256
1257 // FIXME: The logic for looking up nullary and unary selectors should be
1258 // shared with the code in ActOnInstanceMessage.
1259
1260 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1261 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1262
1263 // If this reference is in an @implementation, check for 'private' methods.
1264 if (!Getter)
1265 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1266 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1267 if (ObjCImplementationDecl *ImpDecl =
1268 ObjCImplementations[ClassDecl->getIdentifier()])
1269 Getter = ImpDecl->getInstanceMethod(Sel);
1270
Steve Naroff04151f32008-10-22 19:16:27 +00001271 // Look through local category implementations associated with the class.
1272 if (!Getter) {
1273 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1274 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1275 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1276 }
1277 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001278 if (Getter) {
1279 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001280 // will look for the matching setter, in case it is needed.
1281 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1282 &Member);
1283 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1284 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1285 if (!Setter) {
1286 // If this reference is in an @implementation, also check for 'private'
1287 // methods.
1288 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1289 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1290 if (ObjCImplementationDecl *ImpDecl =
1291 ObjCImplementations[ClassDecl->getIdentifier()])
1292 Setter = ImpDecl->getInstanceMethod(SetterSel);
1293 }
1294 // Look through local category implementations associated with the class.
1295 if (!Setter) {
1296 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1297 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1298 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1299 }
1300 }
1301
1302 // FIXME: we must check that the setter has property type.
1303 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001304 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001305 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001306 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001307 // Handle properties on qualified "id" protocols.
1308 const ObjCQualifiedIdType *QIdTy;
1309 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1310 // Check protocols on qualified interfaces.
1311 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1312 E = QIdTy->qual_end(); I != E; ++I)
1313 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1314 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1315 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001316 // Handle 'field access' to vectors, such as 'V.xx'.
1317 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1318 // Component access limited to variables (reject vec4.rg.g).
1319 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1320 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001321 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1322 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001323 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1324 if (ret.isNull())
1325 return true;
1326 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1327 }
1328
Chris Lattner8ba580c2008-11-19 05:08:23 +00001329 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001330 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001331}
1332
Steve Naroff87d58b42007-09-16 03:34:24 +00001333/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001334/// This provides the location of the left/right parens and a list of comma
1335/// locations.
1336Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001337ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001338 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001339 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1340 Expr *Fn = static_cast<Expr *>(fn);
1341 Expr **Args = reinterpret_cast<Expr**>(args);
1342 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001343 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001344 OverloadedFunctionDecl *Ovl = NULL;
1345
Douglas Gregora133e262008-12-06 00:22:45 +00001346 // Determine whether this is a dependent call inside a C++ template,
1347 // in which case we won't do any semantic analysis now.
1348 bool Dependent = false;
1349 if (Fn->isTypeDependent()) {
1350 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1351 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1352 Dependent = true;
1353 else {
1354 // Resolve the CXXDependentNameExpr to an actual identifier;
1355 // it wasn't really a dependent name after all.
1356 ExprResult Resolved
1357 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1358 /*HasTrailingLParen=*/true,
1359 /*SS=*/0,
1360 /*ForceResolution=*/true);
1361 if (Resolved.isInvalid)
1362 return true;
1363 else {
1364 delete Fn;
1365 Fn = (Expr *)Resolved.Val;
1366 }
1367 }
1368 } else
1369 Dependent = true;
1370 } else
1371 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1372
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001373 // FIXME: Will need to cache the results of name lookup (including
1374 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001375 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001376 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1377
Douglas Gregord2baafd2008-10-21 16:13:35 +00001378 // If we're directly calling a function or a set of overloaded
1379 // functions, get the appropriate declaration.
1380 {
1381 DeclRefExpr *DRExpr = NULL;
1382 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1383 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1384 else
1385 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1386
1387 if (DRExpr) {
1388 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1389 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1390 }
1391 }
1392
Douglas Gregord2baafd2008-10-21 16:13:35 +00001393 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001394 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1395 RParenLoc);
1396 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001397 return true;
1398
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001399 // Update Fn to refer to the actual function selected.
1400 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1401 Fn->getSourceRange().getBegin());
1402 Fn->Destroy(Context);
1403 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001404 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001405
Douglas Gregor10f3c502008-11-19 21:05:33 +00001406 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001407 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001408 CommaLocs, RParenLoc);
1409
Chris Lattner3e254fb2008-04-08 04:40:51 +00001410 // Promote the function operand.
1411 UsualUnaryConversions(Fn);
1412
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001413 // Make the call expr early, before semantic checks. This guarantees cleanup
1414 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001415 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001416 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001417
Steve Naroffd6163f32008-09-05 22:11:13 +00001418 const FunctionType *FuncT;
1419 if (!Fn->getType()->isBlockPointerType()) {
1420 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1421 // have type pointer to function".
1422 const PointerType *PT = Fn->getType()->getAsPointerType();
1423 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001424 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001425 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001426 FuncT = PT->getPointeeType()->getAsFunctionType();
1427 } else { // This is a block call.
1428 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1429 getAsFunctionType();
1430 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001431 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001432 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001433 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001434
1435 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001436 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001437
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001438 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001439 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1440 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001441 unsigned NumArgsInProto = Proto->getNumArgs();
1442 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001443
Chris Lattner3e254fb2008-04-08 04:40:51 +00001444 // If too few arguments are available (and we don't have default
1445 // arguments for the remaining parameters), don't make the call.
1446 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001447 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1448 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1449 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1450 // Use default arguments for missing arguments
1451 NumArgsToCheck = NumArgsInProto;
1452 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001453 }
1454
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001455 // If too many are passed and not variadic, error on the extras and drop
1456 // them.
1457 if (NumArgs > NumArgsInProto) {
1458 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001459 Diag(Args[NumArgsInProto]->getLocStart(),
1460 diag::err_typecheck_call_too_many_args)
1461 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001462 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1463 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001464 // This deletes the extra arguments.
1465 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001466 }
1467 NumArgsToCheck = NumArgsInProto;
1468 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001469
Chris Lattner4b009652007-07-25 00:24:17 +00001470 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001471 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001472 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001473
1474 Expr *Arg;
1475 if (i < NumArgs)
1476 Arg = Args[i];
1477 else
1478 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001479 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001480
Douglas Gregor81c29152008-10-29 00:13:59 +00001481 // Pass the argument.
1482 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001483 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001484
1485 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001486 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001487
1488 // If this is a variadic call, handle args passed through "...".
1489 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001490 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001491 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1492 Expr *Arg = Args[i];
1493 DefaultArgumentPromotion(Arg);
1494 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001495 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001496 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001497 } else {
1498 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1499
Steve Naroffdb65e052007-08-28 23:30:39 +00001500 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001501 for (unsigned i = 0; i != NumArgs; i++) {
1502 Expr *Arg = Args[i];
1503 DefaultArgumentPromotion(Arg);
1504 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001505 }
Chris Lattner4b009652007-07-25 00:24:17 +00001506 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001507
Chris Lattner2e64c072007-08-10 20:18:51 +00001508 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001509 if (FDecl)
1510 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001511
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001512 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001513}
1514
1515Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001516ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001517 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001518 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001519 QualType literalType = QualType::getFromOpaquePtr(Ty);
1520 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001521 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001522 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001523
Eli Friedman8c2173d2008-05-20 05:22:08 +00001524 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001525 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001526 return Diag(LParenLoc, diag::err_variable_object_no_init)
1527 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001528 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001529 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001530 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001531 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001532 }
1533
Douglas Gregor6428e762008-11-05 15:29:30 +00001534 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001535 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001536 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001537
Chris Lattnere5cb5862008-12-04 23:50:19 +00001538 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001539 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001540 if (CheckForConstantInitializer(literalExpr, literalType))
1541 return true;
1542 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001543 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1544 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001545}
1546
1547Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001548ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001549 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001550 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001551 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001552
Steve Naroff0acc9c92007-09-15 18:49:24 +00001553 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001554 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001555
Chris Lattner71ca8c82008-10-26 23:43:26 +00001556 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1557 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001558 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1559 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001560}
1561
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001562/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001563bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001564 UsualUnaryConversions(castExpr);
1565
1566 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1567 // type needs to be scalar.
1568 if (castType->isVoidType()) {
1569 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001570 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1571 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001572 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1573 // GCC struct/union extension: allow cast to self.
1574 if (Context.getCanonicalType(castType) !=
1575 Context.getCanonicalType(castExpr->getType()) ||
1576 (!castType->isStructureType() && !castType->isUnionType())) {
1577 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001578 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001579 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001580 }
1581
1582 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001583 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001584 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001585 } else if (!castExpr->getType()->isScalarType() &&
1586 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001587 return Diag(castExpr->getLocStart(),
1588 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001589 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001590 } else if (castExpr->getType()->isVectorType()) {
1591 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1592 return true;
1593 } else if (castType->isVectorType()) {
1594 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1595 return true;
1596 }
1597 return false;
1598}
1599
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001600bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001601 assert(VectorTy->isVectorType() && "Not a vector type!");
1602
1603 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001604 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001605 return Diag(R.getBegin(),
1606 Ty->isVectorType() ?
1607 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001608 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001609 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001610 } else
1611 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001612 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001613 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001614
1615 return false;
1616}
1617
Chris Lattner4b009652007-07-25 00:24:17 +00001618Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001619ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001620 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001621 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001622
1623 Expr *castExpr = static_cast<Expr*>(Op);
1624 QualType castType = QualType::getFromOpaquePtr(Ty);
1625
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001626 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1627 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001628 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001629}
1630
Chris Lattner98a425c2007-11-26 01:40:58 +00001631/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1632/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001633inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1634 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1635 UsualUnaryConversions(cond);
1636 UsualUnaryConversions(lex);
1637 UsualUnaryConversions(rex);
1638 QualType condT = cond->getType();
1639 QualType lexT = lex->getType();
1640 QualType rexT = rex->getType();
1641
1642 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001643 if (!cond->isTypeDependent()) {
1644 if (!condT->isScalarType()) { // C99 6.5.15p2
1645 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1646 return QualType();
1647 }
Chris Lattner4b009652007-07-25 00:24:17 +00001648 }
Chris Lattner992ae932008-01-06 22:42:25 +00001649
1650 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001651 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1652 return Context.DependentTy;
1653
Chris Lattner992ae932008-01-06 22:42:25 +00001654 // If both operands have arithmetic type, do the usual arithmetic conversions
1655 // to find a common type: C99 6.5.15p3,5.
1656 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001657 UsualArithmeticConversions(lex, rex);
1658 return lex->getType();
1659 }
Chris Lattner992ae932008-01-06 22:42:25 +00001660
1661 // If both operands are the same structure or union type, the result is that
1662 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001663 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001664 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001665 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001666 // "If both the operands have structure or union type, the result has
1667 // that type." This implies that CV qualifiers are dropped.
1668 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001669 }
Chris Lattner992ae932008-01-06 22:42:25 +00001670
1671 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001672 // The following || allows only one side to be void (a GCC-ism).
1673 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001674 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001675 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1676 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001677 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001678 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1679 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001680 ImpCastExprToType(lex, Context.VoidTy);
1681 ImpCastExprToType(rex, Context.VoidTy);
1682 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001683 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001684 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1685 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001686 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1687 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001688 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001689 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001690 return lexT;
1691 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001692 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1693 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001694 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001695 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001696 return rexT;
1697 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001698 // Handle the case where both operands are pointers before we handle null
1699 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001700 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1701 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1702 // get the "pointed to" types
1703 QualType lhptee = LHSPT->getPointeeType();
1704 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001705
Chris Lattner71225142007-07-31 21:27:01 +00001706 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1707 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001708 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001709 // Figure out necessary qualifiers (C99 6.5.15p6)
1710 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001711 QualType destType = Context.getPointerType(destPointee);
1712 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1713 ImpCastExprToType(rex, destType); // promote to void*
1714 return destType;
1715 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001716 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001717 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001718 QualType destType = Context.getPointerType(destPointee);
1719 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1720 ImpCastExprToType(rex, destType); // promote to void*
1721 return destType;
1722 }
Chris Lattner4b009652007-07-25 00:24:17 +00001723
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001724 QualType compositeType = lexT;
1725
1726 // If either type is an Objective-C object type then check
1727 // compatibility according to Objective-C.
1728 if (Context.isObjCObjectPointerType(lexT) ||
1729 Context.isObjCObjectPointerType(rexT)) {
1730 // If both operands are interfaces and either operand can be
1731 // assigned to the other, use that type as the composite
1732 // type. This allows
1733 // xxx ? (A*) a : (B*) b
1734 // where B is a subclass of A.
1735 //
1736 // Additionally, as for assignment, if either type is 'id'
1737 // allow silent coercion. Finally, if the types are
1738 // incompatible then make sure to use 'id' as the composite
1739 // type so the result is acceptable for sending messages to.
1740
1741 // FIXME: This code should not be localized to here. Also this
1742 // should use a compatible check instead of abusing the
1743 // canAssignObjCInterfaces code.
1744 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1745 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1746 if (LHSIface && RHSIface &&
1747 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1748 compositeType = lexT;
1749 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001750 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001751 compositeType = rexT;
1752 } else if (Context.isObjCIdType(lhptee) ||
1753 Context.isObjCIdType(rhptee)) {
1754 // FIXME: This code looks wrong, because isObjCIdType checks
1755 // the struct but getObjCIdType returns the pointer to
1756 // struct. This is horrible and should be fixed.
1757 compositeType = Context.getObjCIdType();
1758 } else {
1759 QualType incompatTy = Context.getObjCIdType();
1760 ImpCastExprToType(lex, incompatTy);
1761 ImpCastExprToType(rex, incompatTy);
1762 return incompatTy;
1763 }
1764 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1765 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001766 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001767 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001768 // In this situation, we assume void* type. No especially good
1769 // reason, but this is what gcc does, and we do have to pick
1770 // to get a consistent AST.
1771 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001772 ImpCastExprToType(lex, incompatTy);
1773 ImpCastExprToType(rex, incompatTy);
1774 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001775 }
1776 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001777 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1778 // differently qualified versions of compatible types, the result type is
1779 // a pointer to an appropriately qualified version of the *composite*
1780 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001781 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001782 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001783 ImpCastExprToType(lex, compositeType);
1784 ImpCastExprToType(rex, compositeType);
1785 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001786 }
Chris Lattner4b009652007-07-25 00:24:17 +00001787 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001788 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1789 // evaluates to "struct objc_object *" (and is handled above when comparing
1790 // id with statically typed objects).
1791 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1792 // GCC allows qualified id and any Objective-C type to devolve to
1793 // id. Currently localizing to here until clear this should be
1794 // part of ObjCQualifiedIdTypesAreCompatible.
1795 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1796 (lexT->isObjCQualifiedIdType() &&
1797 Context.isObjCObjectPointerType(rexT)) ||
1798 (rexT->isObjCQualifiedIdType() &&
1799 Context.isObjCObjectPointerType(lexT))) {
1800 // FIXME: This is not the correct composite type. This only
1801 // happens to work because id can more or less be used anywhere,
1802 // however this may change the type of method sends.
1803 // FIXME: gcc adds some type-checking of the arguments and emits
1804 // (confusing) incompatible comparison warnings in some
1805 // cases. Investigate.
1806 QualType compositeType = Context.getObjCIdType();
1807 ImpCastExprToType(lex, compositeType);
1808 ImpCastExprToType(rex, compositeType);
1809 return compositeType;
1810 }
1811 }
1812
Steve Naroff3eac7692008-09-10 19:17:48 +00001813 // Selection between block pointer types is ok as long as they are the same.
1814 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1815 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1816 return lexT;
1817
Chris Lattner992ae932008-01-06 22:42:25 +00001818 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001819 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001820 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001821 return QualType();
1822}
1823
Steve Naroff87d58b42007-09-16 03:34:24 +00001824/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001825/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001826Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001827 SourceLocation ColonLoc,
1828 ExprTy *Cond, ExprTy *LHS,
1829 ExprTy *RHS) {
1830 Expr *CondExpr = (Expr *) Cond;
1831 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001832
1833 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1834 // was the condition.
1835 bool isLHSNull = LHSExpr == 0;
1836 if (isLHSNull)
1837 LHSExpr = CondExpr;
1838
Chris Lattner4b009652007-07-25 00:24:17 +00001839 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1840 RHSExpr, QuestionLoc);
1841 if (result.isNull())
1842 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001843 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1844 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001845}
1846
Chris Lattner4b009652007-07-25 00:24:17 +00001847
1848// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1849// being closely modeled after the C99 spec:-). The odd characteristic of this
1850// routine is it effectively iqnores the qualifiers on the top level pointee.
1851// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1852// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001853Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001854Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1855 QualType lhptee, rhptee;
1856
1857 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001858 lhptee = lhsType->getAsPointerType()->getPointeeType();
1859 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001860
1861 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001862 lhptee = Context.getCanonicalType(lhptee);
1863 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001864
Chris Lattner005ed752008-01-04 18:04:52 +00001865 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001866
1867 // C99 6.5.16.1p1: This following citation is common to constraints
1868 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1869 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001870 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001871 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001872 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001873
1874 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1875 // incomplete type and the other is a pointer to a qualified or unqualified
1876 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001877 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001878 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001879 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001880
1881 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001882 assert(rhptee->isFunctionType());
1883 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001884 }
1885
1886 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001887 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001888 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001889
1890 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001891 assert(lhptee->isFunctionType());
1892 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001893 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001894
1895 // Check for ObjC interfaces
1896 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1897 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1898 if (LHSIface && RHSIface &&
1899 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1900 return ConvTy;
1901
1902 // ID acts sort of like void* for ObjC interfaces
1903 if (LHSIface && Context.isObjCIdType(rhptee))
1904 return ConvTy;
1905 if (RHSIface && Context.isObjCIdType(lhptee))
1906 return ConvTy;
1907
Chris Lattner4b009652007-07-25 00:24:17 +00001908 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1909 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001910 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1911 rhptee.getUnqualifiedType()))
1912 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001913 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001914}
1915
Steve Naroff3454b6c2008-09-04 15:10:53 +00001916/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1917/// block pointer types are compatible or whether a block and normal pointer
1918/// are compatible. It is more restrict than comparing two function pointer
1919// types.
1920Sema::AssignConvertType
1921Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1922 QualType rhsType) {
1923 QualType lhptee, rhptee;
1924
1925 // get the "pointed to" type (ignoring qualifiers at the top level)
1926 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1927 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1928
1929 // make sure we operate on the canonical type
1930 lhptee = Context.getCanonicalType(lhptee);
1931 rhptee = Context.getCanonicalType(rhptee);
1932
1933 AssignConvertType ConvTy = Compatible;
1934
1935 // For blocks we enforce that qualifiers are identical.
1936 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1937 ConvTy = CompatiblePointerDiscardsQualifiers;
1938
1939 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1940 return IncompatibleBlockPointer;
1941 return ConvTy;
1942}
1943
Chris Lattner4b009652007-07-25 00:24:17 +00001944/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1945/// has code to accommodate several GCC extensions when type checking
1946/// pointers. Here are some objectionable examples that GCC considers warnings:
1947///
1948/// int a, *pint;
1949/// short *pshort;
1950/// struct foo *pfoo;
1951///
1952/// pint = pshort; // warning: assignment from incompatible pointer type
1953/// a = pint; // warning: assignment makes integer from pointer without a cast
1954/// pint = a; // warning: assignment makes pointer from integer without a cast
1955/// pint = pfoo; // warning: assignment from incompatible pointer type
1956///
1957/// As a result, the code for dealing with pointers is more complex than the
1958/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001959///
Chris Lattner005ed752008-01-04 18:04:52 +00001960Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001961Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001962 // Get canonical types. We're not formatting these types, just comparing
1963 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001964 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1965 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001966
1967 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001968 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001969
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001970 // If the left-hand side is a reference type, then we are in a
1971 // (rare!) case where we've allowed the use of references in C,
1972 // e.g., as a parameter type in a built-in function. In this case,
1973 // just make sure that the type referenced is compatible with the
1974 // right-hand side type. The caller is responsible for adjusting
1975 // lhsType so that the resulting expression does not have reference
1976 // type.
1977 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1978 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001979 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001980 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001981 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001982
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001983 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1984 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001985 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001986 // Relax integer conversions like we do for pointers below.
1987 if (rhsType->isIntegerType())
1988 return IntToPointer;
1989 if (lhsType->isIntegerType())
1990 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001991 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001992 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001993
Nate Begemanc5f0f652008-07-14 18:02:46 +00001994 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001995 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001996 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1997 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001998 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001999
Nate Begemanc5f0f652008-07-14 18:02:46 +00002000 // If we are allowing lax vector conversions, and LHS and RHS are both
2001 // vectors, the total size only needs to be the same. This is a bitcast;
2002 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002003 if (getLangOptions().LaxVectorConversions &&
2004 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002005 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2006 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002007 }
2008 return Incompatible;
2009 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002010
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002011 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002012 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002013
Chris Lattner390564e2008-04-07 06:49:41 +00002014 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002015 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002016 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002017
Chris Lattner390564e2008-04-07 06:49:41 +00002018 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002019 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002020
Steve Naroffa982c712008-09-29 18:10:17 +00002021 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002022 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002023 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002024
2025 // Treat block pointers as objects.
2026 if (getLangOptions().ObjC1 &&
2027 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2028 return Compatible;
2029 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002030 return Incompatible;
2031 }
2032
2033 if (isa<BlockPointerType>(lhsType)) {
2034 if (rhsType->isIntegerType())
2035 return IntToPointer;
2036
Steve Naroffa982c712008-09-29 18:10:17 +00002037 // Treat block pointers as objects.
2038 if (getLangOptions().ObjC1 &&
2039 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2040 return Compatible;
2041
Steve Naroff3454b6c2008-09-04 15:10:53 +00002042 if (rhsType->isBlockPointerType())
2043 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2044
2045 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2046 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002047 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002048 }
Chris Lattner1853da22008-01-04 23:18:45 +00002049 return Incompatible;
2050 }
2051
Chris Lattner390564e2008-04-07 06:49:41 +00002052 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002053 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002054 if (lhsType == Context.BoolTy)
2055 return Compatible;
2056
2057 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002058 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002059
Chris Lattner390564e2008-04-07 06:49:41 +00002060 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002061 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002062
2063 if (isa<BlockPointerType>(lhsType) &&
2064 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002065 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002066 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002067 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002068
Chris Lattner1853da22008-01-04 23:18:45 +00002069 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002070 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002071 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002072 }
2073 return Incompatible;
2074}
2075
Chris Lattner005ed752008-01-04 18:04:52 +00002076Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002077Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002078 if (getLangOptions().CPlusPlus) {
2079 if (!lhsType->isRecordType()) {
2080 // C++ 5.17p3: If the left operand is not of class type, the
2081 // expression is implicitly converted (C++ 4) to the
2082 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002083 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002084 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002085 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002086 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002087 }
2088
2089 // FIXME: Currently, we fall through and treat C++ classes like C
2090 // structures.
2091 }
2092
Steve Naroffcdee22d2007-11-27 17:58:44 +00002093 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2094 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002095 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2096 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002097 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002098 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002099 return Compatible;
2100 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002101
2102 // We don't allow conversion of non-null-pointer constants to integers.
2103 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2104 return IntToBlockPointer;
2105
Chris Lattner5f505bf2007-10-16 02:55:40 +00002106 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002107 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002108 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002109 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002110 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002111 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002112 if (!lhsType->isReferenceType())
2113 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002114
Chris Lattner005ed752008-01-04 18:04:52 +00002115 Sema::AssignConvertType result =
2116 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002117
2118 // C99 6.5.16.1p2: The value of the right operand is converted to the
2119 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002120 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2121 // so that we can use references in built-in functions even in C.
2122 // The getNonReferenceType() call makes sure that the resulting expression
2123 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002124 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002125 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002126 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002127}
2128
Chris Lattner005ed752008-01-04 18:04:52 +00002129Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002130Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2131 return CheckAssignmentConstraints(lhsType, rhsType);
2132}
2133
Chris Lattner1eafdea2008-11-18 01:30:42 +00002134QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002135 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002136 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002137 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002138 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002139}
2140
Chris Lattner1eafdea2008-11-18 01:30:42 +00002141inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002142 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002143 // For conversion purposes, we ignore any qualifiers.
2144 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002145 QualType lhsType =
2146 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2147 QualType rhsType =
2148 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002149
Nate Begemanc5f0f652008-07-14 18:02:46 +00002150 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002151 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002152 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002153
Nate Begemanc5f0f652008-07-14 18:02:46 +00002154 // Handle the case of a vector & extvector type of the same size and element
2155 // type. It would be nice if we only had one vector type someday.
2156 if (getLangOptions().LaxVectorConversions)
2157 if (const VectorType *LV = lhsType->getAsVectorType())
2158 if (const VectorType *RV = rhsType->getAsVectorType())
2159 if (LV->getElementType() == RV->getElementType() &&
2160 LV->getNumElements() == RV->getNumElements())
2161 return lhsType->isExtVectorType() ? lhsType : rhsType;
2162
2163 // If the lhs is an extended vector and the rhs is a scalar of the same type
2164 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002165 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002166 QualType eltType = V->getElementType();
2167
2168 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2169 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2170 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002171 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002172 return lhsType;
2173 }
2174 }
2175
Nate Begemanc5f0f652008-07-14 18:02:46 +00002176 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002177 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002178 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002179 QualType eltType = V->getElementType();
2180
2181 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2182 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2183 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002184 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002185 return rhsType;
2186 }
2187 }
2188
Chris Lattner4b009652007-07-25 00:24:17 +00002189 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002190 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002191 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002192 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002193 return QualType();
2194}
2195
2196inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002197 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002198{
2199 QualType lhsType = lex->getType(), rhsType = rex->getType();
2200
2201 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002202 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002203
Steve Naroff8f708362007-08-24 19:07:16 +00002204 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002205
Chris Lattner4b009652007-07-25 00:24:17 +00002206 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002207 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002208 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002209}
2210
2211inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002212 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002213{
2214 QualType lhsType = lex->getType(), rhsType = rex->getType();
2215
Steve Naroff8f708362007-08-24 19:07:16 +00002216 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002217
Chris Lattner4b009652007-07-25 00:24:17 +00002218 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002219 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002220 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002221}
2222
2223inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002224 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002225{
2226 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002227 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002228
Steve Naroff8f708362007-08-24 19:07:16 +00002229 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002230
Chris Lattner4b009652007-07-25 00:24:17 +00002231 // handle the common case first (both operands are arithmetic).
2232 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002233 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002234
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002235 // Put any potential pointer into PExp
2236 Expr* PExp = lex, *IExp = rex;
2237 if (IExp->getType()->isPointerType())
2238 std::swap(PExp, IExp);
2239
2240 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2241 if (IExp->getType()->isIntegerType()) {
2242 // Check for arithmetic on pointers to incomplete types
2243 if (!PTy->getPointeeType()->isObjectType()) {
2244 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002245 Diag(Loc, diag::ext_gnu_void_ptr)
2246 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002247 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002248 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002249 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002250 return QualType();
2251 }
2252 }
2253 return PExp->getType();
2254 }
2255 }
2256
Chris Lattner1eafdea2008-11-18 01:30:42 +00002257 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002258}
2259
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002260// C99 6.5.6
2261QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002262 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002263 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002264 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002265
Steve Naroff8f708362007-08-24 19:07:16 +00002266 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002267
Chris Lattnerf6da2912007-12-09 21:53:25 +00002268 // Enforce type constraints: C99 6.5.6p3.
2269
2270 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002271 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002272 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002273
2274 // Either ptr - int or ptr - ptr.
2275 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002276 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002277
Chris Lattnerf6da2912007-12-09 21:53:25 +00002278 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002279 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002280 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002281 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002282 Diag(Loc, diag::ext_gnu_void_ptr)
2283 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002284 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002285 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002286 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002287 return QualType();
2288 }
2289 }
2290
2291 // The result type of a pointer-int computation is the pointer type.
2292 if (rex->getType()->isIntegerType())
2293 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002294
Chris Lattnerf6da2912007-12-09 21:53:25 +00002295 // Handle pointer-pointer subtractions.
2296 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002297 QualType rpointee = RHSPTy->getPointeeType();
2298
Chris Lattnerf6da2912007-12-09 21:53:25 +00002299 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002300 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002301 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002302 if (rpointee->isVoidType()) {
2303 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002304 Diag(Loc, diag::ext_gnu_void_ptr)
2305 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002306 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002307 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002308 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002309 return QualType();
2310 }
2311 }
2312
2313 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002314 if (!Context.typesAreCompatible(
2315 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2316 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002317 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002318 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002319 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002320 return QualType();
2321 }
2322
2323 return Context.getPointerDiffType();
2324 }
2325 }
2326
Chris Lattner1eafdea2008-11-18 01:30:42 +00002327 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002328}
2329
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002330// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002331QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002332 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002333 // C99 6.5.7p2: Each of the operands shall have integer type.
2334 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002335 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002336
Chris Lattner2c8bff72007-12-12 05:47:28 +00002337 // Shifts don't perform usual arithmetic conversions, they just do integer
2338 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002339 if (!isCompAssign)
2340 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002341 UsualUnaryConversions(rex);
2342
2343 // "The type of the result is that of the promoted left operand."
2344 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002345}
2346
Eli Friedman0d9549b2008-08-22 00:56:42 +00002347static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2348 ASTContext& Context) {
2349 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2350 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2351 // ID acts sort of like void* for ObjC interfaces
2352 if (LHSIface && Context.isObjCIdType(RHS))
2353 return true;
2354 if (RHSIface && Context.isObjCIdType(LHS))
2355 return true;
2356 if (!LHSIface || !RHSIface)
2357 return false;
2358 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2359 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2360}
2361
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002362// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002363QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002364 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002365 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002366 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002367
Chris Lattner254f3bc2007-08-26 01:18:55 +00002368 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002369 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2370 UsualArithmeticConversions(lex, rex);
2371 else {
2372 UsualUnaryConversions(lex);
2373 UsualUnaryConversions(rex);
2374 }
Chris Lattner4b009652007-07-25 00:24:17 +00002375 QualType lType = lex->getType();
2376 QualType rType = rex->getType();
2377
Ted Kremenek486509e2007-10-29 17:13:39 +00002378 // For non-floating point types, check for self-comparisons of the form
2379 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2380 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002381 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002382 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2383 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002384 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002385 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002386 }
2387
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002388 // The result of comparisons is 'bool' in C++, 'int' in C.
2389 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2390
Chris Lattner254f3bc2007-08-26 01:18:55 +00002391 if (isRelational) {
2392 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002393 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002394 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002395 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002396 if (lType->isFloatingType()) {
2397 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002398 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002399 }
2400
Chris Lattner254f3bc2007-08-26 01:18:55 +00002401 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002402 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002403 }
Chris Lattner4b009652007-07-25 00:24:17 +00002404
Chris Lattner22be8422007-08-26 01:10:14 +00002405 bool LHSIsNull = lex->isNullPointerConstant(Context);
2406 bool RHSIsNull = rex->isNullPointerConstant(Context);
2407
Chris Lattner254f3bc2007-08-26 01:18:55 +00002408 // All of the following pointer related warnings are GCC extensions, except
2409 // when handling null pointer constants. One day, we can consider making them
2410 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002411 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002412 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002413 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002414 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002415 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002416
Steve Naroff3b435622007-11-13 14:57:38 +00002417 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002418 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2419 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002420 RCanPointeeTy.getUnqualifiedType()) &&
2421 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002422 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002423 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002424 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002425 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002426 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002427 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002428 // Handle block pointer types.
2429 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2430 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2431 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2432
2433 if (!LHSIsNull && !RHSIsNull &&
2434 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002435 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002436 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002437 }
2438 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002439 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002440 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002441 // Allow block pointers to be compared with null pointer constants.
2442 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2443 (lType->isPointerType() && rType->isBlockPointerType())) {
2444 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002445 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002446 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002447 }
2448 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002449 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002450 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002451
Steve Naroff936c4362008-06-03 14:04:54 +00002452 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002453 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002454 const PointerType *LPT = lType->getAsPointerType();
2455 const PointerType *RPT = rType->getAsPointerType();
2456 bool LPtrToVoid = LPT ?
2457 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2458 bool RPtrToVoid = RPT ?
2459 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2460
2461 if (!LPtrToVoid && !RPtrToVoid &&
2462 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002463 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002464 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002465 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002466 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002467 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002468 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002469 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002470 }
Steve Naroff936c4362008-06-03 14:04:54 +00002471 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2472 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002473 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002474 } else {
2475 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002476 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002477 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002478 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002479 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002480 }
Steve Naroff936c4362008-06-03 14:04:54 +00002481 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002482 }
Steve Naroff936c4362008-06-03 14:04:54 +00002483 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2484 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002485 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002486 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002487 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002488 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002489 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002490 }
Steve Naroff936c4362008-06-03 14:04:54 +00002491 if (lType->isIntegerType() &&
2492 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002493 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002494 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002495 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002496 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002497 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002498 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002499 // Handle block pointers.
2500 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2501 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002502 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002503 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002504 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002505 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002506 }
2507 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2508 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002509 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002510 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002511 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002512 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002513 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002514 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002515}
2516
Nate Begemanc5f0f652008-07-14 18:02:46 +00002517/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2518/// operates on extended vector types. Instead of producing an IntTy result,
2519/// like a scalar comparison, a vector comparison produces a vector of integer
2520/// types.
2521QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002522 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002523 bool isRelational) {
2524 // Check to make sure we're operating on vectors of the same type and width,
2525 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002526 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002527 if (vType.isNull())
2528 return vType;
2529
2530 QualType lType = lex->getType();
2531 QualType rType = rex->getType();
2532
2533 // For non-floating point types, check for self-comparisons of the form
2534 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2535 // often indicate logic errors in the program.
2536 if (!lType->isFloatingType()) {
2537 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2538 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2539 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002540 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002541 }
2542
2543 // Check for comparisons of floating point operands using != and ==.
2544 if (!isRelational && lType->isFloatingType()) {
2545 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002546 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002547 }
2548
2549 // Return the type for the comparison, which is the same as vector type for
2550 // integer vectors, or an integer type of identical size and number of
2551 // elements for floating point vectors.
2552 if (lType->isIntegerType())
2553 return lType;
2554
2555 const VectorType *VTy = lType->getAsVectorType();
2556
2557 // FIXME: need to deal with non-32b int / non-64b long long
2558 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2559 if (TypeSize == 32) {
2560 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2561 }
2562 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2563 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2564}
2565
Chris Lattner4b009652007-07-25 00:24:17 +00002566inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002567 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002568{
2569 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002570 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002571
Steve Naroff8f708362007-08-24 19:07:16 +00002572 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002573
2574 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002575 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002576 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002577}
2578
2579inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002580 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002581{
2582 UsualUnaryConversions(lex);
2583 UsualUnaryConversions(rex);
2584
Eli Friedmanbea3f842008-05-13 20:16:47 +00002585 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002586 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002587 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002588}
2589
Chris Lattner4c2642c2008-11-18 01:22:49 +00002590/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2591/// emit an error and return true. If so, return false.
2592static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2593 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2594 if (IsLV == Expr::MLV_Valid)
2595 return false;
2596
2597 unsigned Diag = 0;
2598 bool NeedType = false;
2599 switch (IsLV) { // C99 6.5.16p2
2600 default: assert(0 && "Unknown result from isModifiableLvalue!");
2601 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002602 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002603 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2604 NeedType = true;
2605 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002606 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002607 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2608 NeedType = true;
2609 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002610 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002611 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2612 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002613 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002614 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2615 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002616 case Expr::MLV_IncompleteType:
2617 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002618 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2619 NeedType = true;
2620 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002621 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002622 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2623 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002624 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002625 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2626 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002627 case Expr::MLV_ReadonlyProperty:
2628 Diag = diag::error_readonly_property_assignment;
2629 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002630 case Expr::MLV_NoSetterProperty:
2631 Diag = diag::error_nosetter_property_assignment;
2632 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002633 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002634
Chris Lattner4c2642c2008-11-18 01:22:49 +00002635 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002636 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002637 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002638 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002639 return true;
2640}
2641
2642
2643
2644// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002645QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2646 SourceLocation Loc,
2647 QualType CompoundType) {
2648 // Verify that LHS is a modifiable lvalue, and emit error if not.
2649 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002650 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002651
2652 QualType LHSType = LHS->getType();
2653 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002654
Chris Lattner005ed752008-01-04 18:04:52 +00002655 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002656 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002657 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002658 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002659
2660 // If the RHS is a unary plus or minus, check to see if they = and + are
2661 // right next to each other. If so, the user may have typo'd "x =+ 4"
2662 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002663 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002664 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2665 RHSCheck = ICE->getSubExpr();
2666 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2667 if ((UO->getOpcode() == UnaryOperator::Plus ||
2668 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002669 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002670 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002671 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002672 Diag(Loc, diag::warn_not_compound_assign)
2673 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2674 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002675 }
2676 } else {
2677 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002678 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002679 }
Chris Lattner005ed752008-01-04 18:04:52 +00002680
Chris Lattner1eafdea2008-11-18 01:30:42 +00002681 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2682 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002683 return QualType();
2684
Chris Lattner4b009652007-07-25 00:24:17 +00002685 // C99 6.5.16p3: The type of an assignment expression is the type of the
2686 // left operand unless the left operand has qualified type, in which case
2687 // it is the unqualified version of the type of the left operand.
2688 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2689 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002690 // C++ 5.17p1: the type of the assignment expression is that of its left
2691 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002692 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002693}
2694
Chris Lattner1eafdea2008-11-18 01:30:42 +00002695// C99 6.5.17
2696QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2697 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002698
2699 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002700 DefaultFunctionArrayConversion(RHS);
2701 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002702}
2703
2704/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2705/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002706QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2707 QualType ResType = Op->getType();
2708 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002709
Steve Naroffd30e1932007-08-24 17:20:07 +00002710 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002711 if (ResType->isRealType()) {
2712 // OK!
2713 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2714 // C99 6.5.2.4p2, 6.5.6p2
2715 if (PT->getPointeeType()->isObjectType()) {
2716 // Pointer to object is ok!
2717 } else if (PT->getPointeeType()->isVoidType()) {
2718 // Pointer to void is extension.
2719 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2720 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002721 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002722 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002723 return QualType();
2724 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002725 } else if (ResType->isComplexType()) {
2726 // C99 does not support ++/-- on complex types, we allow as an extension.
2727 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002728 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002729 } else {
2730 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002731 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002732 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002733 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002734 // At this point, we know we have a real, complex or pointer type.
2735 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002736 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002737 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002738 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002739}
2740
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002741/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002742/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002743/// where the declaration is needed for type checking. We only need to
2744/// handle cases when the expression references a function designator
2745/// or is an lvalue. Here are some examples:
2746/// - &(x) => x
2747/// - &*****f => f for f a function designator.
2748/// - &s.xx => s
2749/// - &s.zz[1].yy -> s, if zz is an array
2750/// - *(x + 1) -> x, if x is an array
2751/// - &"123"[2] -> 0
2752/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002753static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002754 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002755 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002756 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002757 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002758 // Fields cannot be declared with a 'register' storage class.
2759 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002760 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002761 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002762 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002763 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002764 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002765
Douglas Gregord2baafd2008-10-21 16:13:35 +00002766 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002767 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002768 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002769 return 0;
2770 else
2771 return VD;
2772 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002773 case Stmt::UnaryOperatorClass: {
2774 UnaryOperator *UO = cast<UnaryOperator>(E);
2775
2776 switch(UO->getOpcode()) {
2777 case UnaryOperator::Deref: {
2778 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002779 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2780 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2781 if (!VD || VD->getType()->isPointerType())
2782 return 0;
2783 return VD;
2784 }
2785 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002786 }
2787 case UnaryOperator::Real:
2788 case UnaryOperator::Imag:
2789 case UnaryOperator::Extension:
2790 return getPrimaryDecl(UO->getSubExpr());
2791 default:
2792 return 0;
2793 }
2794 }
2795 case Stmt::BinaryOperatorClass: {
2796 BinaryOperator *BO = cast<BinaryOperator>(E);
2797
2798 // Handle cases involving pointer arithmetic. The result of an
2799 // Assign or AddAssign is not an lvalue so they can be ignored.
2800
2801 // (x + n) or (n + x) => x
2802 if (BO->getOpcode() == BinaryOperator::Add) {
2803 if (BO->getLHS()->getType()->isPointerType()) {
2804 return getPrimaryDecl(BO->getLHS());
2805 } else if (BO->getRHS()->getType()->isPointerType()) {
2806 return getPrimaryDecl(BO->getRHS());
2807 }
2808 }
2809
2810 return 0;
2811 }
Chris Lattner4b009652007-07-25 00:24:17 +00002812 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002813 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002814 case Stmt::ImplicitCastExprClass:
2815 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002816 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002817 default:
2818 return 0;
2819 }
2820}
2821
2822/// CheckAddressOfOperand - The operand of & must be either a function
2823/// designator or an lvalue designating an object. If it is an lvalue, the
2824/// object cannot be declared with storage class register or be a bit field.
2825/// Note: The usual conversions are *not* applied to the operand of the &
2826/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002827/// In C++, the operand might be an overloaded function name, in which case
2828/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002829QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002830 if (getLangOptions().C99) {
2831 // Implement C99-only parts of addressof rules.
2832 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2833 if (uOp->getOpcode() == UnaryOperator::Deref)
2834 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2835 // (assuming the deref expression is valid).
2836 return uOp->getSubExpr()->getType();
2837 }
2838 // Technically, there should be a check for array subscript
2839 // expressions here, but the result of one is always an lvalue anyway.
2840 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002841 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002842 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002843
2844 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002845 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2846 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002847 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2848 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002849 return QualType();
2850 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002851 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2852 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002853 Diag(OpLoc, diag::err_typecheck_address_of)
2854 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002855 return QualType();
2856 }
2857 // Check for Apple extension for accessing vector components.
2858 } else if (isa<ArraySubscriptExpr>(op) &&
2859 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002860 Diag(OpLoc, diag::err_typecheck_address_of)
2861 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002862 return QualType();
2863 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002864 // We have an lvalue with a decl. Make sure the decl is not declared
2865 // with the register storage-class specifier.
2866 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2867 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002868 Diag(OpLoc, diag::err_typecheck_address_of)
2869 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002870 return QualType();
2871 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002872 } else if (isa<OverloadedFunctionDecl>(dcl))
2873 return Context.OverloadTy;
2874 else
Chris Lattner4b009652007-07-25 00:24:17 +00002875 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002876 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002877
Chris Lattner4b009652007-07-25 00:24:17 +00002878 // If the operand has type "type", the result has type "pointer to type".
2879 return Context.getPointerType(op->getType());
2880}
2881
Chris Lattnerda5c0872008-11-23 09:13:29 +00002882QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2883 UsualUnaryConversions(Op);
2884 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002885
Chris Lattnerda5c0872008-11-23 09:13:29 +00002886 // Note that per both C89 and C99, this is always legal, even if ptype is an
2887 // incomplete type or void. It would be possible to warn about dereferencing
2888 // a void pointer, but it's completely well-defined, and such a warning is
2889 // unlikely to catch any mistakes.
2890 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002891 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002892
Chris Lattner77d52da2008-11-20 06:06:08 +00002893 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002894 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002895 return QualType();
2896}
2897
2898static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2899 tok::TokenKind Kind) {
2900 BinaryOperator::Opcode Opc;
2901 switch (Kind) {
2902 default: assert(0 && "Unknown binop!");
2903 case tok::star: Opc = BinaryOperator::Mul; break;
2904 case tok::slash: Opc = BinaryOperator::Div; break;
2905 case tok::percent: Opc = BinaryOperator::Rem; break;
2906 case tok::plus: Opc = BinaryOperator::Add; break;
2907 case tok::minus: Opc = BinaryOperator::Sub; break;
2908 case tok::lessless: Opc = BinaryOperator::Shl; break;
2909 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2910 case tok::lessequal: Opc = BinaryOperator::LE; break;
2911 case tok::less: Opc = BinaryOperator::LT; break;
2912 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2913 case tok::greater: Opc = BinaryOperator::GT; break;
2914 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2915 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2916 case tok::amp: Opc = BinaryOperator::And; break;
2917 case tok::caret: Opc = BinaryOperator::Xor; break;
2918 case tok::pipe: Opc = BinaryOperator::Or; break;
2919 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2920 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2921 case tok::equal: Opc = BinaryOperator::Assign; break;
2922 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2923 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2924 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2925 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2926 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2927 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2928 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2929 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2930 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2931 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2932 case tok::comma: Opc = BinaryOperator::Comma; break;
2933 }
2934 return Opc;
2935}
2936
2937static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2938 tok::TokenKind Kind) {
2939 UnaryOperator::Opcode Opc;
2940 switch (Kind) {
2941 default: assert(0 && "Unknown unary op!");
2942 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2943 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2944 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2945 case tok::star: Opc = UnaryOperator::Deref; break;
2946 case tok::plus: Opc = UnaryOperator::Plus; break;
2947 case tok::minus: Opc = UnaryOperator::Minus; break;
2948 case tok::tilde: Opc = UnaryOperator::Not; break;
2949 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002950 case tok::kw___real: Opc = UnaryOperator::Real; break;
2951 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2952 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2953 }
2954 return Opc;
2955}
2956
Douglas Gregord7f915e2008-11-06 23:29:22 +00002957/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2958/// operator @p Opc at location @c TokLoc. This routine only supports
2959/// built-in operations; ActOnBinOp handles overloaded operators.
2960Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2961 unsigned Op,
2962 Expr *lhs, Expr *rhs) {
2963 QualType ResultTy; // Result type of the binary operator.
2964 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2965 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2966
2967 switch (Opc) {
2968 default:
2969 assert(0 && "Unknown binary expr!");
2970 case BinaryOperator::Assign:
2971 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2972 break;
2973 case BinaryOperator::Mul:
2974 case BinaryOperator::Div:
2975 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2976 break;
2977 case BinaryOperator::Rem:
2978 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2979 break;
2980 case BinaryOperator::Add:
2981 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2982 break;
2983 case BinaryOperator::Sub:
2984 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2985 break;
2986 case BinaryOperator::Shl:
2987 case BinaryOperator::Shr:
2988 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2989 break;
2990 case BinaryOperator::LE:
2991 case BinaryOperator::LT:
2992 case BinaryOperator::GE:
2993 case BinaryOperator::GT:
2994 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2995 break;
2996 case BinaryOperator::EQ:
2997 case BinaryOperator::NE:
2998 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2999 break;
3000 case BinaryOperator::And:
3001 case BinaryOperator::Xor:
3002 case BinaryOperator::Or:
3003 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3004 break;
3005 case BinaryOperator::LAnd:
3006 case BinaryOperator::LOr:
3007 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3008 break;
3009 case BinaryOperator::MulAssign:
3010 case BinaryOperator::DivAssign:
3011 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3012 if (!CompTy.isNull())
3013 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3014 break;
3015 case BinaryOperator::RemAssign:
3016 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3017 if (!CompTy.isNull())
3018 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3019 break;
3020 case BinaryOperator::AddAssign:
3021 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3022 if (!CompTy.isNull())
3023 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3024 break;
3025 case BinaryOperator::SubAssign:
3026 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3027 if (!CompTy.isNull())
3028 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3029 break;
3030 case BinaryOperator::ShlAssign:
3031 case BinaryOperator::ShrAssign:
3032 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3033 if (!CompTy.isNull())
3034 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3035 break;
3036 case BinaryOperator::AndAssign:
3037 case BinaryOperator::XorAssign:
3038 case BinaryOperator::OrAssign:
3039 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3040 if (!CompTy.isNull())
3041 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3042 break;
3043 case BinaryOperator::Comma:
3044 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3045 break;
3046 }
3047 if (ResultTy.isNull())
3048 return true;
3049 if (CompTy.isNull())
3050 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3051 else
3052 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3053}
3054
Chris Lattner4b009652007-07-25 00:24:17 +00003055// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003056Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3057 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003058 ExprTy *LHS, ExprTy *RHS) {
3059 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3060 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3061
Steve Naroff87d58b42007-09-16 03:34:24 +00003062 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3063 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003064
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003065 // If either expression is type-dependent, just build the AST.
3066 // FIXME: We'll need to perform some caching of the result of name
3067 // lookup for operator+.
3068 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3069 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3070 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3071 Context.DependentTy, TokLoc);
3072 else
3073 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3074 }
3075
Douglas Gregord7f915e2008-11-06 23:29:22 +00003076 if (getLangOptions().CPlusPlus &&
3077 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3078 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003079 // If this is one of the assignment operators, we only perform
3080 // overload resolution if the left-hand side is a class or
3081 // enumeration type (C++ [expr.ass]p3).
3082 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3083 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3084 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3085 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003086
3087 // Determine which overloaded operator we're dealing with.
3088 static const OverloadedOperatorKind OverOps[] = {
3089 OO_Star, OO_Slash, OO_Percent,
3090 OO_Plus, OO_Minus,
3091 OO_LessLess, OO_GreaterGreater,
3092 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3093 OO_EqualEqual, OO_ExclaimEqual,
3094 OO_Amp,
3095 OO_Caret,
3096 OO_Pipe,
3097 OO_AmpAmp,
3098 OO_PipePipe,
3099 OO_Equal, OO_StarEqual,
3100 OO_SlashEqual, OO_PercentEqual,
3101 OO_PlusEqual, OO_MinusEqual,
3102 OO_LessLessEqual, OO_GreaterGreaterEqual,
3103 OO_AmpEqual, OO_CaretEqual,
3104 OO_PipeEqual,
3105 OO_Comma
3106 };
3107 OverloadedOperatorKind OverOp = OverOps[Opc];
3108
Douglas Gregor5ed15042008-11-18 23:14:02 +00003109 // Add the appropriate overloaded operators (C++ [over.match.oper])
3110 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003111 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003112 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003113 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003114
3115 // Perform overload resolution.
3116 OverloadCandidateSet::iterator Best;
3117 switch (BestViableFunction(CandidateSet, Best)) {
3118 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003119 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003120 FunctionDecl *FnDecl = Best->Function;
3121
Douglas Gregor70d26122008-11-12 17:17:38 +00003122 if (FnDecl) {
3123 // We matched an overloaded operator. Build a call to that
3124 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003125
Douglas Gregor70d26122008-11-12 17:17:38 +00003126 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3128 if (PerformObjectArgumentInitialization(lhs, Method) ||
3129 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3130 "passing"))
3131 return true;
3132 } else {
3133 // Convert the arguments.
3134 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3135 "passing") ||
3136 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3137 "passing"))
3138 return true;
3139 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003140
Douglas Gregor70d26122008-11-12 17:17:38 +00003141 // Determine the result type
3142 QualType ResultTy
3143 = FnDecl->getType()->getAsFunctionType()->getResultType();
3144 ResultTy = ResultTy.getNonReferenceType();
3145
3146 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003147 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3148 SourceLocation());
3149 UsualUnaryConversions(FnExpr);
3150
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003151 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003152 } else {
3153 // We matched a built-in operator. Convert the arguments, then
3154 // break out so that we will build the appropriate built-in
3155 // operator node.
3156 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3157 "passing") ||
3158 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3159 "passing"))
3160 return true;
3161
3162 break;
3163 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003164 }
3165
3166 case OR_No_Viable_Function:
3167 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003168 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003169 break;
3170
3171 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003172 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3173 << BinaryOperator::getOpcodeStr(Opc)
3174 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003175 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3176 return true;
3177 }
3178
Douglas Gregor70d26122008-11-12 17:17:38 +00003179 // Either we found no viable overloaded operator or we matched a
3180 // built-in operator. In either case, fall through to trying to
3181 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003182 }
Chris Lattner4b009652007-07-25 00:24:17 +00003183
Douglas Gregord7f915e2008-11-06 23:29:22 +00003184 // Build a built-in binary operation.
3185 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003186}
3187
3188// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003189Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3190 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003191 Expr *Input = (Expr*)input;
3192 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003193
3194 if (getLangOptions().CPlusPlus &&
3195 (Input->getType()->isRecordType()
3196 || Input->getType()->isEnumeralType())) {
3197 // Determine which overloaded operator we're dealing with.
3198 static const OverloadedOperatorKind OverOps[] = {
3199 OO_None, OO_None,
3200 OO_PlusPlus, OO_MinusMinus,
3201 OO_Amp, OO_Star,
3202 OO_Plus, OO_Minus,
3203 OO_Tilde, OO_Exclaim,
3204 OO_None, OO_None,
3205 OO_None,
3206 OO_None
3207 };
3208 OverloadedOperatorKind OverOp = OverOps[Opc];
3209
3210 // Add the appropriate overloaded operators (C++ [over.match.oper])
3211 // to the candidate set.
3212 OverloadCandidateSet CandidateSet;
3213 if (OverOp != OO_None)
3214 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3215
3216 // Perform overload resolution.
3217 OverloadCandidateSet::iterator Best;
3218 switch (BestViableFunction(CandidateSet, Best)) {
3219 case OR_Success: {
3220 // We found a built-in operator or an overloaded operator.
3221 FunctionDecl *FnDecl = Best->Function;
3222
3223 if (FnDecl) {
3224 // We matched an overloaded operator. Build a call to that
3225 // operator.
3226
3227 // Convert the arguments.
3228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3229 if (PerformObjectArgumentInitialization(Input, Method))
3230 return true;
3231 } else {
3232 // Convert the arguments.
3233 if (PerformCopyInitialization(Input,
3234 FnDecl->getParamDecl(0)->getType(),
3235 "passing"))
3236 return true;
3237 }
3238
3239 // Determine the result type
3240 QualType ResultTy
3241 = FnDecl->getType()->getAsFunctionType()->getResultType();
3242 ResultTy = ResultTy.getNonReferenceType();
3243
3244 // Build the actual expression node.
3245 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3246 SourceLocation());
3247 UsualUnaryConversions(FnExpr);
3248
3249 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3250 } else {
3251 // We matched a built-in operator. Convert the arguments, then
3252 // break out so that we will build the appropriate built-in
3253 // operator node.
3254 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3255 "passing"))
3256 return true;
3257
3258 break;
3259 }
3260 }
3261
3262 case OR_No_Viable_Function:
3263 // No viable function; fall through to handling this as a
3264 // built-in operator, which will produce an error message for us.
3265 break;
3266
3267 case OR_Ambiguous:
3268 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3269 << UnaryOperator::getOpcodeStr(Opc)
3270 << Input->getSourceRange();
3271 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3272 return true;
3273 }
3274
3275 // Either we found no viable overloaded operator or we matched a
3276 // built-in operator. In either case, fall through to trying to
3277 // build a built-in operation.
3278 }
3279
Chris Lattner4b009652007-07-25 00:24:17 +00003280 QualType resultType;
3281 switch (Opc) {
3282 default:
3283 assert(0 && "Unimplemented unary expr!");
3284 case UnaryOperator::PreInc:
3285 case UnaryOperator::PreDec:
3286 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3287 break;
3288 case UnaryOperator::AddrOf:
3289 resultType = CheckAddressOfOperand(Input, OpLoc);
3290 break;
3291 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003292 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003293 resultType = CheckIndirectionOperand(Input, OpLoc);
3294 break;
3295 case UnaryOperator::Plus:
3296 case UnaryOperator::Minus:
3297 UsualUnaryConversions(Input);
3298 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003299 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3300 break;
3301 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3302 resultType->isEnumeralType())
3303 break;
3304 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3305 Opc == UnaryOperator::Plus &&
3306 resultType->isPointerType())
3307 break;
3308
Chris Lattner77d52da2008-11-20 06:06:08 +00003309 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003310 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003311 case UnaryOperator::Not: // bitwise complement
3312 UsualUnaryConversions(Input);
3313 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003314 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3315 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3316 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003317 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003318 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003319 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003320 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003321 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003322 break;
3323 case UnaryOperator::LNot: // logical negation
3324 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3325 DefaultFunctionArrayConversion(Input);
3326 resultType = Input->getType();
3327 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003328 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003329 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003330 // LNot always has type int. C99 6.5.3.3p5.
3331 resultType = Context.IntTy;
3332 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003333 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003334 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003335 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003336 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003337 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003338 resultType = Input->getType();
3339 break;
3340 }
3341 if (resultType.isNull())
3342 return true;
3343 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3344}
3345
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003346/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3347Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003348 SourceLocation LabLoc,
3349 IdentifierInfo *LabelII) {
3350 // Look up the record for this label identifier.
3351 LabelStmt *&LabelDecl = LabelMap[LabelII];
3352
Daniel Dunbar879788d2008-08-04 16:51:22 +00003353 // If we haven't seen this label yet, create a forward reference. It
3354 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003355 if (LabelDecl == 0)
3356 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3357
3358 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003359 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3360 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003361}
3362
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003363Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003364 SourceLocation RPLoc) { // "({..})"
3365 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3366 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3367 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3368
3369 // FIXME: there are a variety of strange constraints to enforce here, for
3370 // example, it is not possible to goto into a stmt expression apparently.
3371 // More semantic analysis is needed.
3372
3373 // FIXME: the last statement in the compount stmt has its value used. We
3374 // should not warn about it being unused.
3375
3376 // If there are sub stmts in the compound stmt, take the type of the last one
3377 // as the type of the stmtexpr.
3378 QualType Ty = Context.VoidTy;
3379
Chris Lattner200964f2008-07-26 19:51:01 +00003380 if (!Compound->body_empty()) {
3381 Stmt *LastStmt = Compound->body_back();
3382 // If LastStmt is a label, skip down through into the body.
3383 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3384 LastStmt = Label->getSubStmt();
3385
3386 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003387 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003388 }
Chris Lattner4b009652007-07-25 00:24:17 +00003389
3390 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3391}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003392
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003393Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003394 SourceLocation TypeLoc,
3395 TypeTy *argty,
3396 OffsetOfComponent *CompPtr,
3397 unsigned NumComponents,
3398 SourceLocation RPLoc) {
3399 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3400 assert(!ArgTy.isNull() && "Missing type argument!");
3401
3402 // We must have at least one component that refers to the type, and the first
3403 // one is known to be a field designator. Verify that the ArgTy represents
3404 // a struct/union/class.
3405 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003406 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003407
3408 // Otherwise, create a compound literal expression as the base, and
3409 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003410 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003411
Chris Lattnerb37522e2007-08-31 21:49:13 +00003412 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3413 // GCC extension, diagnose them.
3414 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003415 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3416 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003417
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003418 for (unsigned i = 0; i != NumComponents; ++i) {
3419 const OffsetOfComponent &OC = CompPtr[i];
3420 if (OC.isBrackets) {
3421 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003422 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003423 if (!AT) {
3424 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003425 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003426 }
3427
Chris Lattner2af6a802007-08-30 17:59:59 +00003428 // FIXME: C++: Verify that operator[] isn't overloaded.
3429
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003430 // C99 6.5.2.1p1
3431 Expr *Idx = static_cast<Expr*>(OC.U.E);
3432 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003433 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3434 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003435
3436 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3437 continue;
3438 }
3439
3440 const RecordType *RC = Res->getType()->getAsRecordType();
3441 if (!RC) {
3442 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003443 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003444 }
3445
3446 // Get the decl corresponding to this.
3447 RecordDecl *RD = RC->getDecl();
3448 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3449 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003450 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3451 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003452
3453 // FIXME: C++: Verify that MemberDecl isn't a static field.
3454 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003455 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3456 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003457 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3458 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003459 }
3460
3461 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3462 BuiltinLoc);
3463}
3464
3465
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003466Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003467 TypeTy *arg1, TypeTy *arg2,
3468 SourceLocation RPLoc) {
3469 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3470 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3471
3472 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3473
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003474 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003475}
3476
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003477Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003478 ExprTy *expr1, ExprTy *expr2,
3479 SourceLocation RPLoc) {
3480 Expr *CondExpr = static_cast<Expr*>(cond);
3481 Expr *LHSExpr = static_cast<Expr*>(expr1);
3482 Expr *RHSExpr = static_cast<Expr*>(expr2);
3483
3484 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3485
3486 // The conditional expression is required to be a constant expression.
3487 llvm::APSInt condEval(32);
3488 SourceLocation ExpLoc;
3489 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003490 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3491 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003492
3493 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3494 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3495 RHSExpr->getType();
3496 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3497}
3498
Steve Naroff52a81c02008-09-03 18:15:37 +00003499//===----------------------------------------------------------------------===//
3500// Clang Extensions.
3501//===----------------------------------------------------------------------===//
3502
3503/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003504void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003505 // Analyze block parameters.
3506 BlockSemaInfo *BSI = new BlockSemaInfo();
3507
3508 // Add BSI to CurBlock.
3509 BSI->PrevBlockInfo = CurBlock;
3510 CurBlock = BSI;
3511
3512 BSI->ReturnType = 0;
3513 BSI->TheScope = BlockScope;
3514
Steve Naroff52059382008-10-10 01:28:17 +00003515 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3516 PushDeclContext(BSI->TheDecl);
3517}
3518
3519void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003520 // Analyze arguments to block.
3521 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3522 "Not a function declarator!");
3523 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3524
Steve Naroff52059382008-10-10 01:28:17 +00003525 CurBlock->hasPrototype = FTI.hasPrototype;
3526 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003527
3528 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3529 // no arguments, not a function that takes a single void argument.
3530 if (FTI.hasPrototype &&
3531 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3532 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3533 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3534 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003535 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003536 } else if (FTI.hasPrototype) {
3537 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003538 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3539 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003540 }
Steve Naroff52059382008-10-10 01:28:17 +00003541 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3542
3543 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3544 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3545 // If this has an identifier, add it to the scope stack.
3546 if ((*AI)->getIdentifier())
3547 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003548}
3549
3550/// ActOnBlockError - If there is an error parsing a block, this callback
3551/// is invoked to pop the information about the block from the action impl.
3552void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3553 // Ensure that CurBlock is deleted.
3554 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3555
3556 // Pop off CurBlock, handle nested blocks.
3557 CurBlock = CurBlock->PrevBlockInfo;
3558
3559 // FIXME: Delete the ParmVarDecl objects as well???
3560
3561}
3562
3563/// ActOnBlockStmtExpr - This is called when the body of a block statement
3564/// literal was successfully completed. ^(int x){...}
3565Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3566 Scope *CurScope) {
3567 // Ensure that CurBlock is deleted.
3568 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3569 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3570
Steve Naroff52059382008-10-10 01:28:17 +00003571 PopDeclContext();
3572
Steve Naroff52a81c02008-09-03 18:15:37 +00003573 // Pop off CurBlock, handle nested blocks.
3574 CurBlock = CurBlock->PrevBlockInfo;
3575
3576 QualType RetTy = Context.VoidTy;
3577 if (BSI->ReturnType)
3578 RetTy = QualType(BSI->ReturnType, 0);
3579
3580 llvm::SmallVector<QualType, 8> ArgTypes;
3581 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3582 ArgTypes.push_back(BSI->Params[i]->getType());
3583
3584 QualType BlockTy;
3585 if (!BSI->hasPrototype)
3586 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3587 else
3588 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003589 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003590
3591 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003592
Steve Naroff95029d92008-10-08 18:44:00 +00003593 BSI->TheDecl->setBody(Body.take());
3594 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003595}
3596
Nate Begemanbd881ef2008-01-30 20:50:20 +00003597/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003598/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003599/// The number of arguments has already been validated to match the number of
3600/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003601static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3602 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003603 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003604 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003605 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3606 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003607
3608 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003609 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003610 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003611 return true;
3612}
3613
3614Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3615 SourceLocation *CommaLocs,
3616 SourceLocation BuiltinLoc,
3617 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003618 // __builtin_overload requires at least 2 arguments
3619 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003620 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3621 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003622
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003623 // The first argument is required to be a constant expression. It tells us
3624 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003625 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003626 Expr *NParamsExpr = Args[0];
3627 llvm::APSInt constEval(32);
3628 SourceLocation ExpLoc;
3629 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003630 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3631 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003632
3633 // Verify that the number of parameters is > 0
3634 unsigned NumParams = constEval.getZExtValue();
3635 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003636 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3637 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003638 // Verify that we have at least 1 + NumParams arguments to the builtin.
3639 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003640 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3641 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003642
3643 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003644 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003645 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003646 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3647 // UsualUnaryConversions will convert the function DeclRefExpr into a
3648 // pointer to function.
3649 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003650 const FunctionTypeProto *FnType = 0;
3651 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3652 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003653
3654 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3655 // parameters, and the number of parameters must match the value passed to
3656 // the builtin.
3657 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003658 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3659 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003660
3661 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003662 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003663 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003664 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003665 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003666 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3667 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003668 // Remember our match, and continue processing the remaining arguments
3669 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003670 OE = new OverloadExpr(Args, NumArgs, i,
3671 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003672 BuiltinLoc, RParenLoc);
3673 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003674 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003675 // Return the newly created OverloadExpr node, if we succeded in matching
3676 // exactly one of the candidate functions.
3677 if (OE)
3678 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003679
3680 // If we didn't find a matching function Expr in the __builtin_overload list
3681 // the return an error.
3682 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003683 for (unsigned i = 0; i != NumParams; ++i) {
3684 if (i != 0) typeNames += ", ";
3685 typeNames += Args[i+1]->getType().getAsString();
3686 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003687
Chris Lattner77d52da2008-11-20 06:06:08 +00003688 return Diag(BuiltinLoc, diag::err_overload_no_match)
3689 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003690}
3691
Anders Carlsson36760332007-10-15 20:28:48 +00003692Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3693 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003694 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003695 Expr *E = static_cast<Expr*>(expr);
3696 QualType T = QualType::getFromOpaquePtr(type);
3697
3698 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003699
3700 // Get the va_list type
3701 QualType VaListType = Context.getBuiltinVaListType();
3702 // Deal with implicit array decay; for example, on x86-64,
3703 // va_list is an array, but it's supposed to decay to
3704 // a pointer for va_arg.
3705 if (VaListType->isArrayType())
3706 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003707 // Make sure the input expression also decays appropriately.
3708 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003709
3710 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003711 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003712 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003713 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003714
3715 // FIXME: Warn if a non-POD type is passed in.
3716
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003717 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003718}
3719
Douglas Gregorad4b3792008-11-29 04:51:27 +00003720Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3721 // The type of __null will be int or long, depending on the size of
3722 // pointers on the target.
3723 QualType Ty;
3724 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3725 Ty = Context.IntTy;
3726 else
3727 Ty = Context.LongTy;
3728
3729 return new GNUNullExpr(Ty, TokenLoc);
3730}
3731
Chris Lattner005ed752008-01-04 18:04:52 +00003732bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3733 SourceLocation Loc,
3734 QualType DstType, QualType SrcType,
3735 Expr *SrcExpr, const char *Flavor) {
3736 // Decode the result (notice that AST's are still created for extensions).
3737 bool isInvalid = false;
3738 unsigned DiagKind;
3739 switch (ConvTy) {
3740 default: assert(0 && "Unknown conversion type");
3741 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003742 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003743 DiagKind = diag::ext_typecheck_convert_pointer_int;
3744 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003745 case IntToPointer:
3746 DiagKind = diag::ext_typecheck_convert_int_pointer;
3747 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003748 case IncompatiblePointer:
3749 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3750 break;
3751 case FunctionVoidPointer:
3752 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3753 break;
3754 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003755 // If the qualifiers lost were because we were applying the
3756 // (deprecated) C++ conversion from a string literal to a char*
3757 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3758 // Ideally, this check would be performed in
3759 // CheckPointerTypesForAssignment. However, that would require a
3760 // bit of refactoring (so that the second argument is an
3761 // expression, rather than a type), which should be done as part
3762 // of a larger effort to fix CheckPointerTypesForAssignment for
3763 // C++ semantics.
3764 if (getLangOptions().CPlusPlus &&
3765 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3766 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003767 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3768 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003769 case IntToBlockPointer:
3770 DiagKind = diag::err_int_to_block_pointer;
3771 break;
3772 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003773 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003774 break;
Steve Naroff19608432008-10-14 22:18:38 +00003775 case IncompatibleObjCQualifiedId:
3776 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3777 // it can give a more specific diagnostic.
3778 DiagKind = diag::warn_incompatible_qualified_id;
3779 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003780 case Incompatible:
3781 DiagKind = diag::err_typecheck_convert_incompatible;
3782 isInvalid = true;
3783 break;
3784 }
3785
Chris Lattner271d4c22008-11-24 05:29:24 +00003786 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3787 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003788 return isInvalid;
3789}
Anders Carlssond5201b92008-11-30 19:50:32 +00003790
3791bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3792{
3793 Expr::EvalResult EvalResult;
3794
3795 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3796 EvalResult.HasSideEffects) {
3797 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3798
3799 if (EvalResult.Diag) {
3800 // We only show the note if it's not the usual "invalid subexpression"
3801 // or if it's actually in a subexpression.
3802 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3803 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3804 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3805 }
3806
3807 return true;
3808 }
3809
3810 if (EvalResult.Diag) {
3811 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3812 E->getSourceRange();
3813
3814 // Print the reason it's not a constant.
3815 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3816 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3817 }
3818
3819 if (Result)
3820 *Result = EvalResult.Val.getInt();
3821 return false;
3822}