blob: 264b85b69cb2c82b67276a75811c3406d6f23b63 [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.
Anders Carlsson488a0792008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Naroff87d58b42007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000296
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Chris Lattner4b009652007-07-25 00:24:17 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff0acc9c92007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
361/// ActOnDeclarationNameExpr - The parser has read some kind of name
362/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
363/// performs lookup on that name and returns an expression that refers
364/// to that name. This routine isn't directly called from the parser,
365/// because the parser doesn't know about DeclarationName. Rather,
366/// this routine is called by ActOnIdentifierExpr,
367/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
368/// which form the DeclarationName from the corresponding syntactic
369/// forms.
370///
371/// HasTrailingLParen indicates whether this identifier is used in a
372/// function call context. LookupCtx is only used for a C++
373/// qualified-id (foo::bar) to indicate the class or namespace that
374/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000375///
376/// If ForceResolution is true, then we will attempt to resolve the
377/// name even if it looks like a dependent name. This option is off by
378/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000379Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
380 DeclarationName Name,
381 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000382 const CXXScopeSpec *SS,
383 bool ForceResolution) {
384 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
385 HasTrailingLParen && !SS && !ForceResolution) {
386 // We've seen something of the form
387 // identifier(
388 // and we are in a template, so it is likely that 's' is a
389 // dependent name. However, we won't know until we've parsed all
390 // of the call arguments. So, build a CXXDependentNameExpr node
391 // to represent this name. Then, if it turns out that none of the
392 // arguments are type-dependent, we'll force the resolution of the
393 // dependent name at that point.
394 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
395 Context.DependentTy, Loc);
396 }
397
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000398 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000399 Decl *D;
400 if (SS && !SS->isEmpty()) {
401 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
402 if (DC == 0)
403 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000404 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000405 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000406 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000407
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408 // If this reference is in an Objective-C method, then ivar lookup happens as
409 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000410 IdentifierInfo *II = Name.getAsIdentifierInfo();
411 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000412 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 // There are two cases to handle here. 1) scoped lookup could have failed,
414 // in which case we should look for an ivar. 2) scoped lookup could have
415 // found a decl, but that decl is outside the current method (i.e. a global
416 // variable). In these two cases, we do a lookup for an ivar with this
417 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000418 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000419 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000421 // FIXME: This should use a new expr for a direct reference, don't turn
422 // this into Self->ivar, just return a BareIVarExpr or something.
423 IdentifierInfo &II = Context.Idents.get("self");
424 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
425 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
426 static_cast<Expr*>(SelfExpr.Val), true, true);
427 }
428 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000429 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000430 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000431 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000432 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000433 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000434 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000435 }
Chris Lattner4b009652007-07-25 00:24:17 +0000436 if (D == 0) {
437 // Otherwise, this could be an implicitly declared function reference (legal
438 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000439 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000440 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000441 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000442 else {
443 // If this name wasn't predeclared and if this is not a function call,
444 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000445 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000446 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000447 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000448 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
449 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000450 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000451 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000452 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000453 }
454 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000455
Douglas Gregor8acb7272008-12-11 16:49:14 +0000456 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000457 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
458 if (MD->isStatic())
459 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000460 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000461 << FD->getDeclName();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000462 if (MD->getParent() != FD->getDeclContext())
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000463 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000464 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000465 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000466
467 if (FD->isInvalidDecl())
468 return true;
469
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000470 // FIXME: Handle 'mutable'.
471 return new DeclRefExpr(FD,
472 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000473 }
474
Chris Lattner271d4c22008-11-24 05:29:24 +0000475 return Diag(Loc, diag::err_invalid_non_static_member_use)
476 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000477 }
Chris Lattner4b009652007-07-25 00:24:17 +0000478 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000479 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000480 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000481 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000482 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000483 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000484
Steve Naroffd6163f32008-09-05 22:11:13 +0000485 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000486 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
487 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
488
Steve Naroffd6163f32008-09-05 22:11:13 +0000489 ValueDecl *VD = cast<ValueDecl>(D);
490
491 // check if referencing an identifier with __attribute__((deprecated)).
492 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000493 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000494
495 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
496 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
497 Scope *CheckS = S;
498 while (CheckS) {
499 if (CheckS->isWithinElse() &&
500 CheckS->getControlParent()->isDeclScope(Var)) {
501 if (Var->getType()->isBooleanType())
502 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
503 else
504 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
505 break;
506 }
507
508 // Move up one more control parent to check again.
509 CheckS = CheckS->getControlParent();
510 if (CheckS)
511 CheckS = CheckS->getParent();
512 }
513 }
514 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000515
516 // Only create DeclRefExpr's for valid Decl's.
517 if (VD->isInvalidDecl())
518 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000519
520 // If the identifier reference is inside a block, and it refers to a value
521 // that is outside the block, create a BlockDeclRefExpr instead of a
522 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
523 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000524 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000525 // We do not do this for things like enum constants, global variables, etc,
526 // as they do not get snapshotted.
527 //
528 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000529 // The BlocksAttr indicates the variable is bound by-reference.
530 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000531 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
532 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000533
534 // Variable will be bound by-copy, make it const within the closure.
535 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000536 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
537 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000538 }
539 // If this reference is not in a block or if the referenced variable is
540 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000541
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000542 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000543 bool ValueDependent = false;
544 if (getLangOptions().CPlusPlus) {
545 // C++ [temp.dep.expr]p3:
546 // An id-expression is type-dependent if it contains:
547 // - an identifier that was declared with a dependent type,
548 if (VD->getType()->isDependentType())
549 TypeDependent = true;
550 // - FIXME: a template-id that is dependent,
551 // - a conversion-function-id that specifies a dependent type,
552 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
553 Name.getCXXNameType()->isDependentType())
554 TypeDependent = true;
555 // - a nested-name-specifier that contains a class-name that
556 // names a dependent type.
557 else if (SS && !SS->isEmpty()) {
558 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
559 DC; DC = DC->getParent()) {
560 // FIXME: could stop early at namespace scope.
561 if (DC->isCXXRecord()) {
562 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
563 if (Context.getTypeDeclType(Record)->isDependentType()) {
564 TypeDependent = true;
565 break;
566 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000567 }
568 }
569 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000570
Douglas Gregora5d84612008-12-10 20:57:37 +0000571 // C++ [temp.dep.constexpr]p2:
572 //
573 // An identifier is value-dependent if it is:
574 // - a name declared with a dependent type,
575 if (TypeDependent)
576 ValueDependent = true;
577 // - the name of a non-type template parameter,
578 else if (isa<NonTypeTemplateParmDecl>(VD))
579 ValueDependent = true;
580 // - a constant with integral or enumeration type and is
581 // initialized with an expression that is value-dependent
582 // (FIXME!).
583 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000584
585 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
586 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000587}
588
Chris Lattner69909292008-08-10 01:53:14 +0000589Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000590 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000591 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000592
593 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000594 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000595 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
596 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
597 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000599
Chris Lattner7e637512008-01-12 08:14:25 +0000600 // Pre-defined identifiers are of type char[x], where x is the length of the
601 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000602 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000603 if (FunctionDecl *FD = getCurFunctionDecl())
604 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000605 else if (ObjCMethodDecl *MD = getCurMethodDecl())
606 Length = MD->getSynthesizedMethodSize();
607 else {
608 Diag(Loc, diag::ext_predef_outside_function);
609 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
610 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
611 }
612
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000613
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000614 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000615 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000616 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000617 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000618}
619
Steve Naroff87d58b42007-09-16 03:34:24 +0000620Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000621 llvm::SmallString<16> CharBuffer;
622 CharBuffer.resize(Tok.getLength());
623 const char *ThisTokBegin = &CharBuffer[0];
624 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
625
626 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
627 Tok.getLocation(), PP);
628 if (Literal.hadError())
629 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000630
631 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
632
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000633 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
634 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000635}
636
Steve Naroff87d58b42007-09-16 03:34:24 +0000637Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000638 // fast path for a single digit (which is quite common). A single digit
639 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
640 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000641 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000642
Chris Lattner8cd0e932008-03-05 18:54:05 +0000643 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000644 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000645 Context.IntTy,
646 Tok.getLocation()));
647 }
648 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000649 // Add padding so that NumericLiteralParser can overread by one character.
650 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000651 const char *ThisTokBegin = &IntegerBuffer[0];
652
653 // Get the spelling of the token, which eliminates trigraphs, etc.
654 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000655
Chris Lattner4b009652007-07-25 00:24:17 +0000656 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
657 Tok.getLocation(), PP);
658 if (Literal.hadError)
659 return ExprResult(true);
660
Chris Lattner1de66eb2007-08-26 03:42:43 +0000661 Expr *Res;
662
663 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000664 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000665 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000666 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000667 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000668 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000669 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000670 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000671
672 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
673
Ted Kremenekddedbe22007-11-29 00:56:49 +0000674 // isExact will be set by GetFloatValue().
675 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000676 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000677 Ty, Tok.getLocation());
678
Chris Lattner1de66eb2007-08-26 03:42:43 +0000679 } else if (!Literal.isIntegerLiteral()) {
680 return ExprResult(true);
681 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000682 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000683
Neil Booth7421e9c2007-08-29 22:00:19 +0000684 // long long is a C99 feature.
685 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000686 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000687 Diag(Tok.getLocation(), diag::ext_longlong);
688
Chris Lattner4b009652007-07-25 00:24:17 +0000689 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000690 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000691
692 if (Literal.GetIntegerValue(ResultVal)) {
693 // If this value didn't fit into uintmax_t, warn and force to ull.
694 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000695 Ty = Context.UnsignedLongLongTy;
696 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000697 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000698 } else {
699 // If this value fits into a ULL, try to figure out what else it fits into
700 // according to the rules of C99 6.4.4.1p5.
701
702 // Octal, Hexadecimal, and integers with a U suffix are allowed to
703 // be an unsigned int.
704 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
705
706 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000707 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000708 if (!Literal.isLong && !Literal.isLongLong) {
709 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000710 unsigned IntSize = Context.Target.getIntWidth();
711
Chris Lattner4b009652007-07-25 00:24:17 +0000712 // Does it fit in a unsigned int?
713 if (ResultVal.isIntN(IntSize)) {
714 // Does it fit in a signed int?
715 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000716 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000717 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000718 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000719 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000720 }
Chris Lattner4b009652007-07-25 00:24:17 +0000721 }
722
723 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000724 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000725 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000726
727 // Does it fit in a unsigned long?
728 if (ResultVal.isIntN(LongSize)) {
729 // Does it fit in a signed long?
730 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000731 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000732 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000733 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000734 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000735 }
Chris Lattner4b009652007-07-25 00:24:17 +0000736 }
737
738 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000739 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000740 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000741
742 // Does it fit in a unsigned long long?
743 if (ResultVal.isIntN(LongLongSize)) {
744 // Does it fit in a signed long long?
745 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000746 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000747 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000748 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000749 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000750 }
751 }
752
753 // If we still couldn't decide a type, we probably have something that
754 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000755 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000756 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000757 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000758 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000759 }
Chris Lattnere4068872008-05-09 05:59:00 +0000760
761 if (ResultVal.getBitWidth() != Width)
762 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000763 }
764
Chris Lattner48d7f382008-04-02 04:24:33 +0000765 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000766 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000767
768 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
769 if (Literal.isImaginary)
770 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
771
772 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000773}
774
Steve Naroff87d58b42007-09-16 03:34:24 +0000775Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000776 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000777 Expr *E = (Expr *)Val;
778 assert((E != 0) && "ActOnParenExpr() missing expr");
779 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000780}
781
782/// The UsualUnaryConversions() function is *not* called by this routine.
783/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000784bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
785 SourceLocation OpLoc,
786 const SourceRange &ExprRange,
787 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000788 // C99 6.5.3.4p1:
789 if (isa<FunctionType>(exprType) && isSizeof)
790 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000791 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000792 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000793 Diag(OpLoc, diag::ext_sizeof_void_type)
794 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
795 else if (exprType->isIncompleteType())
796 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
797 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000798 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000799
800 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000801}
802
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000803/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
804/// the same for @c alignof and @c __alignof
805/// Note that the ArgRange is invalid if isType is false.
806Action::ExprResult
807Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
808 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000809 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000810 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000811
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000812 QualType ArgTy;
813 SourceRange Range;
814 if (isType) {
815 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
816 Range = ArgRange;
817 } else {
818 // Get the end location.
819 Expr *ArgEx = (Expr *)TyOrEx;
820 Range = ArgEx->getSourceRange();
821 ArgTy = ArgEx->getType();
822 }
823
824 // Verify that the operand is valid.
825 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000826 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000827
828 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
829 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
830 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000831}
832
Chris Lattner5110ad52007-08-24 21:41:10 +0000833QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000834 DefaultFunctionArrayConversion(V);
835
Chris Lattnera16e42d2007-08-26 05:39:26 +0000836 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000837 if (const ComplexType *CT = V->getType()->getAsComplexType())
838 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000839
840 // Otherwise they pass through real integer and floating point types here.
841 if (V->getType()->isArithmeticType())
842 return V->getType();
843
844 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000845 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000846 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000847}
848
849
Chris Lattner4b009652007-07-25 00:24:17 +0000850
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000851Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000852 tok::TokenKind Kind,
853 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000854 Expr *Arg = (Expr *)Input;
855
Chris Lattner4b009652007-07-25 00:24:17 +0000856 UnaryOperator::Opcode Opc;
857 switch (Kind) {
858 default: assert(0 && "Unknown unary op!");
859 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
860 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
861 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000862
863 if (getLangOptions().CPlusPlus &&
864 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
865 // Which overloaded operator?
866 OverloadedOperatorKind OverOp =
867 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
868
869 // C++ [over.inc]p1:
870 //
871 // [...] If the function is a member function with one
872 // parameter (which shall be of type int) or a non-member
873 // function with two parameters (the second of which shall be
874 // of type int), it defines the postfix increment operator ++
875 // for objects of that type. When the postfix increment is
876 // called as a result of using the ++ operator, the int
877 // argument will have value zero.
878 Expr *Args[2] = {
879 Arg,
880 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
881 /*isSigned=*/true),
882 Context.IntTy, SourceLocation())
883 };
884
885 // Build the candidate set for overloading
886 OverloadCandidateSet CandidateSet;
887 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
888
889 // Perform overload resolution.
890 OverloadCandidateSet::iterator Best;
891 switch (BestViableFunction(CandidateSet, Best)) {
892 case OR_Success: {
893 // We found a built-in operator or an overloaded operator.
894 FunctionDecl *FnDecl = Best->Function;
895
896 if (FnDecl) {
897 // We matched an overloaded operator. Build a call to that
898 // operator.
899
900 // Convert the arguments.
901 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
902 if (PerformObjectArgumentInitialization(Arg, Method))
903 return true;
904 } else {
905 // Convert the arguments.
906 if (PerformCopyInitialization(Arg,
907 FnDecl->getParamDecl(0)->getType(),
908 "passing"))
909 return true;
910 }
911
912 // Determine the result type
913 QualType ResultTy
914 = FnDecl->getType()->getAsFunctionType()->getResultType();
915 ResultTy = ResultTy.getNonReferenceType();
916
917 // Build the actual expression node.
918 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
919 SourceLocation());
920 UsualUnaryConversions(FnExpr);
921
922 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
923 } else {
924 // We matched a built-in operator. Convert the arguments, then
925 // break out so that we will build the appropriate built-in
926 // operator node.
927 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
928 "passing"))
929 return true;
930
931 break;
932 }
933 }
934
935 case OR_No_Viable_Function:
936 // No viable function; fall through to handling this as a
937 // built-in operator, which will produce an error message for us.
938 break;
939
940 case OR_Ambiguous:
941 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
942 << UnaryOperator::getOpcodeStr(Opc)
943 << Arg->getSourceRange();
944 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
945 return true;
946 }
947
948 // Either we found no viable overloaded operator or we matched a
949 // built-in operator. In either case, fall through to trying to
950 // build a built-in operation.
951 }
952
953 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000954 if (result.isNull())
955 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000956 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000957}
958
959Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000960ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000961 ExprTy *Idx, SourceLocation RLoc) {
962 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
963
Douglas Gregor80723c52008-11-19 17:17:41 +0000964 if (getLangOptions().CPlusPlus &&
965 LHSExp->getType()->isRecordType() ||
966 LHSExp->getType()->isEnumeralType() ||
967 RHSExp->getType()->isRecordType() ||
Sebastian Redle5edfce2008-12-03 16:32:40 +0000968 RHSExp->getType()->isEnumeralType()) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000969 // Add the appropriate overloaded operators (C++ [over.match.oper])
970 // to the candidate set.
971 OverloadCandidateSet CandidateSet;
972 Expr *Args[2] = { LHSExp, RHSExp };
973 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
974
975 // Perform overload resolution.
976 OverloadCandidateSet::iterator Best;
977 switch (BestViableFunction(CandidateSet, Best)) {
978 case OR_Success: {
979 // We found a built-in operator or an overloaded operator.
980 FunctionDecl *FnDecl = Best->Function;
981
982 if (FnDecl) {
983 // We matched an overloaded operator. Build a call to that
984 // operator.
985
986 // Convert the arguments.
987 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
988 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
989 PerformCopyInitialization(RHSExp,
990 FnDecl->getParamDecl(0)->getType(),
991 "passing"))
992 return true;
993 } else {
994 // Convert the arguments.
995 if (PerformCopyInitialization(LHSExp,
996 FnDecl->getParamDecl(0)->getType(),
997 "passing") ||
998 PerformCopyInitialization(RHSExp,
999 FnDecl->getParamDecl(1)->getType(),
1000 "passing"))
1001 return true;
1002 }
1003
1004 // Determine the result type
1005 QualType ResultTy
1006 = FnDecl->getType()->getAsFunctionType()->getResultType();
1007 ResultTy = ResultTy.getNonReferenceType();
1008
1009 // Build the actual expression node.
1010 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1011 SourceLocation());
1012 UsualUnaryConversions(FnExpr);
1013
1014 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1015 } else {
1016 // We matched a built-in operator. Convert the arguments, then
1017 // break out so that we will build the appropriate built-in
1018 // operator node.
1019 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1020 "passing") ||
1021 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1022 "passing"))
1023 return true;
1024
1025 break;
1026 }
1027 }
1028
1029 case OR_No_Viable_Function:
1030 // No viable function; fall through to handling this as a
1031 // built-in operator, which will produce an error message for us.
1032 break;
1033
1034 case OR_Ambiguous:
1035 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1036 << "[]"
1037 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1038 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1039 return true;
1040 }
1041
1042 // Either we found no viable overloaded operator or we matched a
1043 // built-in operator. In either case, fall through to trying to
1044 // build a built-in operation.
1045 }
1046
Chris Lattner4b009652007-07-25 00:24:17 +00001047 // Perform default conversions.
1048 DefaultFunctionArrayConversion(LHSExp);
1049 DefaultFunctionArrayConversion(RHSExp);
1050
1051 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1052
1053 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001054 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001055 // in the subscript position. As a result, we need to derive the array base
1056 // and index from the expression types.
1057 Expr *BaseExpr, *IndexExpr;
1058 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001059 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001060 BaseExpr = LHSExp;
1061 IndexExpr = RHSExp;
1062 // FIXME: need to deal with const...
1063 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001064 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001065 // Handle the uncommon case of "123[Ptr]".
1066 BaseExpr = RHSExp;
1067 IndexExpr = LHSExp;
1068 // FIXME: need to deal with const...
1069 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001070 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1071 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001072 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001073
1074 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001075 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1076 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001077 return Diag(LLoc, diag::err_ext_vector_component_access)
1078 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001079 // FIXME: need to deal with const...
1080 ResultType = VTy->getElementType();
1081 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001082 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1083 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001084 }
1085 // C99 6.5.2.1p1
1086 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001087 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1088 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001089
1090 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1091 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001092 // void (*)(int)) and pointers to incomplete types. Functions are not
1093 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001094 if (!ResultType->isObjectType())
1095 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001096 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001097 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001098
1099 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1100}
1101
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001102QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001103CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001104 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001105 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001106
1107 // This flag determines whether or not the component is to be treated as a
1108 // special name, or a regular GLSL-style component access.
1109 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001110
1111 // The vector accessor can't exceed the number of elements.
1112 const char *compStr = CompName.getName();
1113 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001114 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001115 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001116 return QualType();
1117 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001118
1119 // Check that we've found one of the special components, or that the component
1120 // names must come from the same set.
1121 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1122 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1123 SpecialComponent = true;
1124 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001125 do
1126 compStr++;
1127 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1128 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1129 do
1130 compStr++;
1131 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1132 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1133 do
1134 compStr++;
1135 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1136 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001137
Nate Begemanc8e51f82008-05-09 06:41:27 +00001138 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001139 // We didn't get to the end of the string. This means the component names
1140 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001141 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1142 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001143 return QualType();
1144 }
1145 // Each component accessor can't exceed the vector type.
1146 compStr = CompName.getName();
1147 while (*compStr) {
1148 if (vecType->isAccessorWithinNumElements(*compStr))
1149 compStr++;
1150 else
1151 break;
1152 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001153 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001154 // We didn't get to the end of the string. This means a component accessor
1155 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001156 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001157 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001158 return QualType();
1159 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001160
1161 // If we have a special component name, verify that the current vector length
1162 // is an even number, since all special component names return exactly half
1163 // the elements.
1164 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001165 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001166 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001167 return QualType();
1168 }
1169
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001170 // The component accessor looks fine - now we need to compute the actual type.
1171 // The vector type is implied by the component accessor. For example,
1172 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001173 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1174 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001175 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001176 if (CompSize == 1)
1177 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001178
Nate Begemanaf6ed502008-04-18 23:10:10 +00001179 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001180 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001181 // diagostics look bad. We want extended vector types to appear built-in.
1182 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1183 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1184 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001185 }
1186 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001187}
1188
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001189/// constructSetterName - Return the setter name for the given
1190/// identifier, i.e. "set" + Name where the initial character of Name
1191/// has been capitalized.
1192// FIXME: Merge with same routine in Parser. But where should this
1193// live?
1194static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1195 const IdentifierInfo *Name) {
1196 llvm::SmallString<100> SelectorName;
1197 SelectorName = "set";
1198 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1199 SelectorName[3] = toupper(SelectorName[3]);
1200 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1201}
1202
Chris Lattner4b009652007-07-25 00:24:17 +00001203Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001204ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001205 tok::TokenKind OpKind, SourceLocation MemberLoc,
1206 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001207 Expr *BaseExpr = static_cast<Expr *>(Base);
1208 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001209
1210 // Perform default conversions.
1211 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001212
Steve Naroff2cb66382007-07-26 03:11:44 +00001213 QualType BaseType = BaseExpr->getType();
1214 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001215
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001216 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1217 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001218 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001219 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001220 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001221 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1222 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001223 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001224 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001225 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001226 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001227
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001228 // Handle field access to simple records. This also handles access to fields
1229 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001230 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001231 RecordDecl *RDecl = RTy->getDecl();
1232 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001233 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001234 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001235 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001236 // FIXME: Qualified name lookup for C++ is a bit more complicated
1237 // than this.
1238 DeclContext::lookup_result Lookup = RDecl->lookup(Context, &Member);
1239 if (Lookup.first == Lookup.second) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001240 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001241 << &Member << BaseExpr->getSourceRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001242 }
1243
1244 FieldDecl *MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
1245 if (!MemberDecl) {
1246 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
1247 "Clang only supports references to members");
1248 return Diag(MemberLoc, DiagID);
1249 }
Eli Friedman76b49832008-02-06 22:48:16 +00001250
1251 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001252 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001253 QualType MemberType = MemberDecl->getType();
1254 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001255 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001256 if (MemberDecl->isMutable())
1257 combinedQualifiers &= ~QualType::Const;
Eli Friedman76b49832008-02-06 22:48:16 +00001258 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1259
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001260 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001261 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001262 }
1263
Chris Lattnere9d71612008-07-21 04:59:05 +00001264 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1265 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001266 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1267 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001268 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001269 OpKind == tok::arrow);
Chris Lattner8ba580c2008-11-19 05:08:23 +00001270 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001271 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001272 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001273 }
1274
Chris Lattnere9d71612008-07-21 04:59:05 +00001275 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1276 // pointer to a (potentially qualified) interface type.
1277 const PointerType *PTy;
1278 const ObjCInterfaceType *IFTy;
1279 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1280 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1281 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001282
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001283 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001284 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1285 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1286
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001287 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001288 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1289 E = IFTy->qual_end(); I != E; ++I)
1290 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1291 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001292
1293 // If that failed, look for an "implicit" property by seeing if the nullary
1294 // selector is implemented.
1295
1296 // FIXME: The logic for looking up nullary and unary selectors should be
1297 // shared with the code in ActOnInstanceMessage.
1298
1299 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1300 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1301
1302 // If this reference is in an @implementation, check for 'private' methods.
1303 if (!Getter)
1304 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1305 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1306 if (ObjCImplementationDecl *ImpDecl =
1307 ObjCImplementations[ClassDecl->getIdentifier()])
1308 Getter = ImpDecl->getInstanceMethod(Sel);
1309
Steve Naroff04151f32008-10-22 19:16:27 +00001310 // Look through local category implementations associated with the class.
1311 if (!Getter) {
1312 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1313 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1314 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1315 }
1316 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001317 if (Getter) {
1318 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001319 // will look for the matching setter, in case it is needed.
1320 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1321 &Member);
1322 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1323 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1324 if (!Setter) {
1325 // If this reference is in an @implementation, also check for 'private'
1326 // methods.
1327 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1328 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1329 if (ObjCImplementationDecl *ImpDecl =
1330 ObjCImplementations[ClassDecl->getIdentifier()])
1331 Setter = ImpDecl->getInstanceMethod(SetterSel);
1332 }
1333 // Look through local category implementations associated with the class.
1334 if (!Setter) {
1335 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1336 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1337 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1338 }
1339 }
1340
1341 // FIXME: we must check that the setter has property type.
1342 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001343 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001344 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001345 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001346 // Handle properties on qualified "id" protocols.
1347 const ObjCQualifiedIdType *QIdTy;
1348 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1349 // Check protocols on qualified interfaces.
1350 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001351 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001352 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1353 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001354 // Also must look for a getter name which uses property syntax.
1355 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1356 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1357 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1358 OpLoc, MemberLoc, NULL, 0);
1359 }
1360 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001361 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001362 // Handle 'field access' to vectors, such as 'V.xx'.
1363 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1364 // Component access limited to variables (reject vec4.rg.g).
1365 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1366 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001367 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1368 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001369 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1370 if (ret.isNull())
1371 return true;
1372 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1373 }
1374
Chris Lattner8ba580c2008-11-19 05:08:23 +00001375 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001376 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001377}
1378
Steve Naroff87d58b42007-09-16 03:34:24 +00001379/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001380/// This provides the location of the left/right parens and a list of comma
1381/// locations.
1382Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001383ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001384 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001385 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1386 Expr *Fn = static_cast<Expr *>(fn);
1387 Expr **Args = reinterpret_cast<Expr**>(args);
1388 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001389 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001390 OverloadedFunctionDecl *Ovl = NULL;
1391
Douglas Gregora133e262008-12-06 00:22:45 +00001392 // Determine whether this is a dependent call inside a C++ template,
1393 // in which case we won't do any semantic analysis now.
1394 bool Dependent = false;
1395 if (Fn->isTypeDependent()) {
1396 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1397 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1398 Dependent = true;
1399 else {
1400 // Resolve the CXXDependentNameExpr to an actual identifier;
1401 // it wasn't really a dependent name after all.
1402 ExprResult Resolved
1403 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1404 /*HasTrailingLParen=*/true,
1405 /*SS=*/0,
1406 /*ForceResolution=*/true);
1407 if (Resolved.isInvalid)
1408 return true;
1409 else {
1410 delete Fn;
1411 Fn = (Expr *)Resolved.Val;
1412 }
1413 }
1414 } else
1415 Dependent = true;
1416 } else
1417 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1418
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001419 // FIXME: Will need to cache the results of name lookup (including
1420 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001421 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001422 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1423
Douglas Gregord2baafd2008-10-21 16:13:35 +00001424 // If we're directly calling a function or a set of overloaded
1425 // functions, get the appropriate declaration.
1426 {
1427 DeclRefExpr *DRExpr = NULL;
1428 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1429 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1430 else
1431 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1432
1433 if (DRExpr) {
1434 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1435 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1436 }
1437 }
1438
Douglas Gregord2baafd2008-10-21 16:13:35 +00001439 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001440 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1441 RParenLoc);
1442 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001443 return true;
1444
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001445 // Update Fn to refer to the actual function selected.
1446 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1447 Fn->getSourceRange().getBegin());
1448 Fn->Destroy(Context);
1449 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001450 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001451
Douglas Gregor10f3c502008-11-19 21:05:33 +00001452 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001453 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001454 CommaLocs, RParenLoc);
1455
Chris Lattner3e254fb2008-04-08 04:40:51 +00001456 // Promote the function operand.
1457 UsualUnaryConversions(Fn);
1458
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001459 // Make the call expr early, before semantic checks. This guarantees cleanup
1460 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001461 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001462 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001463
Steve Naroffd6163f32008-09-05 22:11:13 +00001464 const FunctionType *FuncT;
1465 if (!Fn->getType()->isBlockPointerType()) {
1466 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1467 // have type pointer to function".
1468 const PointerType *PT = Fn->getType()->getAsPointerType();
1469 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001470 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001471 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001472 FuncT = PT->getPointeeType()->getAsFunctionType();
1473 } else { // This is a block call.
1474 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1475 getAsFunctionType();
1476 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001477 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001478 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001479 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001480
1481 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001482 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001483
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001484 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001485 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1486 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001487 unsigned NumArgsInProto = Proto->getNumArgs();
1488 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001489
Chris Lattner3e254fb2008-04-08 04:40:51 +00001490 // If too few arguments are available (and we don't have default
1491 // arguments for the remaining parameters), don't make the call.
1492 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001493 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1494 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1495 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1496 // Use default arguments for missing arguments
1497 NumArgsToCheck = NumArgsInProto;
1498 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001499 }
1500
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001501 // If too many are passed and not variadic, error on the extras and drop
1502 // them.
1503 if (NumArgs > NumArgsInProto) {
1504 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001505 Diag(Args[NumArgsInProto]->getLocStart(),
1506 diag::err_typecheck_call_too_many_args)
1507 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001508 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1509 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001510 // This deletes the extra arguments.
1511 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001512 }
1513 NumArgsToCheck = NumArgsInProto;
1514 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001515
Chris Lattner4b009652007-07-25 00:24:17 +00001516 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001517 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001518 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001519
1520 Expr *Arg;
1521 if (i < NumArgs)
1522 Arg = Args[i];
1523 else
1524 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001525 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001526
Douglas Gregor81c29152008-10-29 00:13:59 +00001527 // Pass the argument.
1528 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001529 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001530
1531 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001532 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001533
1534 // If this is a variadic call, handle args passed through "...".
1535 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001536 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001537 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1538 Expr *Arg = Args[i];
1539 DefaultArgumentPromotion(Arg);
1540 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001541 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001542 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001543 } else {
1544 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1545
Steve Naroffdb65e052007-08-28 23:30:39 +00001546 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001547 for (unsigned i = 0; i != NumArgs; i++) {
1548 Expr *Arg = Args[i];
1549 DefaultArgumentPromotion(Arg);
1550 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001551 }
Chris Lattner4b009652007-07-25 00:24:17 +00001552 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001553
Chris Lattner2e64c072007-08-10 20:18:51 +00001554 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001555 if (FDecl)
1556 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001557
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001558 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001559}
1560
1561Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001562ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001563 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001564 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001565 QualType literalType = QualType::getFromOpaquePtr(Ty);
1566 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001567 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001568 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001569
Eli Friedman8c2173d2008-05-20 05:22:08 +00001570 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001571 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001572 return Diag(LParenLoc, diag::err_variable_object_no_init)
1573 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001574 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001575 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001576 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001577 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001578 }
1579
Douglas Gregor6428e762008-11-05 15:29:30 +00001580 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001581 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001582 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001583
Chris Lattnere5cb5862008-12-04 23:50:19 +00001584 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001585 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001586 if (CheckForConstantInitializer(literalExpr, literalType))
1587 return true;
1588 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001589 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1590 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001591}
1592
1593Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001594ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001595 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001596 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001597 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001598
Steve Naroff0acc9c92007-09-15 18:49:24 +00001599 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001600 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001601
Chris Lattner71ca8c82008-10-26 23:43:26 +00001602 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1603 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001604 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1605 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001606}
1607
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001608/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001609bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001610 UsualUnaryConversions(castExpr);
1611
1612 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1613 // type needs to be scalar.
1614 if (castType->isVoidType()) {
1615 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001616 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1617 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001618 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1619 // GCC struct/union extension: allow cast to self.
1620 if (Context.getCanonicalType(castType) !=
1621 Context.getCanonicalType(castExpr->getType()) ||
1622 (!castType->isStructureType() && !castType->isUnionType())) {
1623 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001624 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001625 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001626 }
1627
1628 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001629 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001630 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001631 } else if (!castExpr->getType()->isScalarType() &&
1632 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001633 return Diag(castExpr->getLocStart(),
1634 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001635 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001636 } else if (castExpr->getType()->isVectorType()) {
1637 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1638 return true;
1639 } else if (castType->isVectorType()) {
1640 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1641 return true;
1642 }
1643 return false;
1644}
1645
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001646bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001647 assert(VectorTy->isVectorType() && "Not a vector type!");
1648
1649 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001650 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001651 return Diag(R.getBegin(),
1652 Ty->isVectorType() ?
1653 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001654 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001655 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001656 } else
1657 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001658 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001659 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001660
1661 return false;
1662}
1663
Chris Lattner4b009652007-07-25 00:24:17 +00001664Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001665ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001666 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001667 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001668
1669 Expr *castExpr = static_cast<Expr*>(Op);
1670 QualType castType = QualType::getFromOpaquePtr(Ty);
1671
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001672 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1673 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001674 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001675}
1676
Chris Lattner98a425c2007-11-26 01:40:58 +00001677/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1678/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001679inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1680 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1681 UsualUnaryConversions(cond);
1682 UsualUnaryConversions(lex);
1683 UsualUnaryConversions(rex);
1684 QualType condT = cond->getType();
1685 QualType lexT = lex->getType();
1686 QualType rexT = rex->getType();
1687
1688 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001689 if (!cond->isTypeDependent()) {
1690 if (!condT->isScalarType()) { // C99 6.5.15p2
1691 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1692 return QualType();
1693 }
Chris Lattner4b009652007-07-25 00:24:17 +00001694 }
Chris Lattner992ae932008-01-06 22:42:25 +00001695
1696 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001697 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1698 return Context.DependentTy;
1699
Chris Lattner992ae932008-01-06 22:42:25 +00001700 // If both operands have arithmetic type, do the usual arithmetic conversions
1701 // to find a common type: C99 6.5.15p3,5.
1702 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001703 UsualArithmeticConversions(lex, rex);
1704 return lex->getType();
1705 }
Chris Lattner992ae932008-01-06 22:42:25 +00001706
1707 // If both operands are the same structure or union type, the result is that
1708 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001709 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001710 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001711 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001712 // "If both the operands have structure or union type, the result has
1713 // that type." This implies that CV qualifiers are dropped.
1714 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001715 }
Chris Lattner992ae932008-01-06 22:42:25 +00001716
1717 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001718 // The following || allows only one side to be void (a GCC-ism).
1719 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001720 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001721 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1722 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001723 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001724 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1725 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001726 ImpCastExprToType(lex, Context.VoidTy);
1727 ImpCastExprToType(rex, Context.VoidTy);
1728 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001729 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001730 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1731 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001732 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1733 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001734 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001735 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001736 return lexT;
1737 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001738 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1739 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001740 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001741 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001742 return rexT;
1743 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001744 // Handle the case where both operands are pointers before we handle null
1745 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001746 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1747 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1748 // get the "pointed to" types
1749 QualType lhptee = LHSPT->getPointeeType();
1750 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001751
Chris Lattner71225142007-07-31 21:27:01 +00001752 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1753 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001754 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001755 // Figure out necessary qualifiers (C99 6.5.15p6)
1756 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001757 QualType destType = Context.getPointerType(destPointee);
1758 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1759 ImpCastExprToType(rex, destType); // promote to void*
1760 return destType;
1761 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001762 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001763 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001764 QualType destType = Context.getPointerType(destPointee);
1765 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1766 ImpCastExprToType(rex, destType); // promote to void*
1767 return destType;
1768 }
Chris Lattner4b009652007-07-25 00:24:17 +00001769
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001770 QualType compositeType = lexT;
1771
1772 // If either type is an Objective-C object type then check
1773 // compatibility according to Objective-C.
1774 if (Context.isObjCObjectPointerType(lexT) ||
1775 Context.isObjCObjectPointerType(rexT)) {
1776 // If both operands are interfaces and either operand can be
1777 // assigned to the other, use that type as the composite
1778 // type. This allows
1779 // xxx ? (A*) a : (B*) b
1780 // where B is a subclass of A.
1781 //
1782 // Additionally, as for assignment, if either type is 'id'
1783 // allow silent coercion. Finally, if the types are
1784 // incompatible then make sure to use 'id' as the composite
1785 // type so the result is acceptable for sending messages to.
1786
1787 // FIXME: This code should not be localized to here. Also this
1788 // should use a compatible check instead of abusing the
1789 // canAssignObjCInterfaces code.
1790 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1791 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1792 if (LHSIface && RHSIface &&
1793 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1794 compositeType = lexT;
1795 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001796 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001797 compositeType = rexT;
1798 } else if (Context.isObjCIdType(lhptee) ||
1799 Context.isObjCIdType(rhptee)) {
1800 // FIXME: This code looks wrong, because isObjCIdType checks
1801 // the struct but getObjCIdType returns the pointer to
1802 // struct. This is horrible and should be fixed.
1803 compositeType = Context.getObjCIdType();
1804 } else {
1805 QualType incompatTy = Context.getObjCIdType();
1806 ImpCastExprToType(lex, incompatTy);
1807 ImpCastExprToType(rex, incompatTy);
1808 return incompatTy;
1809 }
1810 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1811 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001812 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001813 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001814 // In this situation, we assume void* type. No especially good
1815 // reason, but this is what gcc does, and we do have to pick
1816 // to get a consistent AST.
1817 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001818 ImpCastExprToType(lex, incompatTy);
1819 ImpCastExprToType(rex, incompatTy);
1820 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001821 }
1822 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001823 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1824 // differently qualified versions of compatible types, the result type is
1825 // a pointer to an appropriately qualified version of the *composite*
1826 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001827 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001828 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001829 ImpCastExprToType(lex, compositeType);
1830 ImpCastExprToType(rex, compositeType);
1831 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001832 }
Chris Lattner4b009652007-07-25 00:24:17 +00001833 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001834 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1835 // evaluates to "struct objc_object *" (and is handled above when comparing
1836 // id with statically typed objects).
1837 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1838 // GCC allows qualified id and any Objective-C type to devolve to
1839 // id. Currently localizing to here until clear this should be
1840 // part of ObjCQualifiedIdTypesAreCompatible.
1841 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1842 (lexT->isObjCQualifiedIdType() &&
1843 Context.isObjCObjectPointerType(rexT)) ||
1844 (rexT->isObjCQualifiedIdType() &&
1845 Context.isObjCObjectPointerType(lexT))) {
1846 // FIXME: This is not the correct composite type. This only
1847 // happens to work because id can more or less be used anywhere,
1848 // however this may change the type of method sends.
1849 // FIXME: gcc adds some type-checking of the arguments and emits
1850 // (confusing) incompatible comparison warnings in some
1851 // cases. Investigate.
1852 QualType compositeType = Context.getObjCIdType();
1853 ImpCastExprToType(lex, compositeType);
1854 ImpCastExprToType(rex, compositeType);
1855 return compositeType;
1856 }
1857 }
1858
Steve Naroff3eac7692008-09-10 19:17:48 +00001859 // Selection between block pointer types is ok as long as they are the same.
1860 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1861 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1862 return lexT;
1863
Chris Lattner992ae932008-01-06 22:42:25 +00001864 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001865 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001866 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001867 return QualType();
1868}
1869
Steve Naroff87d58b42007-09-16 03:34:24 +00001870/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001871/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001872Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001873 SourceLocation ColonLoc,
1874 ExprTy *Cond, ExprTy *LHS,
1875 ExprTy *RHS) {
1876 Expr *CondExpr = (Expr *) Cond;
1877 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001878
1879 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1880 // was the condition.
1881 bool isLHSNull = LHSExpr == 0;
1882 if (isLHSNull)
1883 LHSExpr = CondExpr;
1884
Chris Lattner4b009652007-07-25 00:24:17 +00001885 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1886 RHSExpr, QuestionLoc);
1887 if (result.isNull())
1888 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001889 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1890 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001891}
1892
Chris Lattner4b009652007-07-25 00:24:17 +00001893
1894// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1895// being closely modeled after the C99 spec:-). The odd characteristic of this
1896// routine is it effectively iqnores the qualifiers on the top level pointee.
1897// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1898// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001899Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001900Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1901 QualType lhptee, rhptee;
1902
1903 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001904 lhptee = lhsType->getAsPointerType()->getPointeeType();
1905 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001906
1907 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001908 lhptee = Context.getCanonicalType(lhptee);
1909 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001910
Chris Lattner005ed752008-01-04 18:04:52 +00001911 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001912
1913 // C99 6.5.16.1p1: This following citation is common to constraints
1914 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1915 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001916 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001917 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001918 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001919
1920 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1921 // incomplete type and the other is a pointer to a qualified or unqualified
1922 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001923 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001924 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001925 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001926
1927 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001928 assert(rhptee->isFunctionType());
1929 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001930 }
1931
1932 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001933 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001934 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001935
1936 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001937 assert(lhptee->isFunctionType());
1938 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001939 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001940
1941 // Check for ObjC interfaces
1942 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1943 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1944 if (LHSIface && RHSIface &&
1945 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1946 return ConvTy;
1947
1948 // ID acts sort of like void* for ObjC interfaces
1949 if (LHSIface && Context.isObjCIdType(rhptee))
1950 return ConvTy;
1951 if (RHSIface && Context.isObjCIdType(lhptee))
1952 return ConvTy;
1953
Chris Lattner4b009652007-07-25 00:24:17 +00001954 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1955 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001956 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1957 rhptee.getUnqualifiedType()))
1958 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001959 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001960}
1961
Steve Naroff3454b6c2008-09-04 15:10:53 +00001962/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1963/// block pointer types are compatible or whether a block and normal pointer
1964/// are compatible. It is more restrict than comparing two function pointer
1965// types.
1966Sema::AssignConvertType
1967Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1968 QualType rhsType) {
1969 QualType lhptee, rhptee;
1970
1971 // get the "pointed to" type (ignoring qualifiers at the top level)
1972 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1973 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1974
1975 // make sure we operate on the canonical type
1976 lhptee = Context.getCanonicalType(lhptee);
1977 rhptee = Context.getCanonicalType(rhptee);
1978
1979 AssignConvertType ConvTy = Compatible;
1980
1981 // For blocks we enforce that qualifiers are identical.
1982 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1983 ConvTy = CompatiblePointerDiscardsQualifiers;
1984
1985 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1986 return IncompatibleBlockPointer;
1987 return ConvTy;
1988}
1989
Chris Lattner4b009652007-07-25 00:24:17 +00001990/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1991/// has code to accommodate several GCC extensions when type checking
1992/// pointers. Here are some objectionable examples that GCC considers warnings:
1993///
1994/// int a, *pint;
1995/// short *pshort;
1996/// struct foo *pfoo;
1997///
1998/// pint = pshort; // warning: assignment from incompatible pointer type
1999/// a = pint; // warning: assignment makes integer from pointer without a cast
2000/// pint = a; // warning: assignment makes pointer from integer without a cast
2001/// pint = pfoo; // warning: assignment from incompatible pointer type
2002///
2003/// As a result, the code for dealing with pointers is more complex than the
2004/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002005///
Chris Lattner005ed752008-01-04 18:04:52 +00002006Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002007Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002008 // Get canonical types. We're not formatting these types, just comparing
2009 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002010 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2011 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002012
2013 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002014 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002015
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002016 // If the left-hand side is a reference type, then we are in a
2017 // (rare!) case where we've allowed the use of references in C,
2018 // e.g., as a parameter type in a built-in function. In this case,
2019 // just make sure that the type referenced is compatible with the
2020 // right-hand side type. The caller is responsible for adjusting
2021 // lhsType so that the resulting expression does not have reference
2022 // type.
2023 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2024 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002025 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002026 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002027 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002028
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002029 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2030 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002031 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002032 // Relax integer conversions like we do for pointers below.
2033 if (rhsType->isIntegerType())
2034 return IntToPointer;
2035 if (lhsType->isIntegerType())
2036 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002037 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002038 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002039
Nate Begemanc5f0f652008-07-14 18:02:46 +00002040 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002041 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002042 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2043 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002044 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002045
Nate Begemanc5f0f652008-07-14 18:02:46 +00002046 // If we are allowing lax vector conversions, and LHS and RHS are both
2047 // vectors, the total size only needs to be the same. This is a bitcast;
2048 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002049 if (getLangOptions().LaxVectorConversions &&
2050 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002051 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2052 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002053 }
2054 return Incompatible;
2055 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002056
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002057 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002058 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002059
Chris Lattner390564e2008-04-07 06:49:41 +00002060 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002061 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002062 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002063
Chris Lattner390564e2008-04-07 06:49:41 +00002064 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002065 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002066
Steve Naroffa982c712008-09-29 18:10:17 +00002067 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002068 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002069 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002070
2071 // Treat block pointers as objects.
2072 if (getLangOptions().ObjC1 &&
2073 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2074 return Compatible;
2075 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002076 return Incompatible;
2077 }
2078
2079 if (isa<BlockPointerType>(lhsType)) {
2080 if (rhsType->isIntegerType())
2081 return IntToPointer;
2082
Steve Naroffa982c712008-09-29 18:10:17 +00002083 // Treat block pointers as objects.
2084 if (getLangOptions().ObjC1 &&
2085 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2086 return Compatible;
2087
Steve Naroff3454b6c2008-09-04 15:10:53 +00002088 if (rhsType->isBlockPointerType())
2089 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2090
2091 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2092 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002093 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002094 }
Chris Lattner1853da22008-01-04 23:18:45 +00002095 return Incompatible;
2096 }
2097
Chris Lattner390564e2008-04-07 06:49:41 +00002098 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002099 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002100 if (lhsType == Context.BoolTy)
2101 return Compatible;
2102
2103 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002104 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002105
Chris Lattner390564e2008-04-07 06:49:41 +00002106 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002107 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002108
2109 if (isa<BlockPointerType>(lhsType) &&
2110 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002111 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002112 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002113 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002114
Chris Lattner1853da22008-01-04 23:18:45 +00002115 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002116 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002117 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002118 }
2119 return Incompatible;
2120}
2121
Chris Lattner005ed752008-01-04 18:04:52 +00002122Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002123Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002124 if (getLangOptions().CPlusPlus) {
2125 if (!lhsType->isRecordType()) {
2126 // C++ 5.17p3: If the left operand is not of class type, the
2127 // expression is implicitly converted (C++ 4) to the
2128 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002129 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002130 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002131 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002132 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002133 }
2134
2135 // FIXME: Currently, we fall through and treat C++ classes like C
2136 // structures.
2137 }
2138
Steve Naroffcdee22d2007-11-27 17:58:44 +00002139 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2140 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002141 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2142 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002143 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002144 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002145 return Compatible;
2146 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002147
2148 // We don't allow conversion of non-null-pointer constants to integers.
2149 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2150 return IntToBlockPointer;
2151
Chris Lattner5f505bf2007-10-16 02:55:40 +00002152 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002153 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002154 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002155 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002156 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002157 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002158 if (!lhsType->isReferenceType())
2159 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002160
Chris Lattner005ed752008-01-04 18:04:52 +00002161 Sema::AssignConvertType result =
2162 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002163
2164 // C99 6.5.16.1p2: The value of the right operand is converted to the
2165 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002166 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2167 // so that we can use references in built-in functions even in C.
2168 // The getNonReferenceType() call makes sure that the resulting expression
2169 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002170 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002171 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002172 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002173}
2174
Chris Lattner005ed752008-01-04 18:04:52 +00002175Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002176Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2177 return CheckAssignmentConstraints(lhsType, rhsType);
2178}
2179
Chris Lattner1eafdea2008-11-18 01:30:42 +00002180QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002181 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002182 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002183 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002184 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002185}
2186
Chris Lattner1eafdea2008-11-18 01:30:42 +00002187inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002188 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002189 // For conversion purposes, we ignore any qualifiers.
2190 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002191 QualType lhsType =
2192 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2193 QualType rhsType =
2194 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002195
Nate Begemanc5f0f652008-07-14 18:02:46 +00002196 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002197 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002198 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002199
Nate Begemanc5f0f652008-07-14 18:02:46 +00002200 // Handle the case of a vector & extvector type of the same size and element
2201 // type. It would be nice if we only had one vector type someday.
2202 if (getLangOptions().LaxVectorConversions)
2203 if (const VectorType *LV = lhsType->getAsVectorType())
2204 if (const VectorType *RV = rhsType->getAsVectorType())
2205 if (LV->getElementType() == RV->getElementType() &&
2206 LV->getNumElements() == RV->getNumElements())
2207 return lhsType->isExtVectorType() ? lhsType : rhsType;
2208
2209 // If the lhs is an extended vector and the rhs is a scalar of the same type
2210 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002211 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002212 QualType eltType = V->getElementType();
2213
2214 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2215 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2216 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002217 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002218 return lhsType;
2219 }
2220 }
2221
Nate Begemanc5f0f652008-07-14 18:02:46 +00002222 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002223 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002224 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002225 QualType eltType = V->getElementType();
2226
2227 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2228 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2229 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002230 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002231 return rhsType;
2232 }
2233 }
2234
Chris Lattner4b009652007-07-25 00:24:17 +00002235 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002236 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002237 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002238 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002239 return QualType();
2240}
2241
2242inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002243 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002244{
2245 QualType lhsType = lex->getType(), rhsType = rex->getType();
2246
2247 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002248 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002249
Steve Naroff8f708362007-08-24 19:07:16 +00002250 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002251
Chris Lattner4b009652007-07-25 00:24:17 +00002252 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002253 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002254 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002255}
2256
2257inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002258 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002259{
2260 QualType lhsType = lex->getType(), rhsType = rex->getType();
2261
Steve Naroff8f708362007-08-24 19:07:16 +00002262 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002263
Chris Lattner4b009652007-07-25 00:24:17 +00002264 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002265 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002266 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002267}
2268
2269inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002270 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002271{
2272 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002273 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002274
Steve Naroff8f708362007-08-24 19:07:16 +00002275 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002276
Chris Lattner4b009652007-07-25 00:24:17 +00002277 // handle the common case first (both operands are arithmetic).
2278 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002279 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002280
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002281 // Put any potential pointer into PExp
2282 Expr* PExp = lex, *IExp = rex;
2283 if (IExp->getType()->isPointerType())
2284 std::swap(PExp, IExp);
2285
2286 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2287 if (IExp->getType()->isIntegerType()) {
2288 // Check for arithmetic on pointers to incomplete types
2289 if (!PTy->getPointeeType()->isObjectType()) {
2290 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002291 Diag(Loc, diag::ext_gnu_void_ptr)
2292 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002293 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002294 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002295 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002296 return QualType();
2297 }
2298 }
2299 return PExp->getType();
2300 }
2301 }
2302
Chris Lattner1eafdea2008-11-18 01:30:42 +00002303 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002304}
2305
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002306// C99 6.5.6
2307QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002308 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002309 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002310 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002311
Steve Naroff8f708362007-08-24 19:07:16 +00002312 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002313
Chris Lattnerf6da2912007-12-09 21:53:25 +00002314 // Enforce type constraints: C99 6.5.6p3.
2315
2316 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002317 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002318 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002319
2320 // Either ptr - int or ptr - ptr.
2321 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002322 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002323
Chris Lattnerf6da2912007-12-09 21:53:25 +00002324 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002325 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002326 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002327 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002328 Diag(Loc, diag::ext_gnu_void_ptr)
2329 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002330 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002331 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002332 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002333 return QualType();
2334 }
2335 }
2336
2337 // The result type of a pointer-int computation is the pointer type.
2338 if (rex->getType()->isIntegerType())
2339 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002340
Chris Lattnerf6da2912007-12-09 21:53:25 +00002341 // Handle pointer-pointer subtractions.
2342 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002343 QualType rpointee = RHSPTy->getPointeeType();
2344
Chris Lattnerf6da2912007-12-09 21:53:25 +00002345 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002346 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002347 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002348 if (rpointee->isVoidType()) {
2349 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002350 Diag(Loc, diag::ext_gnu_void_ptr)
2351 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002352 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002353 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002354 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002355 return QualType();
2356 }
2357 }
2358
2359 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002360 if (!Context.typesAreCompatible(
2361 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2362 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002363 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002364 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002365 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002366 return QualType();
2367 }
2368
2369 return Context.getPointerDiffType();
2370 }
2371 }
2372
Chris Lattner1eafdea2008-11-18 01:30:42 +00002373 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002374}
2375
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002376// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002377QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002378 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002379 // C99 6.5.7p2: Each of the operands shall have integer type.
2380 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002381 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002382
Chris Lattner2c8bff72007-12-12 05:47:28 +00002383 // Shifts don't perform usual arithmetic conversions, they just do integer
2384 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002385 if (!isCompAssign)
2386 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002387 UsualUnaryConversions(rex);
2388
2389 // "The type of the result is that of the promoted left operand."
2390 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002391}
2392
Eli Friedman0d9549b2008-08-22 00:56:42 +00002393static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2394 ASTContext& Context) {
2395 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2396 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2397 // ID acts sort of like void* for ObjC interfaces
2398 if (LHSIface && Context.isObjCIdType(RHS))
2399 return true;
2400 if (RHSIface && Context.isObjCIdType(LHS))
2401 return true;
2402 if (!LHSIface || !RHSIface)
2403 return false;
2404 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2405 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2406}
2407
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002408// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002409QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002410 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002411 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002412 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002413
Chris Lattner254f3bc2007-08-26 01:18:55 +00002414 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002415 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2416 UsualArithmeticConversions(lex, rex);
2417 else {
2418 UsualUnaryConversions(lex);
2419 UsualUnaryConversions(rex);
2420 }
Chris Lattner4b009652007-07-25 00:24:17 +00002421 QualType lType = lex->getType();
2422 QualType rType = rex->getType();
2423
Ted Kremenek486509e2007-10-29 17:13:39 +00002424 // For non-floating point types, check for self-comparisons of the form
2425 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2426 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002427 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002428 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2429 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002430 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002431 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002432 }
2433
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002434 // The result of comparisons is 'bool' in C++, 'int' in C.
2435 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2436
Chris Lattner254f3bc2007-08-26 01:18:55 +00002437 if (isRelational) {
2438 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002439 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002440 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002441 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002442 if (lType->isFloatingType()) {
2443 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002444 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002445 }
2446
Chris Lattner254f3bc2007-08-26 01:18:55 +00002447 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002448 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002449 }
Chris Lattner4b009652007-07-25 00:24:17 +00002450
Chris Lattner22be8422007-08-26 01:10:14 +00002451 bool LHSIsNull = lex->isNullPointerConstant(Context);
2452 bool RHSIsNull = rex->isNullPointerConstant(Context);
2453
Chris Lattner254f3bc2007-08-26 01:18:55 +00002454 // All of the following pointer related warnings are GCC extensions, except
2455 // when handling null pointer constants. One day, we can consider making them
2456 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002457 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002458 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002459 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002460 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002461 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002462
Steve Naroff3b435622007-11-13 14:57:38 +00002463 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002464 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2465 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002466 RCanPointeeTy.getUnqualifiedType()) &&
2467 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002468 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002469 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002470 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002471 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002472 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002473 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002474 // Handle block pointer types.
2475 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2476 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2477 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2478
2479 if (!LHSIsNull && !RHSIsNull &&
2480 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002481 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002482 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002483 }
2484 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002485 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002486 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002487 // Allow block pointers to be compared with null pointer constants.
2488 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2489 (lType->isPointerType() && rType->isBlockPointerType())) {
2490 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002491 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002492 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002493 }
2494 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002495 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002496 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002497
Steve Naroff936c4362008-06-03 14:04:54 +00002498 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002499 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002500 const PointerType *LPT = lType->getAsPointerType();
2501 const PointerType *RPT = rType->getAsPointerType();
2502 bool LPtrToVoid = LPT ?
2503 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2504 bool RPtrToVoid = RPT ?
2505 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2506
2507 if (!LPtrToVoid && !RPtrToVoid &&
2508 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002509 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002510 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002511 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002512 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002513 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002514 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002515 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002516 }
Steve Naroff936c4362008-06-03 14:04:54 +00002517 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2518 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002519 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002520 } else {
2521 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002522 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002523 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002524 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002525 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002526 }
Steve Naroff936c4362008-06-03 14:04:54 +00002527 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002528 }
Steve Naroff936c4362008-06-03 14:04:54 +00002529 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2530 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002531 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002532 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002533 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002534 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002535 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002536 }
Steve Naroff936c4362008-06-03 14:04:54 +00002537 if (lType->isIntegerType() &&
2538 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002539 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002540 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002541 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002542 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002543 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002544 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002545 // Handle block pointers.
2546 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2547 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002548 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002549 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002550 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002551 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002552 }
2553 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2554 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002555 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002556 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002557 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002558 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002559 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002560 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002561}
2562
Nate Begemanc5f0f652008-07-14 18:02:46 +00002563/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2564/// operates on extended vector types. Instead of producing an IntTy result,
2565/// like a scalar comparison, a vector comparison produces a vector of integer
2566/// types.
2567QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002568 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002569 bool isRelational) {
2570 // Check to make sure we're operating on vectors of the same type and width,
2571 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002572 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002573 if (vType.isNull())
2574 return vType;
2575
2576 QualType lType = lex->getType();
2577 QualType rType = rex->getType();
2578
2579 // For non-floating point types, check for self-comparisons of the form
2580 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2581 // often indicate logic errors in the program.
2582 if (!lType->isFloatingType()) {
2583 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2584 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2585 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002586 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002587 }
2588
2589 // Check for comparisons of floating point operands using != and ==.
2590 if (!isRelational && lType->isFloatingType()) {
2591 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002592 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002593 }
2594
2595 // Return the type for the comparison, which is the same as vector type for
2596 // integer vectors, or an integer type of identical size and number of
2597 // elements for floating point vectors.
2598 if (lType->isIntegerType())
2599 return lType;
2600
2601 const VectorType *VTy = lType->getAsVectorType();
2602
2603 // FIXME: need to deal with non-32b int / non-64b long long
2604 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2605 if (TypeSize == 32) {
2606 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2607 }
2608 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2609 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2610}
2611
Chris Lattner4b009652007-07-25 00:24:17 +00002612inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002613 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002614{
2615 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002616 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002617
Steve Naroff8f708362007-08-24 19:07:16 +00002618 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002619
2620 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002621 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002622 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002623}
2624
2625inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002626 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002627{
2628 UsualUnaryConversions(lex);
2629 UsualUnaryConversions(rex);
2630
Eli Friedmanbea3f842008-05-13 20:16:47 +00002631 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002632 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002633 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002634}
2635
Chris Lattner4c2642c2008-11-18 01:22:49 +00002636/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2637/// emit an error and return true. If so, return false.
2638static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2639 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2640 if (IsLV == Expr::MLV_Valid)
2641 return false;
2642
2643 unsigned Diag = 0;
2644 bool NeedType = false;
2645 switch (IsLV) { // C99 6.5.16p2
2646 default: assert(0 && "Unknown result from isModifiableLvalue!");
2647 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002648 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002649 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2650 NeedType = true;
2651 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002652 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002653 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2654 NeedType = true;
2655 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002656 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002657 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2658 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002659 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002660 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2661 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002662 case Expr::MLV_IncompleteType:
2663 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002664 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2665 NeedType = true;
2666 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002667 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002668 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2669 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002670 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002671 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2672 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002673 case Expr::MLV_ReadonlyProperty:
2674 Diag = diag::error_readonly_property_assignment;
2675 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002676 case Expr::MLV_NoSetterProperty:
2677 Diag = diag::error_nosetter_property_assignment;
2678 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002679 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002680
Chris Lattner4c2642c2008-11-18 01:22:49 +00002681 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002682 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002683 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002684 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002685 return true;
2686}
2687
2688
2689
2690// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002691QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2692 SourceLocation Loc,
2693 QualType CompoundType) {
2694 // Verify that LHS is a modifiable lvalue, and emit error if not.
2695 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002696 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002697
2698 QualType LHSType = LHS->getType();
2699 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002700
Chris Lattner005ed752008-01-04 18:04:52 +00002701 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002702 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002703 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002704 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002705
2706 // If the RHS is a unary plus or minus, check to see if they = and + are
2707 // right next to each other. If so, the user may have typo'd "x =+ 4"
2708 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002709 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002710 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2711 RHSCheck = ICE->getSubExpr();
2712 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2713 if ((UO->getOpcode() == UnaryOperator::Plus ||
2714 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002715 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002716 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002717 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002718 Diag(Loc, diag::warn_not_compound_assign)
2719 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2720 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002721 }
2722 } else {
2723 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002724 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002725 }
Chris Lattner005ed752008-01-04 18:04:52 +00002726
Chris Lattner1eafdea2008-11-18 01:30:42 +00002727 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2728 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002729 return QualType();
2730
Chris Lattner4b009652007-07-25 00:24:17 +00002731 // C99 6.5.16p3: The type of an assignment expression is the type of the
2732 // left operand unless the left operand has qualified type, in which case
2733 // it is the unqualified version of the type of the left operand.
2734 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2735 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002736 // C++ 5.17p1: the type of the assignment expression is that of its left
2737 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002738 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002739}
2740
Chris Lattner1eafdea2008-11-18 01:30:42 +00002741// C99 6.5.17
2742QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2743 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002744
2745 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002746 DefaultFunctionArrayConversion(RHS);
2747 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002748}
2749
2750/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2751/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002752QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2753 QualType ResType = Op->getType();
2754 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Steve Naroffd30e1932007-08-24 17:20:07 +00002756 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002757 if (ResType->isRealType()) {
2758 // OK!
2759 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2760 // C99 6.5.2.4p2, 6.5.6p2
2761 if (PT->getPointeeType()->isObjectType()) {
2762 // Pointer to object is ok!
2763 } else if (PT->getPointeeType()->isVoidType()) {
2764 // Pointer to void is extension.
2765 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2766 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002767 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002768 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002769 return QualType();
2770 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002771 } else if (ResType->isComplexType()) {
2772 // C99 does not support ++/-- on complex types, we allow as an extension.
2773 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002774 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002775 } else {
2776 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002777 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002778 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002779 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002780 // At this point, we know we have a real, complex or pointer type.
2781 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002782 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002783 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002784 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002785}
2786
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002787/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002788/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002789/// where the declaration is needed for type checking. We only need to
2790/// handle cases when the expression references a function designator
2791/// or is an lvalue. Here are some examples:
2792/// - &(x) => x
2793/// - &*****f => f for f a function designator.
2794/// - &s.xx => s
2795/// - &s.zz[1].yy -> s, if zz is an array
2796/// - *(x + 1) -> x, if x is an array
2797/// - &"123"[2] -> 0
2798/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002799static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002800 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002801 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002802 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002803 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002804 // Fields cannot be declared with a 'register' storage class.
2805 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002806 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002807 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002808 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002809 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002810 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002811
Douglas Gregord2baafd2008-10-21 16:13:35 +00002812 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002813 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002814 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002815 return 0;
2816 else
2817 return VD;
2818 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002819 case Stmt::UnaryOperatorClass: {
2820 UnaryOperator *UO = cast<UnaryOperator>(E);
2821
2822 switch(UO->getOpcode()) {
2823 case UnaryOperator::Deref: {
2824 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002825 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2826 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2827 if (!VD || VD->getType()->isPointerType())
2828 return 0;
2829 return VD;
2830 }
2831 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002832 }
2833 case UnaryOperator::Real:
2834 case UnaryOperator::Imag:
2835 case UnaryOperator::Extension:
2836 return getPrimaryDecl(UO->getSubExpr());
2837 default:
2838 return 0;
2839 }
2840 }
2841 case Stmt::BinaryOperatorClass: {
2842 BinaryOperator *BO = cast<BinaryOperator>(E);
2843
2844 // Handle cases involving pointer arithmetic. The result of an
2845 // Assign or AddAssign is not an lvalue so they can be ignored.
2846
2847 // (x + n) or (n + x) => x
2848 if (BO->getOpcode() == BinaryOperator::Add) {
2849 if (BO->getLHS()->getType()->isPointerType()) {
2850 return getPrimaryDecl(BO->getLHS());
2851 } else if (BO->getRHS()->getType()->isPointerType()) {
2852 return getPrimaryDecl(BO->getRHS());
2853 }
2854 }
2855
2856 return 0;
2857 }
Chris Lattner4b009652007-07-25 00:24:17 +00002858 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002859 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002860 case Stmt::ImplicitCastExprClass:
2861 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002862 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002863 default:
2864 return 0;
2865 }
2866}
2867
2868/// CheckAddressOfOperand - The operand of & must be either a function
2869/// designator or an lvalue designating an object. If it is an lvalue, the
2870/// object cannot be declared with storage class register or be a bit field.
2871/// Note: The usual conversions are *not* applied to the operand of the &
2872/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002873/// In C++, the operand might be an overloaded function name, in which case
2874/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002875QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002876 if (getLangOptions().C99) {
2877 // Implement C99-only parts of addressof rules.
2878 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2879 if (uOp->getOpcode() == UnaryOperator::Deref)
2880 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2881 // (assuming the deref expression is valid).
2882 return uOp->getSubExpr()->getType();
2883 }
2884 // Technically, there should be a check for array subscript
2885 // expressions here, but the result of one is always an lvalue anyway.
2886 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002887 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002888 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002889
2890 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002891 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2892 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002893 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2894 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002895 return QualType();
2896 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002897 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2898 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002899 Diag(OpLoc, diag::err_typecheck_address_of)
2900 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002901 return QualType();
2902 }
2903 // Check for Apple extension for accessing vector components.
2904 } else if (isa<ArraySubscriptExpr>(op) &&
2905 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002906 Diag(OpLoc, diag::err_typecheck_address_of)
2907 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002908 return QualType();
2909 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002910 // We have an lvalue with a decl. Make sure the decl is not declared
2911 // with the register storage-class specifier.
2912 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2913 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002914 Diag(OpLoc, diag::err_typecheck_address_of)
2915 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002916 return QualType();
2917 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00002918 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002919 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00002920 } else if (isa<FieldDecl>(dcl)) {
2921 // Okay: we can take the address of a field.
2922 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002923 else
Chris Lattner4b009652007-07-25 00:24:17 +00002924 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002925 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002926
Chris Lattner4b009652007-07-25 00:24:17 +00002927 // If the operand has type "type", the result has type "pointer to type".
2928 return Context.getPointerType(op->getType());
2929}
2930
Chris Lattnerda5c0872008-11-23 09:13:29 +00002931QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2932 UsualUnaryConversions(Op);
2933 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002934
Chris Lattnerda5c0872008-11-23 09:13:29 +00002935 // Note that per both C89 and C99, this is always legal, even if ptype is an
2936 // incomplete type or void. It would be possible to warn about dereferencing
2937 // a void pointer, but it's completely well-defined, and such a warning is
2938 // unlikely to catch any mistakes.
2939 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002940 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002941
Chris Lattner77d52da2008-11-20 06:06:08 +00002942 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002943 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002944 return QualType();
2945}
2946
2947static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2948 tok::TokenKind Kind) {
2949 BinaryOperator::Opcode Opc;
2950 switch (Kind) {
2951 default: assert(0 && "Unknown binop!");
2952 case tok::star: Opc = BinaryOperator::Mul; break;
2953 case tok::slash: Opc = BinaryOperator::Div; break;
2954 case tok::percent: Opc = BinaryOperator::Rem; break;
2955 case tok::plus: Opc = BinaryOperator::Add; break;
2956 case tok::minus: Opc = BinaryOperator::Sub; break;
2957 case tok::lessless: Opc = BinaryOperator::Shl; break;
2958 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2959 case tok::lessequal: Opc = BinaryOperator::LE; break;
2960 case tok::less: Opc = BinaryOperator::LT; break;
2961 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2962 case tok::greater: Opc = BinaryOperator::GT; break;
2963 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2964 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2965 case tok::amp: Opc = BinaryOperator::And; break;
2966 case tok::caret: Opc = BinaryOperator::Xor; break;
2967 case tok::pipe: Opc = BinaryOperator::Or; break;
2968 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2969 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2970 case tok::equal: Opc = BinaryOperator::Assign; break;
2971 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2972 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2973 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2974 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2975 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2976 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2977 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2978 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2979 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2980 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2981 case tok::comma: Opc = BinaryOperator::Comma; break;
2982 }
2983 return Opc;
2984}
2985
2986static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2987 tok::TokenKind Kind) {
2988 UnaryOperator::Opcode Opc;
2989 switch (Kind) {
2990 default: assert(0 && "Unknown unary op!");
2991 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2992 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2993 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2994 case tok::star: Opc = UnaryOperator::Deref; break;
2995 case tok::plus: Opc = UnaryOperator::Plus; break;
2996 case tok::minus: Opc = UnaryOperator::Minus; break;
2997 case tok::tilde: Opc = UnaryOperator::Not; break;
2998 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002999 case tok::kw___real: Opc = UnaryOperator::Real; break;
3000 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3001 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3002 }
3003 return Opc;
3004}
3005
Douglas Gregord7f915e2008-11-06 23:29:22 +00003006/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3007/// operator @p Opc at location @c TokLoc. This routine only supports
3008/// built-in operations; ActOnBinOp handles overloaded operators.
3009Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3010 unsigned Op,
3011 Expr *lhs, Expr *rhs) {
3012 QualType ResultTy; // Result type of the binary operator.
3013 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3014 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3015
3016 switch (Opc) {
3017 default:
3018 assert(0 && "Unknown binary expr!");
3019 case BinaryOperator::Assign:
3020 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3021 break;
3022 case BinaryOperator::Mul:
3023 case BinaryOperator::Div:
3024 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3025 break;
3026 case BinaryOperator::Rem:
3027 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3028 break;
3029 case BinaryOperator::Add:
3030 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3031 break;
3032 case BinaryOperator::Sub:
3033 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3034 break;
3035 case BinaryOperator::Shl:
3036 case BinaryOperator::Shr:
3037 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3038 break;
3039 case BinaryOperator::LE:
3040 case BinaryOperator::LT:
3041 case BinaryOperator::GE:
3042 case BinaryOperator::GT:
3043 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3044 break;
3045 case BinaryOperator::EQ:
3046 case BinaryOperator::NE:
3047 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3048 break;
3049 case BinaryOperator::And:
3050 case BinaryOperator::Xor:
3051 case BinaryOperator::Or:
3052 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3053 break;
3054 case BinaryOperator::LAnd:
3055 case BinaryOperator::LOr:
3056 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3057 break;
3058 case BinaryOperator::MulAssign:
3059 case BinaryOperator::DivAssign:
3060 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3061 if (!CompTy.isNull())
3062 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3063 break;
3064 case BinaryOperator::RemAssign:
3065 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3066 if (!CompTy.isNull())
3067 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3068 break;
3069 case BinaryOperator::AddAssign:
3070 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3071 if (!CompTy.isNull())
3072 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3073 break;
3074 case BinaryOperator::SubAssign:
3075 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3076 if (!CompTy.isNull())
3077 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3078 break;
3079 case BinaryOperator::ShlAssign:
3080 case BinaryOperator::ShrAssign:
3081 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3082 if (!CompTy.isNull())
3083 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3084 break;
3085 case BinaryOperator::AndAssign:
3086 case BinaryOperator::XorAssign:
3087 case BinaryOperator::OrAssign:
3088 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3089 if (!CompTy.isNull())
3090 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3091 break;
3092 case BinaryOperator::Comma:
3093 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3094 break;
3095 }
3096 if (ResultTy.isNull())
3097 return true;
3098 if (CompTy.isNull())
3099 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3100 else
3101 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3102}
3103
Chris Lattner4b009652007-07-25 00:24:17 +00003104// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003105Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3106 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003107 ExprTy *LHS, ExprTy *RHS) {
3108 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3109 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3110
Steve Naroff87d58b42007-09-16 03:34:24 +00003111 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3112 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003113
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003114 // If either expression is type-dependent, just build the AST.
3115 // FIXME: We'll need to perform some caching of the result of name
3116 // lookup for operator+.
3117 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3118 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3119 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3120 Context.DependentTy, TokLoc);
3121 else
3122 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3123 }
3124
Douglas Gregord7f915e2008-11-06 23:29:22 +00003125 if (getLangOptions().CPlusPlus &&
3126 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3127 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003128 // If this is one of the assignment operators, we only perform
3129 // overload resolution if the left-hand side is a class or
3130 // enumeration type (C++ [expr.ass]p3).
3131 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3132 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3133 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3134 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003135
3136 // Determine which overloaded operator we're dealing with.
3137 static const OverloadedOperatorKind OverOps[] = {
3138 OO_Star, OO_Slash, OO_Percent,
3139 OO_Plus, OO_Minus,
3140 OO_LessLess, OO_GreaterGreater,
3141 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3142 OO_EqualEqual, OO_ExclaimEqual,
3143 OO_Amp,
3144 OO_Caret,
3145 OO_Pipe,
3146 OO_AmpAmp,
3147 OO_PipePipe,
3148 OO_Equal, OO_StarEqual,
3149 OO_SlashEqual, OO_PercentEqual,
3150 OO_PlusEqual, OO_MinusEqual,
3151 OO_LessLessEqual, OO_GreaterGreaterEqual,
3152 OO_AmpEqual, OO_CaretEqual,
3153 OO_PipeEqual,
3154 OO_Comma
3155 };
3156 OverloadedOperatorKind OverOp = OverOps[Opc];
3157
Douglas Gregor5ed15042008-11-18 23:14:02 +00003158 // Add the appropriate overloaded operators (C++ [over.match.oper])
3159 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003160 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003161 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003162 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003163
3164 // Perform overload resolution.
3165 OverloadCandidateSet::iterator Best;
3166 switch (BestViableFunction(CandidateSet, Best)) {
3167 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003168 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003169 FunctionDecl *FnDecl = Best->Function;
3170
Douglas Gregor70d26122008-11-12 17:17:38 +00003171 if (FnDecl) {
3172 // We matched an overloaded operator. Build a call to that
3173 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003174
Douglas Gregor70d26122008-11-12 17:17:38 +00003175 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003176 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3177 if (PerformObjectArgumentInitialization(lhs, Method) ||
3178 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3179 "passing"))
3180 return true;
3181 } else {
3182 // Convert the arguments.
3183 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3184 "passing") ||
3185 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3186 "passing"))
3187 return true;
3188 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003189
Douglas Gregor70d26122008-11-12 17:17:38 +00003190 // Determine the result type
3191 QualType ResultTy
3192 = FnDecl->getType()->getAsFunctionType()->getResultType();
3193 ResultTy = ResultTy.getNonReferenceType();
3194
3195 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003196 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3197 SourceLocation());
3198 UsualUnaryConversions(FnExpr);
3199
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003200 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003201 } else {
3202 // We matched a built-in operator. Convert the arguments, then
3203 // break out so that we will build the appropriate built-in
3204 // operator node.
3205 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3206 "passing") ||
3207 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3208 "passing"))
3209 return true;
3210
3211 break;
3212 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003213 }
3214
3215 case OR_No_Viable_Function:
3216 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003217 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003218 break;
3219
3220 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003221 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3222 << BinaryOperator::getOpcodeStr(Opc)
3223 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003224 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3225 return true;
3226 }
3227
Douglas Gregor70d26122008-11-12 17:17:38 +00003228 // Either we found no viable overloaded operator or we matched a
3229 // built-in operator. In either case, fall through to trying to
3230 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003231 }
Chris Lattner4b009652007-07-25 00:24:17 +00003232
Douglas Gregord7f915e2008-11-06 23:29:22 +00003233 // Build a built-in binary operation.
3234 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003235}
3236
3237// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003238Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3239 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003240 Expr *Input = (Expr*)input;
3241 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003242
3243 if (getLangOptions().CPlusPlus &&
3244 (Input->getType()->isRecordType()
3245 || Input->getType()->isEnumeralType())) {
3246 // Determine which overloaded operator we're dealing with.
3247 static const OverloadedOperatorKind OverOps[] = {
3248 OO_None, OO_None,
3249 OO_PlusPlus, OO_MinusMinus,
3250 OO_Amp, OO_Star,
3251 OO_Plus, OO_Minus,
3252 OO_Tilde, OO_Exclaim,
3253 OO_None, OO_None,
3254 OO_None,
3255 OO_None
3256 };
3257 OverloadedOperatorKind OverOp = OverOps[Opc];
3258
3259 // Add the appropriate overloaded operators (C++ [over.match.oper])
3260 // to the candidate set.
3261 OverloadCandidateSet CandidateSet;
3262 if (OverOp != OO_None)
3263 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3264
3265 // Perform overload resolution.
3266 OverloadCandidateSet::iterator Best;
3267 switch (BestViableFunction(CandidateSet, Best)) {
3268 case OR_Success: {
3269 // We found a built-in operator or an overloaded operator.
3270 FunctionDecl *FnDecl = Best->Function;
3271
3272 if (FnDecl) {
3273 // We matched an overloaded operator. Build a call to that
3274 // operator.
3275
3276 // Convert the arguments.
3277 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3278 if (PerformObjectArgumentInitialization(Input, Method))
3279 return true;
3280 } else {
3281 // Convert the arguments.
3282 if (PerformCopyInitialization(Input,
3283 FnDecl->getParamDecl(0)->getType(),
3284 "passing"))
3285 return true;
3286 }
3287
3288 // Determine the result type
3289 QualType ResultTy
3290 = FnDecl->getType()->getAsFunctionType()->getResultType();
3291 ResultTy = ResultTy.getNonReferenceType();
3292
3293 // Build the actual expression node.
3294 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3295 SourceLocation());
3296 UsualUnaryConversions(FnExpr);
3297
3298 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3299 } else {
3300 // We matched a built-in operator. Convert the arguments, then
3301 // break out so that we will build the appropriate built-in
3302 // operator node.
3303 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3304 "passing"))
3305 return true;
3306
3307 break;
3308 }
3309 }
3310
3311 case OR_No_Viable_Function:
3312 // No viable function; fall through to handling this as a
3313 // built-in operator, which will produce an error message for us.
3314 break;
3315
3316 case OR_Ambiguous:
3317 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3318 << UnaryOperator::getOpcodeStr(Opc)
3319 << Input->getSourceRange();
3320 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3321 return true;
3322 }
3323
3324 // Either we found no viable overloaded operator or we matched a
3325 // built-in operator. In either case, fall through to trying to
3326 // build a built-in operation.
3327 }
3328
Chris Lattner4b009652007-07-25 00:24:17 +00003329 QualType resultType;
3330 switch (Opc) {
3331 default:
3332 assert(0 && "Unimplemented unary expr!");
3333 case UnaryOperator::PreInc:
3334 case UnaryOperator::PreDec:
3335 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3336 break;
3337 case UnaryOperator::AddrOf:
3338 resultType = CheckAddressOfOperand(Input, OpLoc);
3339 break;
3340 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003341 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003342 resultType = CheckIndirectionOperand(Input, OpLoc);
3343 break;
3344 case UnaryOperator::Plus:
3345 case UnaryOperator::Minus:
3346 UsualUnaryConversions(Input);
3347 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003348 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3349 break;
3350 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3351 resultType->isEnumeralType())
3352 break;
3353 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3354 Opc == UnaryOperator::Plus &&
3355 resultType->isPointerType())
3356 break;
3357
Chris Lattner77d52da2008-11-20 06:06:08 +00003358 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003359 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003360 case UnaryOperator::Not: // bitwise complement
3361 UsualUnaryConversions(Input);
3362 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003363 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3364 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3365 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003366 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003367 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003368 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003369 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003370 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003371 break;
3372 case UnaryOperator::LNot: // logical negation
3373 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3374 DefaultFunctionArrayConversion(Input);
3375 resultType = Input->getType();
3376 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003377 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003378 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003379 // LNot always has type int. C99 6.5.3.3p5.
3380 resultType = Context.IntTy;
3381 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003382 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003383 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003384 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003385 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003386 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003387 resultType = Input->getType();
3388 break;
3389 }
3390 if (resultType.isNull())
3391 return true;
3392 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3393}
3394
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003395/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3396Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003397 SourceLocation LabLoc,
3398 IdentifierInfo *LabelII) {
3399 // Look up the record for this label identifier.
3400 LabelStmt *&LabelDecl = LabelMap[LabelII];
3401
Daniel Dunbar879788d2008-08-04 16:51:22 +00003402 // If we haven't seen this label yet, create a forward reference. It
3403 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003404 if (LabelDecl == 0)
3405 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3406
3407 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003408 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3409 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003410}
3411
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003412Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003413 SourceLocation RPLoc) { // "({..})"
3414 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3415 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3416 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3417
3418 // FIXME: there are a variety of strange constraints to enforce here, for
3419 // example, it is not possible to goto into a stmt expression apparently.
3420 // More semantic analysis is needed.
3421
3422 // FIXME: the last statement in the compount stmt has its value used. We
3423 // should not warn about it being unused.
3424
3425 // If there are sub stmts in the compound stmt, take the type of the last one
3426 // as the type of the stmtexpr.
3427 QualType Ty = Context.VoidTy;
3428
Chris Lattner200964f2008-07-26 19:51:01 +00003429 if (!Compound->body_empty()) {
3430 Stmt *LastStmt = Compound->body_back();
3431 // If LastStmt is a label, skip down through into the body.
3432 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3433 LastStmt = Label->getSubStmt();
3434
3435 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003436 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003437 }
Chris Lattner4b009652007-07-25 00:24:17 +00003438
3439 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3440}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003441
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003442Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003443 SourceLocation TypeLoc,
3444 TypeTy *argty,
3445 OffsetOfComponent *CompPtr,
3446 unsigned NumComponents,
3447 SourceLocation RPLoc) {
3448 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3449 assert(!ArgTy.isNull() && "Missing type argument!");
3450
3451 // We must have at least one component that refers to the type, and the first
3452 // one is known to be a field designator. Verify that the ArgTy represents
3453 // a struct/union/class.
3454 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003455 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003456
3457 // Otherwise, create a compound literal expression as the base, and
3458 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003459 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003460
Chris Lattnerb37522e2007-08-31 21:49:13 +00003461 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3462 // GCC extension, diagnose them.
3463 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003464 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3465 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003466
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003467 for (unsigned i = 0; i != NumComponents; ++i) {
3468 const OffsetOfComponent &OC = CompPtr[i];
3469 if (OC.isBrackets) {
3470 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003471 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003472 if (!AT) {
3473 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003474 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003475 }
3476
Chris Lattner2af6a802007-08-30 17:59:59 +00003477 // FIXME: C++: Verify that operator[] isn't overloaded.
3478
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003479 // C99 6.5.2.1p1
3480 Expr *Idx = static_cast<Expr*>(OC.U.E);
3481 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003482 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3483 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003484
3485 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3486 continue;
3487 }
3488
3489 const RecordType *RC = Res->getType()->getAsRecordType();
3490 if (!RC) {
3491 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003492 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003493 }
3494
3495 // Get the decl corresponding to this.
3496 RecordDecl *RD = RC->getDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003497 FieldDecl *MemberDecl = 0;
3498 DeclContext::lookup_result Lookup = RD->lookup(Context, OC.U.IdentInfo);
3499 if (Lookup.first != Lookup.second)
3500 MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
3501
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003502 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003503 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3504 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003505
3506 // FIXME: C++: Verify that MemberDecl isn't a static field.
3507 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003508 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3509 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003510 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3511 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003512 }
3513
3514 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3515 BuiltinLoc);
3516}
3517
3518
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003519Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003520 TypeTy *arg1, TypeTy *arg2,
3521 SourceLocation RPLoc) {
3522 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3523 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3524
3525 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3526
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003527 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003528}
3529
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003530Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003531 ExprTy *expr1, ExprTy *expr2,
3532 SourceLocation RPLoc) {
3533 Expr *CondExpr = static_cast<Expr*>(cond);
3534 Expr *LHSExpr = static_cast<Expr*>(expr1);
3535 Expr *RHSExpr = static_cast<Expr*>(expr2);
3536
3537 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3538
3539 // The conditional expression is required to be a constant expression.
3540 llvm::APSInt condEval(32);
3541 SourceLocation ExpLoc;
3542 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003543 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3544 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003545
3546 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3547 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3548 RHSExpr->getType();
3549 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3550}
3551
Steve Naroff52a81c02008-09-03 18:15:37 +00003552//===----------------------------------------------------------------------===//
3553// Clang Extensions.
3554//===----------------------------------------------------------------------===//
3555
3556/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003557void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003558 // Analyze block parameters.
3559 BlockSemaInfo *BSI = new BlockSemaInfo();
3560
3561 // Add BSI to CurBlock.
3562 BSI->PrevBlockInfo = CurBlock;
3563 CurBlock = BSI;
3564
3565 BSI->ReturnType = 0;
3566 BSI->TheScope = BlockScope;
3567
Steve Naroff52059382008-10-10 01:28:17 +00003568 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003569 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003570}
3571
3572void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003573 // Analyze arguments to block.
3574 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3575 "Not a function declarator!");
3576 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3577
Steve Naroff52059382008-10-10 01:28:17 +00003578 CurBlock->hasPrototype = FTI.hasPrototype;
3579 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003580
3581 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3582 // no arguments, not a function that takes a single void argument.
3583 if (FTI.hasPrototype &&
3584 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3585 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3586 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3587 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003588 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003589 } else if (FTI.hasPrototype) {
3590 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003591 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3592 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003593 }
Steve Naroff52059382008-10-10 01:28:17 +00003594 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3595
3596 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3597 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3598 // If this has an identifier, add it to the scope stack.
3599 if ((*AI)->getIdentifier())
3600 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003601}
3602
3603/// ActOnBlockError - If there is an error parsing a block, this callback
3604/// is invoked to pop the information about the block from the action impl.
3605void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3606 // Ensure that CurBlock is deleted.
3607 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3608
3609 // Pop off CurBlock, handle nested blocks.
3610 CurBlock = CurBlock->PrevBlockInfo;
3611
3612 // FIXME: Delete the ParmVarDecl objects as well???
3613
3614}
3615
3616/// ActOnBlockStmtExpr - This is called when the body of a block statement
3617/// literal was successfully completed. ^(int x){...}
3618Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3619 Scope *CurScope) {
3620 // Ensure that CurBlock is deleted.
3621 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3622 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3623
Steve Naroff52059382008-10-10 01:28:17 +00003624 PopDeclContext();
3625
Steve Naroff52a81c02008-09-03 18:15:37 +00003626 // Pop off CurBlock, handle nested blocks.
3627 CurBlock = CurBlock->PrevBlockInfo;
3628
3629 QualType RetTy = Context.VoidTy;
3630 if (BSI->ReturnType)
3631 RetTy = QualType(BSI->ReturnType, 0);
3632
3633 llvm::SmallVector<QualType, 8> ArgTypes;
3634 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3635 ArgTypes.push_back(BSI->Params[i]->getType());
3636
3637 QualType BlockTy;
3638 if (!BSI->hasPrototype)
3639 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3640 else
3641 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003642 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003643
3644 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003645
Steve Naroff95029d92008-10-08 18:44:00 +00003646 BSI->TheDecl->setBody(Body.take());
3647 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003648}
3649
Nate Begemanbd881ef2008-01-30 20:50:20 +00003650/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003651/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003652/// The number of arguments has already been validated to match the number of
3653/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003654static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3655 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003656 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003657 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003658 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3659 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003660
3661 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003662 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003663 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003664 return true;
3665}
3666
3667Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3668 SourceLocation *CommaLocs,
3669 SourceLocation BuiltinLoc,
3670 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003671 // __builtin_overload requires at least 2 arguments
3672 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003673 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3674 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003675
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003676 // The first argument is required to be a constant expression. It tells us
3677 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003678 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003679 Expr *NParamsExpr = Args[0];
3680 llvm::APSInt constEval(32);
3681 SourceLocation ExpLoc;
3682 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003683 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3684 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003685
3686 // Verify that the number of parameters is > 0
3687 unsigned NumParams = constEval.getZExtValue();
3688 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003689 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3690 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003691 // Verify that we have at least 1 + NumParams arguments to the builtin.
3692 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003693 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3694 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003695
3696 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003697 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003698 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003699 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3700 // UsualUnaryConversions will convert the function DeclRefExpr into a
3701 // pointer to function.
3702 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003703 const FunctionTypeProto *FnType = 0;
3704 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3705 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003706
3707 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3708 // parameters, and the number of parameters must match the value passed to
3709 // the builtin.
3710 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003711 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3712 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003713
3714 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003715 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003716 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003717 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003718 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003719 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3720 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003721 // Remember our match, and continue processing the remaining arguments
3722 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003723 OE = new OverloadExpr(Args, NumArgs, i,
3724 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003725 BuiltinLoc, RParenLoc);
3726 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003727 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003728 // Return the newly created OverloadExpr node, if we succeded in matching
3729 // exactly one of the candidate functions.
3730 if (OE)
3731 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003732
3733 // If we didn't find a matching function Expr in the __builtin_overload list
3734 // the return an error.
3735 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003736 for (unsigned i = 0; i != NumParams; ++i) {
3737 if (i != 0) typeNames += ", ";
3738 typeNames += Args[i+1]->getType().getAsString();
3739 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003740
Chris Lattner77d52da2008-11-20 06:06:08 +00003741 return Diag(BuiltinLoc, diag::err_overload_no_match)
3742 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003743}
3744
Anders Carlsson36760332007-10-15 20:28:48 +00003745Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3746 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003747 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003748 Expr *E = static_cast<Expr*>(expr);
3749 QualType T = QualType::getFromOpaquePtr(type);
3750
3751 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003752
3753 // Get the va_list type
3754 QualType VaListType = Context.getBuiltinVaListType();
3755 // Deal with implicit array decay; for example, on x86-64,
3756 // va_list is an array, but it's supposed to decay to
3757 // a pointer for va_arg.
3758 if (VaListType->isArrayType())
3759 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003760 // Make sure the input expression also decays appropriately.
3761 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003762
3763 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003764 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003765 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003766 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003767
3768 // FIXME: Warn if a non-POD type is passed in.
3769
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003770 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003771}
3772
Douglas Gregorad4b3792008-11-29 04:51:27 +00003773Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3774 // The type of __null will be int or long, depending on the size of
3775 // pointers on the target.
3776 QualType Ty;
3777 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3778 Ty = Context.IntTy;
3779 else
3780 Ty = Context.LongTy;
3781
3782 return new GNUNullExpr(Ty, TokenLoc);
3783}
3784
Chris Lattner005ed752008-01-04 18:04:52 +00003785bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3786 SourceLocation Loc,
3787 QualType DstType, QualType SrcType,
3788 Expr *SrcExpr, const char *Flavor) {
3789 // Decode the result (notice that AST's are still created for extensions).
3790 bool isInvalid = false;
3791 unsigned DiagKind;
3792 switch (ConvTy) {
3793 default: assert(0 && "Unknown conversion type");
3794 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003795 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003796 DiagKind = diag::ext_typecheck_convert_pointer_int;
3797 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003798 case IntToPointer:
3799 DiagKind = diag::ext_typecheck_convert_int_pointer;
3800 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003801 case IncompatiblePointer:
3802 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3803 break;
3804 case FunctionVoidPointer:
3805 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3806 break;
3807 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003808 // If the qualifiers lost were because we were applying the
3809 // (deprecated) C++ conversion from a string literal to a char*
3810 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3811 // Ideally, this check would be performed in
3812 // CheckPointerTypesForAssignment. However, that would require a
3813 // bit of refactoring (so that the second argument is an
3814 // expression, rather than a type), which should be done as part
3815 // of a larger effort to fix CheckPointerTypesForAssignment for
3816 // C++ semantics.
3817 if (getLangOptions().CPlusPlus &&
3818 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3819 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003820 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3821 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003822 case IntToBlockPointer:
3823 DiagKind = diag::err_int_to_block_pointer;
3824 break;
3825 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003826 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003827 break;
Steve Naroff19608432008-10-14 22:18:38 +00003828 case IncompatibleObjCQualifiedId:
3829 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3830 // it can give a more specific diagnostic.
3831 DiagKind = diag::warn_incompatible_qualified_id;
3832 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003833 case Incompatible:
3834 DiagKind = diag::err_typecheck_convert_incompatible;
3835 isInvalid = true;
3836 break;
3837 }
3838
Chris Lattner271d4c22008-11-24 05:29:24 +00003839 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3840 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003841 return isInvalid;
3842}
Anders Carlssond5201b92008-11-30 19:50:32 +00003843
3844bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3845{
3846 Expr::EvalResult EvalResult;
3847
3848 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3849 EvalResult.HasSideEffects) {
3850 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3851
3852 if (EvalResult.Diag) {
3853 // We only show the note if it's not the usual "invalid subexpression"
3854 // or if it's actually in a subexpression.
3855 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3856 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3857 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3858 }
3859
3860 return true;
3861 }
3862
3863 if (EvalResult.Diag) {
3864 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3865 E->getSourceRange();
3866
3867 // Print the reason it's not a constant.
3868 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3869 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3870 }
3871
3872 if (Result)
3873 *Result = EvalResult.Val.getInt();
3874 return false;
3875}