blob: 51e4e05eec8fdde4b6c617a40a4934be188e8ea0 [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);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000425 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
426 static_cast<Expr*>(SelfExpr.Val), true, true);
427 Context.setFieldDecl(IFace, IV, MRef);
428 return MRef;
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000429 }
430 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000431 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000432 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000433 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000434 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000435 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000436 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000437 }
Chris Lattner4b009652007-07-25 00:24:17 +0000438 if (D == 0) {
439 // Otherwise, this could be an implicitly declared function reference (legal
440 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000441 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000442 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000443 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000444 else {
445 // If this name wasn't predeclared and if this is not a function call,
446 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000447 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000448 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000449 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000450 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
451 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000453 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000454 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000455 }
456 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000457
Douglas Gregor8acb7272008-12-11 16:49:14 +0000458 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
460 if (MD->isStatic())
461 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000462 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000463 << FD->getDeclName();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000464 if (MD->getParent() != FD->getDeclContext())
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000465 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000466 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000467 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000468
469 if (FD->isInvalidDecl())
470 return true;
471
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000472 // FIXME: Handle 'mutable'.
473 return new DeclRefExpr(FD,
474 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000475 }
476
Chris Lattner271d4c22008-11-24 05:29:24 +0000477 return Diag(Loc, diag::err_invalid_non_static_member_use)
478 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000479 }
Chris Lattner4b009652007-07-25 00:24:17 +0000480 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000481 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000482 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000483 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000484 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000485 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000486
Steve Naroffd6163f32008-09-05 22:11:13 +0000487 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000488 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
489 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
490
Steve Naroffd6163f32008-09-05 22:11:13 +0000491 ValueDecl *VD = cast<ValueDecl>(D);
492
493 // check if referencing an identifier with __attribute__((deprecated)).
494 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000495 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000496
497 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
498 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
499 Scope *CheckS = S;
500 while (CheckS) {
501 if (CheckS->isWithinElse() &&
502 CheckS->getControlParent()->isDeclScope(Var)) {
503 if (Var->getType()->isBooleanType())
504 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
505 else
506 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
507 break;
508 }
509
510 // Move up one more control parent to check again.
511 CheckS = CheckS->getControlParent();
512 if (CheckS)
513 CheckS = CheckS->getParent();
514 }
515 }
516 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000517
518 // Only create DeclRefExpr's for valid Decl's.
519 if (VD->isInvalidDecl())
520 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000521
522 // If the identifier reference is inside a block, and it refers to a value
523 // that is outside the block, create a BlockDeclRefExpr instead of a
524 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
525 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000526 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000527 // We do not do this for things like enum constants, global variables, etc,
528 // as they do not get snapshotted.
529 //
530 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000531 // The BlocksAttr indicates the variable is bound by-reference.
532 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000533 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
534 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000535
536 // Variable will be bound by-copy, make it const within the closure.
537 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000538 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
539 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000540 }
541 // If this reference is not in a block or if the referenced variable is
542 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000543
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000544 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000545 bool ValueDependent = false;
546 if (getLangOptions().CPlusPlus) {
547 // C++ [temp.dep.expr]p3:
548 // An id-expression is type-dependent if it contains:
549 // - an identifier that was declared with a dependent type,
550 if (VD->getType()->isDependentType())
551 TypeDependent = true;
552 // - FIXME: a template-id that is dependent,
553 // - a conversion-function-id that specifies a dependent type,
554 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
555 Name.getCXXNameType()->isDependentType())
556 TypeDependent = true;
557 // - a nested-name-specifier that contains a class-name that
558 // names a dependent type.
559 else if (SS && !SS->isEmpty()) {
560 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
561 DC; DC = DC->getParent()) {
562 // FIXME: could stop early at namespace scope.
563 if (DC->isCXXRecord()) {
564 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
565 if (Context.getTypeDeclType(Record)->isDependentType()) {
566 TypeDependent = true;
567 break;
568 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000569 }
570 }
571 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000572
Douglas Gregora5d84612008-12-10 20:57:37 +0000573 // C++ [temp.dep.constexpr]p2:
574 //
575 // An identifier is value-dependent if it is:
576 // - a name declared with a dependent type,
577 if (TypeDependent)
578 ValueDependent = true;
579 // - the name of a non-type template parameter,
580 else if (isa<NonTypeTemplateParmDecl>(VD))
581 ValueDependent = true;
582 // - a constant with integral or enumeration type and is
583 // initialized with an expression that is value-dependent
584 // (FIXME!).
585 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000586
587 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
588 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000589}
590
Chris Lattner69909292008-08-10 01:53:14 +0000591Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000592 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000593 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000594
595 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000596 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000597 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
598 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
599 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000601
Chris Lattner7e637512008-01-12 08:14:25 +0000602 // Pre-defined identifiers are of type char[x], where x is the length of the
603 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000604 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000605 if (FunctionDecl *FD = getCurFunctionDecl())
606 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000607 else if (ObjCMethodDecl *MD = getCurMethodDecl())
608 Length = MD->getSynthesizedMethodSize();
609 else {
610 Diag(Loc, diag::ext_predef_outside_function);
611 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
612 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
613 }
614
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000615
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000616 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000617 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000618 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000619 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000620}
621
Steve Naroff87d58b42007-09-16 03:34:24 +0000622Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000623 llvm::SmallString<16> CharBuffer;
624 CharBuffer.resize(Tok.getLength());
625 const char *ThisTokBegin = &CharBuffer[0];
626 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
627
628 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
629 Tok.getLocation(), PP);
630 if (Literal.hadError())
631 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000632
633 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
634
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000635 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
636 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000637}
638
Steve Naroff87d58b42007-09-16 03:34:24 +0000639Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000640 // fast path for a single digit (which is quite common). A single digit
641 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
642 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000643 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000644
Chris Lattner8cd0e932008-03-05 18:54:05 +0000645 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000646 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000647 Context.IntTy,
648 Tok.getLocation()));
649 }
650 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000651 // Add padding so that NumericLiteralParser can overread by one character.
652 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000653 const char *ThisTokBegin = &IntegerBuffer[0];
654
655 // Get the spelling of the token, which eliminates trigraphs, etc.
656 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000657
Chris Lattner4b009652007-07-25 00:24:17 +0000658 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
659 Tok.getLocation(), PP);
660 if (Literal.hadError)
661 return ExprResult(true);
662
Chris Lattner1de66eb2007-08-26 03:42:43 +0000663 Expr *Res;
664
665 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000666 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000667 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000668 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000669 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000670 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000671 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000672 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000673
674 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
675
Ted Kremenekddedbe22007-11-29 00:56:49 +0000676 // isExact will be set by GetFloatValue().
677 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000678 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000679 Ty, Tok.getLocation());
680
Chris Lattner1de66eb2007-08-26 03:42:43 +0000681 } else if (!Literal.isIntegerLiteral()) {
682 return ExprResult(true);
683 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000684 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000685
Neil Booth7421e9c2007-08-29 22:00:19 +0000686 // long long is a C99 feature.
687 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000688 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000689 Diag(Tok.getLocation(), diag::ext_longlong);
690
Chris Lattner4b009652007-07-25 00:24:17 +0000691 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000692 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000693
694 if (Literal.GetIntegerValue(ResultVal)) {
695 // If this value didn't fit into uintmax_t, warn and force to ull.
696 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000697 Ty = Context.UnsignedLongLongTy;
698 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000699 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000700 } else {
701 // If this value fits into a ULL, try to figure out what else it fits into
702 // according to the rules of C99 6.4.4.1p5.
703
704 // Octal, Hexadecimal, and integers with a U suffix are allowed to
705 // be an unsigned int.
706 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
707
708 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000709 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000710 if (!Literal.isLong && !Literal.isLongLong) {
711 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000712 unsigned IntSize = Context.Target.getIntWidth();
713
Chris Lattner4b009652007-07-25 00:24:17 +0000714 // Does it fit in a unsigned int?
715 if (ResultVal.isIntN(IntSize)) {
716 // Does it fit in a signed int?
717 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000718 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000719 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000720 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000721 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
Chris Lattner4b009652007-07-25 00:24:17 +0000723 }
724
725 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000726 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000727 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000728
729 // Does it fit in a unsigned long?
730 if (ResultVal.isIntN(LongSize)) {
731 // Does it fit in a signed long?
732 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000733 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000734 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000735 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000736 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000737 }
Chris Lattner4b009652007-07-25 00:24:17 +0000738 }
739
740 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000741 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000742 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000743
744 // Does it fit in a unsigned long long?
745 if (ResultVal.isIntN(LongLongSize)) {
746 // Does it fit in a signed long long?
747 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000748 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000749 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000750 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000751 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000752 }
753 }
754
755 // If we still couldn't decide a type, we probably have something that
756 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000757 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000758 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000759 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000760 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
Chris Lattnere4068872008-05-09 05:59:00 +0000762
763 if (ResultVal.getBitWidth() != Width)
764 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000765 }
766
Chris Lattner48d7f382008-04-02 04:24:33 +0000767 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000768 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000769
770 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
771 if (Literal.isImaginary)
772 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
773
774 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000775}
776
Steve Naroff87d58b42007-09-16 03:34:24 +0000777Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000778 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000779 Expr *E = (Expr *)Val;
780 assert((E != 0) && "ActOnParenExpr() missing expr");
781 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000782}
783
784/// The UsualUnaryConversions() function is *not* called by this routine.
785/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000786bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
787 SourceLocation OpLoc,
788 const SourceRange &ExprRange,
789 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 // C99 6.5.3.4p1:
791 if (isa<FunctionType>(exprType) && isSizeof)
792 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000793 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000794 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000795 Diag(OpLoc, diag::ext_sizeof_void_type)
796 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
797 else if (exprType->isIncompleteType())
798 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
799 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000800 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000801
802 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000803}
804
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000805/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
806/// the same for @c alignof and @c __alignof
807/// Note that the ArgRange is invalid if isType is false.
808Action::ExprResult
809Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
810 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000811 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000812 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000813
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000814 QualType ArgTy;
815 SourceRange Range;
816 if (isType) {
817 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
818 Range = ArgRange;
819 } else {
820 // Get the end location.
821 Expr *ArgEx = (Expr *)TyOrEx;
822 Range = ArgEx->getSourceRange();
823 ArgTy = ArgEx->getType();
824 }
825
826 // Verify that the operand is valid.
827 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000828 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000829
830 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
831 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
832 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000833}
834
Chris Lattner5110ad52007-08-24 21:41:10 +0000835QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000836 DefaultFunctionArrayConversion(V);
837
Chris Lattnera16e42d2007-08-26 05:39:26 +0000838 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000839 if (const ComplexType *CT = V->getType()->getAsComplexType())
840 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000841
842 // Otherwise they pass through real integer and floating point types here.
843 if (V->getType()->isArithmeticType())
844 return V->getType();
845
846 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000847 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000848 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000849}
850
851
Chris Lattner4b009652007-07-25 00:24:17 +0000852
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000853Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000854 tok::TokenKind Kind,
855 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000856 Expr *Arg = (Expr *)Input;
857
Chris Lattner4b009652007-07-25 00:24:17 +0000858 UnaryOperator::Opcode Opc;
859 switch (Kind) {
860 default: assert(0 && "Unknown unary op!");
861 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
862 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
863 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000864
865 if (getLangOptions().CPlusPlus &&
866 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
867 // Which overloaded operator?
868 OverloadedOperatorKind OverOp =
869 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
870
871 // C++ [over.inc]p1:
872 //
873 // [...] If the function is a member function with one
874 // parameter (which shall be of type int) or a non-member
875 // function with two parameters (the second of which shall be
876 // of type int), it defines the postfix increment operator ++
877 // for objects of that type. When the postfix increment is
878 // called as a result of using the ++ operator, the int
879 // argument will have value zero.
880 Expr *Args[2] = {
881 Arg,
882 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
883 /*isSigned=*/true),
884 Context.IntTy, SourceLocation())
885 };
886
887 // Build the candidate set for overloading
888 OverloadCandidateSet CandidateSet;
889 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
890
891 // Perform overload resolution.
892 OverloadCandidateSet::iterator Best;
893 switch (BestViableFunction(CandidateSet, Best)) {
894 case OR_Success: {
895 // We found a built-in operator or an overloaded operator.
896 FunctionDecl *FnDecl = Best->Function;
897
898 if (FnDecl) {
899 // We matched an overloaded operator. Build a call to that
900 // operator.
901
902 // Convert the arguments.
903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
904 if (PerformObjectArgumentInitialization(Arg, Method))
905 return true;
906 } else {
907 // Convert the arguments.
908 if (PerformCopyInitialization(Arg,
909 FnDecl->getParamDecl(0)->getType(),
910 "passing"))
911 return true;
912 }
913
914 // Determine the result type
915 QualType ResultTy
916 = FnDecl->getType()->getAsFunctionType()->getResultType();
917 ResultTy = ResultTy.getNonReferenceType();
918
919 // Build the actual expression node.
920 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
921 SourceLocation());
922 UsualUnaryConversions(FnExpr);
923
924 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
925 } else {
926 // We matched a built-in operator. Convert the arguments, then
927 // break out so that we will build the appropriate built-in
928 // operator node.
929 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
930 "passing"))
931 return true;
932
933 break;
934 }
935 }
936
937 case OR_No_Viable_Function:
938 // No viable function; fall through to handling this as a
939 // built-in operator, which will produce an error message for us.
940 break;
941
942 case OR_Ambiguous:
943 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
944 << UnaryOperator::getOpcodeStr(Opc)
945 << Arg->getSourceRange();
946 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
947 return true;
948 }
949
950 // Either we found no viable overloaded operator or we matched a
951 // built-in operator. In either case, fall through to trying to
952 // build a built-in operation.
953 }
954
Sebastian Redl0440c8c2008-12-20 09:35:34 +0000955 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
956 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +0000957 if (result.isNull())
958 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000959 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000960}
961
962Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000963ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000964 ExprTy *Idx, SourceLocation RLoc) {
965 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
966
Douglas Gregor80723c52008-11-19 17:17:41 +0000967 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +0000968 (LHSExp->getType()->isRecordType() ||
969 LHSExp->getType()->isEnumeralType() ||
970 RHSExp->getType()->isRecordType() ||
971 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000972 // Add the appropriate overloaded operators (C++ [over.match.oper])
973 // to the candidate set.
974 OverloadCandidateSet CandidateSet;
975 Expr *Args[2] = { LHSExp, RHSExp };
976 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
977
978 // Perform overload resolution.
979 OverloadCandidateSet::iterator Best;
980 switch (BestViableFunction(CandidateSet, Best)) {
981 case OR_Success: {
982 // We found a built-in operator or an overloaded operator.
983 FunctionDecl *FnDecl = Best->Function;
984
985 if (FnDecl) {
986 // We matched an overloaded operator. Build a call to that
987 // operator.
988
989 // Convert the arguments.
990 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
991 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
992 PerformCopyInitialization(RHSExp,
993 FnDecl->getParamDecl(0)->getType(),
994 "passing"))
995 return true;
996 } else {
997 // Convert the arguments.
998 if (PerformCopyInitialization(LHSExp,
999 FnDecl->getParamDecl(0)->getType(),
1000 "passing") ||
1001 PerformCopyInitialization(RHSExp,
1002 FnDecl->getParamDecl(1)->getType(),
1003 "passing"))
1004 return true;
1005 }
1006
1007 // Determine the result type
1008 QualType ResultTy
1009 = FnDecl->getType()->getAsFunctionType()->getResultType();
1010 ResultTy = ResultTy.getNonReferenceType();
1011
1012 // Build the actual expression node.
1013 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1014 SourceLocation());
1015 UsualUnaryConversions(FnExpr);
1016
1017 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1018 } else {
1019 // We matched a built-in operator. Convert the arguments, then
1020 // break out so that we will build the appropriate built-in
1021 // operator node.
1022 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1023 "passing") ||
1024 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1025 "passing"))
1026 return true;
1027
1028 break;
1029 }
1030 }
1031
1032 case OR_No_Viable_Function:
1033 // No viable function; fall through to handling this as a
1034 // built-in operator, which will produce an error message for us.
1035 break;
1036
1037 case OR_Ambiguous:
1038 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1039 << "[]"
1040 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1041 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1042 return true;
1043 }
1044
1045 // Either we found no viable overloaded operator or we matched a
1046 // built-in operator. In either case, fall through to trying to
1047 // build a built-in operation.
1048 }
1049
Chris Lattner4b009652007-07-25 00:24:17 +00001050 // Perform default conversions.
1051 DefaultFunctionArrayConversion(LHSExp);
1052 DefaultFunctionArrayConversion(RHSExp);
1053
1054 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1055
1056 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001057 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // in the subscript position. As a result, we need to derive the array base
1059 // and index from the expression types.
1060 Expr *BaseExpr, *IndexExpr;
1061 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001062 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001063 BaseExpr = LHSExp;
1064 IndexExpr = RHSExp;
1065 // FIXME: need to deal with const...
1066 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001067 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001068 // Handle the uncommon case of "123[Ptr]".
1069 BaseExpr = RHSExp;
1070 IndexExpr = LHSExp;
1071 // FIXME: need to deal with const...
1072 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001073 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1074 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001075 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001076
1077 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001078 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1079 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001080 return Diag(LLoc, diag::err_ext_vector_component_access)
1081 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001082 // FIXME: need to deal with const...
1083 ResultType = VTy->getElementType();
1084 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001085 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1086 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001087 }
1088 // C99 6.5.2.1p1
1089 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001090 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1091 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001092
1093 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1094 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001095 // void (*)(int)) and pointers to incomplete types. Functions are not
1096 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001097 if (!ResultType->isObjectType())
1098 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001099 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001100 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001101
1102 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1103}
1104
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001105QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001106CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001107 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001108 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001109
1110 // This flag determines whether or not the component is to be treated as a
1111 // special name, or a regular GLSL-style component access.
1112 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001113
1114 // The vector accessor can't exceed the number of elements.
1115 const char *compStr = CompName.getName();
1116 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001117 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001118 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001119 return QualType();
1120 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001121
1122 // Check that we've found one of the special components, or that the component
1123 // names must come from the same set.
1124 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1125 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1126 SpecialComponent = true;
1127 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001128 do
1129 compStr++;
1130 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1131 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1132 do
1133 compStr++;
1134 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1135 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1136 do
1137 compStr++;
1138 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1139 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001140
Nate Begemanc8e51f82008-05-09 06:41:27 +00001141 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001142 // We didn't get to the end of the string. This means the component names
1143 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001144 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1145 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001146 return QualType();
1147 }
1148 // Each component accessor can't exceed the vector type.
1149 compStr = CompName.getName();
1150 while (*compStr) {
1151 if (vecType->isAccessorWithinNumElements(*compStr))
1152 compStr++;
1153 else
1154 break;
1155 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001156 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001157 // We didn't get to the end of the string. This means a component accessor
1158 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001159 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001160 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001161 return QualType();
1162 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001163
1164 // If we have a special component name, verify that the current vector length
1165 // is an even number, since all special component names return exactly half
1166 // the elements.
1167 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001168 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001169 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001170 return QualType();
1171 }
1172
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001173 // The component accessor looks fine - now we need to compute the actual type.
1174 // The vector type is implied by the component accessor. For example,
1175 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001176 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1177 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001178 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001179 if (CompSize == 1)
1180 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001181
Nate Begemanaf6ed502008-04-18 23:10:10 +00001182 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001183 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001184 // diagostics look bad. We want extended vector types to appear built-in.
1185 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1186 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1187 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001188 }
1189 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001190}
1191
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001192/// constructSetterName - Return the setter name for the given
1193/// identifier, i.e. "set" + Name where the initial character of Name
1194/// has been capitalized.
1195// FIXME: Merge with same routine in Parser. But where should this
1196// live?
1197static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1198 const IdentifierInfo *Name) {
1199 llvm::SmallString<100> SelectorName;
1200 SelectorName = "set";
1201 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1202 SelectorName[3] = toupper(SelectorName[3]);
1203 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1204}
1205
Chris Lattner4b009652007-07-25 00:24:17 +00001206Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001207ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001208 tok::TokenKind OpKind, SourceLocation MemberLoc,
1209 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001210 Expr *BaseExpr = static_cast<Expr *>(Base);
1211 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001212
1213 // Perform default conversions.
1214 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001215
Steve Naroff2cb66382007-07-26 03:11:44 +00001216 QualType BaseType = BaseExpr->getType();
1217 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001218
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001219 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1220 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001221 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001222 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001223 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001224 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1225 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001226 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001227 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001228 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001229 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001230
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001231 // Handle field access to simple records. This also handles access to fields
1232 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001233 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001234 RecordDecl *RDecl = RTy->getDecl();
1235 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001236 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001237 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001238 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001239 // FIXME: Qualified name lookup for C++ is a bit more complicated
1240 // than this.
1241 DeclContext::lookup_result Lookup = RDecl->lookup(Context, &Member);
1242 if (Lookup.first == Lookup.second) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001243 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001244 << &Member << BaseExpr->getSourceRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001245 }
1246
1247 FieldDecl *MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
1248 if (!MemberDecl) {
1249 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
1250 "Clang only supports references to members");
1251 return Diag(MemberLoc, DiagID);
1252 }
Eli Friedman76b49832008-02-06 22:48:16 +00001253
1254 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001255 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001256 QualType MemberType = MemberDecl->getType();
1257 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001258 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001259 if (MemberDecl->isMutable())
1260 combinedQualifiers &= ~QualType::Const;
Eli Friedman76b49832008-02-06 22:48:16 +00001261 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1262
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001263 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001264 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001265 }
1266
Chris Lattnere9d71612008-07-21 04:59:05 +00001267 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1268 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001269 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001270 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001271 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1272 BaseExpr,
1273 OpKind == tok::arrow);
1274 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1275 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001276 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001277 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001278 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001279 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001280 }
1281
Chris Lattnere9d71612008-07-21 04:59:05 +00001282 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1283 // pointer to a (potentially qualified) interface type.
1284 const PointerType *PTy;
1285 const ObjCInterfaceType *IFTy;
1286 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1287 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1288 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001289
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001290 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001291 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1292 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1293
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001294 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001295 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1296 E = IFTy->qual_end(); I != E; ++I)
1297 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1298 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001299
1300 // If that failed, look for an "implicit" property by seeing if the nullary
1301 // selector is implemented.
1302
1303 // FIXME: The logic for looking up nullary and unary selectors should be
1304 // shared with the code in ActOnInstanceMessage.
1305
1306 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1307 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1308
1309 // If this reference is in an @implementation, check for 'private' methods.
1310 if (!Getter)
1311 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1312 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1313 if (ObjCImplementationDecl *ImpDecl =
1314 ObjCImplementations[ClassDecl->getIdentifier()])
1315 Getter = ImpDecl->getInstanceMethod(Sel);
1316
Steve Naroff04151f32008-10-22 19:16:27 +00001317 // Look through local category implementations associated with the class.
1318 if (!Getter) {
1319 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1320 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1321 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1322 }
1323 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001324 if (Getter) {
1325 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001326 // will look for the matching setter, in case it is needed.
1327 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1328 &Member);
1329 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1330 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1331 if (!Setter) {
1332 // If this reference is in an @implementation, also check for 'private'
1333 // methods.
1334 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1335 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1336 if (ObjCImplementationDecl *ImpDecl =
1337 ObjCImplementations[ClassDecl->getIdentifier()])
1338 Setter = ImpDecl->getInstanceMethod(SetterSel);
1339 }
1340 // Look through local category implementations associated with the class.
1341 if (!Setter) {
1342 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1343 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1344 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1345 }
1346 }
1347
1348 // FIXME: we must check that the setter has property type.
1349 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001350 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001351 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001352
1353 return Diag(MemberLoc, diag::err_property_not_found) <<
1354 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001355 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001356 // Handle properties on qualified "id" protocols.
1357 const ObjCQualifiedIdType *QIdTy;
1358 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1359 // Check protocols on qualified interfaces.
1360 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001361 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001362 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1363 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001364 // Also must look for a getter name which uses property syntax.
1365 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1366 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1367 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1368 OpLoc, MemberLoc, NULL, 0);
1369 }
1370 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001371
1372 return Diag(MemberLoc, diag::err_property_not_found) <<
1373 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001374 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001375 // Handle 'field access' to vectors, such as 'V.xx'.
1376 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1377 // Component access limited to variables (reject vec4.rg.g).
1378 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1379 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001380 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1381 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001382 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1383 if (ret.isNull())
1384 return true;
1385 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1386 }
1387
Chris Lattner8ba580c2008-11-19 05:08:23 +00001388 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001389 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001390}
1391
Steve Naroff87d58b42007-09-16 03:34:24 +00001392/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001393/// This provides the location of the left/right parens and a list of comma
1394/// locations.
1395Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001396ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001397 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001398 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1399 Expr *Fn = static_cast<Expr *>(fn);
1400 Expr **Args = reinterpret_cast<Expr**>(args);
1401 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001402 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001403 OverloadedFunctionDecl *Ovl = NULL;
1404
Douglas Gregora133e262008-12-06 00:22:45 +00001405 // Determine whether this is a dependent call inside a C++ template,
1406 // in which case we won't do any semantic analysis now.
1407 bool Dependent = false;
1408 if (Fn->isTypeDependent()) {
1409 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1410 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1411 Dependent = true;
1412 else {
1413 // Resolve the CXXDependentNameExpr to an actual identifier;
1414 // it wasn't really a dependent name after all.
1415 ExprResult Resolved
1416 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1417 /*HasTrailingLParen=*/true,
1418 /*SS=*/0,
1419 /*ForceResolution=*/true);
1420 if (Resolved.isInvalid)
1421 return true;
1422 else {
1423 delete Fn;
1424 Fn = (Expr *)Resolved.Val;
1425 }
1426 }
1427 } else
1428 Dependent = true;
1429 } else
1430 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1431
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001432 // FIXME: Will need to cache the results of name lookup (including
1433 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001434 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001435 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1436
Douglas Gregord2baafd2008-10-21 16:13:35 +00001437 // If we're directly calling a function or a set of overloaded
1438 // functions, get the appropriate declaration.
1439 {
1440 DeclRefExpr *DRExpr = NULL;
1441 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1442 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1443 else
1444 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1445
1446 if (DRExpr) {
1447 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1448 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1449 }
1450 }
1451
Douglas Gregord2baafd2008-10-21 16:13:35 +00001452 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001453 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1454 RParenLoc);
1455 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001456 return true;
1457
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001458 // Update Fn to refer to the actual function selected.
1459 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1460 Fn->getSourceRange().getBegin());
1461 Fn->Destroy(Context);
1462 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001463 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001464
Douglas Gregor10f3c502008-11-19 21:05:33 +00001465 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001466 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001467 CommaLocs, RParenLoc);
1468
Chris Lattner3e254fb2008-04-08 04:40:51 +00001469 // Promote the function operand.
1470 UsualUnaryConversions(Fn);
1471
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001472 // Make the call expr early, before semantic checks. This guarantees cleanup
1473 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001474 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001475 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001476
Steve Naroffd6163f32008-09-05 22:11:13 +00001477 const FunctionType *FuncT;
1478 if (!Fn->getType()->isBlockPointerType()) {
1479 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1480 // have type pointer to function".
1481 const PointerType *PT = Fn->getType()->getAsPointerType();
1482 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001483 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001484 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001485 FuncT = PT->getPointeeType()->getAsFunctionType();
1486 } else { // This is a block call.
1487 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1488 getAsFunctionType();
1489 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001490 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001491 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001492 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001493
1494 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001495 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001496
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001497 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001498 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1499 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001500 unsigned NumArgsInProto = Proto->getNumArgs();
1501 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001502
Chris Lattner3e254fb2008-04-08 04:40:51 +00001503 // If too few arguments are available (and we don't have default
1504 // arguments for the remaining parameters), don't make the call.
1505 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001506 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1507 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1508 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1509 // Use default arguments for missing arguments
1510 NumArgsToCheck = NumArgsInProto;
1511 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001512 }
1513
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001514 // If too many are passed and not variadic, error on the extras and drop
1515 // them.
1516 if (NumArgs > NumArgsInProto) {
1517 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001518 Diag(Args[NumArgsInProto]->getLocStart(),
1519 diag::err_typecheck_call_too_many_args)
1520 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001521 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1522 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001523 // This deletes the extra arguments.
1524 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001525 }
1526 NumArgsToCheck = NumArgsInProto;
1527 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001528
Chris Lattner4b009652007-07-25 00:24:17 +00001529 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001530 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001531 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001532
1533 Expr *Arg;
1534 if (i < NumArgs)
1535 Arg = Args[i];
1536 else
1537 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001538 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001539
Douglas Gregor81c29152008-10-29 00:13:59 +00001540 // Pass the argument.
1541 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001542 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001543
1544 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001546
1547 // If this is a variadic call, handle args passed through "...".
1548 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001549 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001550 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1551 Expr *Arg = Args[i];
1552 DefaultArgumentPromotion(Arg);
1553 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001554 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001555 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001556 } else {
1557 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1558
Steve Naroffdb65e052007-08-28 23:30:39 +00001559 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001560 for (unsigned i = 0; i != NumArgs; i++) {
1561 Expr *Arg = Args[i];
1562 DefaultArgumentPromotion(Arg);
1563 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001564 }
Chris Lattner4b009652007-07-25 00:24:17 +00001565 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001566
Chris Lattner2e64c072007-08-10 20:18:51 +00001567 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001568 if (FDecl)
1569 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001570
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001571 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001572}
1573
1574Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001575ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001576 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001577 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001578 QualType literalType = QualType::getFromOpaquePtr(Ty);
1579 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001580 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001581 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001582
Eli Friedman8c2173d2008-05-20 05:22:08 +00001583 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001584 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001585 return Diag(LParenLoc, diag::err_variable_object_no_init)
1586 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001587 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001588 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001589 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001590 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001591 }
1592
Douglas Gregor6428e762008-11-05 15:29:30 +00001593 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001594 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001595 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001596
Chris Lattnere5cb5862008-12-04 23:50:19 +00001597 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001598 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001599 if (CheckForConstantInitializer(literalExpr, literalType))
1600 return true;
1601 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001602 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1603 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001604}
1605
1606Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001607ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001608 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001609 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001610 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001611
Steve Naroff0acc9c92007-09-15 18:49:24 +00001612 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001613 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001614
Chris Lattner71ca8c82008-10-26 23:43:26 +00001615 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1616 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001617 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1618 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001619}
1620
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001621/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001622bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001623 UsualUnaryConversions(castExpr);
1624
1625 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1626 // type needs to be scalar.
1627 if (castType->isVoidType()) {
1628 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001629 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1630 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001631 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1632 // GCC struct/union extension: allow cast to self.
1633 if (Context.getCanonicalType(castType) !=
1634 Context.getCanonicalType(castExpr->getType()) ||
1635 (!castType->isStructureType() && !castType->isUnionType())) {
1636 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001637 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001638 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001639 }
1640
1641 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001642 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001643 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001644 } else if (!castExpr->getType()->isScalarType() &&
1645 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001646 return Diag(castExpr->getLocStart(),
1647 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001648 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001649 } else if (castExpr->getType()->isVectorType()) {
1650 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1651 return true;
1652 } else if (castType->isVectorType()) {
1653 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1654 return true;
1655 }
1656 return false;
1657}
1658
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001659bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001660 assert(VectorTy->isVectorType() && "Not a vector type!");
1661
1662 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001663 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001664 return Diag(R.getBegin(),
1665 Ty->isVectorType() ?
1666 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001667 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001668 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001669 } else
1670 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001671 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001672 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001673
1674 return false;
1675}
1676
Chris Lattner4b009652007-07-25 00:24:17 +00001677Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001678ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001679 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001680 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001681
1682 Expr *castExpr = static_cast<Expr*>(Op);
1683 QualType castType = QualType::getFromOpaquePtr(Ty);
1684
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001685 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1686 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001687 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001688}
1689
Chris Lattner98a425c2007-11-26 01:40:58 +00001690/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1691/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001692inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1693 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1694 UsualUnaryConversions(cond);
1695 UsualUnaryConversions(lex);
1696 UsualUnaryConversions(rex);
1697 QualType condT = cond->getType();
1698 QualType lexT = lex->getType();
1699 QualType rexT = rex->getType();
1700
1701 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001702 if (!cond->isTypeDependent()) {
1703 if (!condT->isScalarType()) { // C99 6.5.15p2
1704 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1705 return QualType();
1706 }
Chris Lattner4b009652007-07-25 00:24:17 +00001707 }
Chris Lattner992ae932008-01-06 22:42:25 +00001708
1709 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001710 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1711 return Context.DependentTy;
1712
Chris Lattner992ae932008-01-06 22:42:25 +00001713 // If both operands have arithmetic type, do the usual arithmetic conversions
1714 // to find a common type: C99 6.5.15p3,5.
1715 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001716 UsualArithmeticConversions(lex, rex);
1717 return lex->getType();
1718 }
Chris Lattner992ae932008-01-06 22:42:25 +00001719
1720 // If both operands are the same structure or union type, the result is that
1721 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001722 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001723 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001724 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001725 // "If both the operands have structure or union type, the result has
1726 // that type." This implies that CV qualifiers are dropped.
1727 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001728 }
Chris Lattner992ae932008-01-06 22:42:25 +00001729
1730 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001731 // The following || allows only one side to be void (a GCC-ism).
1732 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001733 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001734 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1735 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001736 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001737 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1738 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001739 ImpCastExprToType(lex, Context.VoidTy);
1740 ImpCastExprToType(rex, Context.VoidTy);
1741 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001742 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001743 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1744 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001745 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1746 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001747 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001748 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001749 return lexT;
1750 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001751 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1752 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001753 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001754 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001755 return rexT;
1756 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001757 // Handle the case where both operands are pointers before we handle null
1758 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001759 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1760 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1761 // get the "pointed to" types
1762 QualType lhptee = LHSPT->getPointeeType();
1763 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001764
Chris Lattner71225142007-07-31 21:27:01 +00001765 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1766 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001767 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001768 // Figure out necessary qualifiers (C99 6.5.15p6)
1769 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001770 QualType destType = Context.getPointerType(destPointee);
1771 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1772 ImpCastExprToType(rex, destType); // promote to void*
1773 return destType;
1774 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001775 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001776 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001777 QualType destType = Context.getPointerType(destPointee);
1778 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1779 ImpCastExprToType(rex, destType); // promote to void*
1780 return destType;
1781 }
Chris Lattner4b009652007-07-25 00:24:17 +00001782
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001783 QualType compositeType = lexT;
1784
1785 // If either type is an Objective-C object type then check
1786 // compatibility according to Objective-C.
1787 if (Context.isObjCObjectPointerType(lexT) ||
1788 Context.isObjCObjectPointerType(rexT)) {
1789 // If both operands are interfaces and either operand can be
1790 // assigned to the other, use that type as the composite
1791 // type. This allows
1792 // xxx ? (A*) a : (B*) b
1793 // where B is a subclass of A.
1794 //
1795 // Additionally, as for assignment, if either type is 'id'
1796 // allow silent coercion. Finally, if the types are
1797 // incompatible then make sure to use 'id' as the composite
1798 // type so the result is acceptable for sending messages to.
1799
1800 // FIXME: This code should not be localized to here. Also this
1801 // should use a compatible check instead of abusing the
1802 // canAssignObjCInterfaces code.
1803 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1804 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1805 if (LHSIface && RHSIface &&
1806 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1807 compositeType = lexT;
1808 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001809 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001810 compositeType = rexT;
1811 } else if (Context.isObjCIdType(lhptee) ||
1812 Context.isObjCIdType(rhptee)) {
1813 // FIXME: This code looks wrong, because isObjCIdType checks
1814 // the struct but getObjCIdType returns the pointer to
1815 // struct. This is horrible and should be fixed.
1816 compositeType = Context.getObjCIdType();
1817 } else {
1818 QualType incompatTy = Context.getObjCIdType();
1819 ImpCastExprToType(lex, incompatTy);
1820 ImpCastExprToType(rex, incompatTy);
1821 return incompatTy;
1822 }
1823 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1824 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001825 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001826 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001827 // In this situation, we assume void* type. No especially good
1828 // reason, but this is what gcc does, and we do have to pick
1829 // to get a consistent AST.
1830 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001831 ImpCastExprToType(lex, incompatTy);
1832 ImpCastExprToType(rex, incompatTy);
1833 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001834 }
1835 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001836 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1837 // differently qualified versions of compatible types, the result type is
1838 // a pointer to an appropriately qualified version of the *composite*
1839 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001840 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001841 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001842 ImpCastExprToType(lex, compositeType);
1843 ImpCastExprToType(rex, compositeType);
1844 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001845 }
Chris Lattner4b009652007-07-25 00:24:17 +00001846 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001847 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1848 // evaluates to "struct objc_object *" (and is handled above when comparing
1849 // id with statically typed objects).
1850 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1851 // GCC allows qualified id and any Objective-C type to devolve to
1852 // id. Currently localizing to here until clear this should be
1853 // part of ObjCQualifiedIdTypesAreCompatible.
1854 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1855 (lexT->isObjCQualifiedIdType() &&
1856 Context.isObjCObjectPointerType(rexT)) ||
1857 (rexT->isObjCQualifiedIdType() &&
1858 Context.isObjCObjectPointerType(lexT))) {
1859 // FIXME: This is not the correct composite type. This only
1860 // happens to work because id can more or less be used anywhere,
1861 // however this may change the type of method sends.
1862 // FIXME: gcc adds some type-checking of the arguments and emits
1863 // (confusing) incompatible comparison warnings in some
1864 // cases. Investigate.
1865 QualType compositeType = Context.getObjCIdType();
1866 ImpCastExprToType(lex, compositeType);
1867 ImpCastExprToType(rex, compositeType);
1868 return compositeType;
1869 }
1870 }
1871
Steve Naroff3eac7692008-09-10 19:17:48 +00001872 // Selection between block pointer types is ok as long as they are the same.
1873 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1874 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1875 return lexT;
1876
Chris Lattner992ae932008-01-06 22:42:25 +00001877 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001878 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001879 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001880 return QualType();
1881}
1882
Steve Naroff87d58b42007-09-16 03:34:24 +00001883/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001884/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001885Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001886 SourceLocation ColonLoc,
1887 ExprTy *Cond, ExprTy *LHS,
1888 ExprTy *RHS) {
1889 Expr *CondExpr = (Expr *) Cond;
1890 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001891
1892 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1893 // was the condition.
1894 bool isLHSNull = LHSExpr == 0;
1895 if (isLHSNull)
1896 LHSExpr = CondExpr;
1897
Chris Lattner4b009652007-07-25 00:24:17 +00001898 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1899 RHSExpr, QuestionLoc);
1900 if (result.isNull())
1901 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001902 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1903 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001904}
1905
Chris Lattner4b009652007-07-25 00:24:17 +00001906
1907// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1908// being closely modeled after the C99 spec:-). The odd characteristic of this
1909// routine is it effectively iqnores the qualifiers on the top level pointee.
1910// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1911// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001912Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001913Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1914 QualType lhptee, rhptee;
1915
1916 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001917 lhptee = lhsType->getAsPointerType()->getPointeeType();
1918 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001919
1920 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001921 lhptee = Context.getCanonicalType(lhptee);
1922 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001923
Chris Lattner005ed752008-01-04 18:04:52 +00001924 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001925
1926 // C99 6.5.16.1p1: This following citation is common to constraints
1927 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1928 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001929 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001930 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001931 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001932
1933 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1934 // incomplete type and the other is a pointer to a qualified or unqualified
1935 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001936 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001937 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001938 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001939
1940 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001941 assert(rhptee->isFunctionType());
1942 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001943 }
1944
1945 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001946 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001947 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001948
1949 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001950 assert(lhptee->isFunctionType());
1951 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001952 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001953
1954 // Check for ObjC interfaces
1955 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1956 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1957 if (LHSIface && RHSIface &&
1958 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1959 return ConvTy;
1960
1961 // ID acts sort of like void* for ObjC interfaces
1962 if (LHSIface && Context.isObjCIdType(rhptee))
1963 return ConvTy;
1964 if (RHSIface && Context.isObjCIdType(lhptee))
1965 return ConvTy;
1966
Chris Lattner4b009652007-07-25 00:24:17 +00001967 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1968 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001969 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1970 rhptee.getUnqualifiedType()))
1971 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001972 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001973}
1974
Steve Naroff3454b6c2008-09-04 15:10:53 +00001975/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1976/// block pointer types are compatible or whether a block and normal pointer
1977/// are compatible. It is more restrict than comparing two function pointer
1978// types.
1979Sema::AssignConvertType
1980Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1981 QualType rhsType) {
1982 QualType lhptee, rhptee;
1983
1984 // get the "pointed to" type (ignoring qualifiers at the top level)
1985 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1986 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1987
1988 // make sure we operate on the canonical type
1989 lhptee = Context.getCanonicalType(lhptee);
1990 rhptee = Context.getCanonicalType(rhptee);
1991
1992 AssignConvertType ConvTy = Compatible;
1993
1994 // For blocks we enforce that qualifiers are identical.
1995 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1996 ConvTy = CompatiblePointerDiscardsQualifiers;
1997
1998 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1999 return IncompatibleBlockPointer;
2000 return ConvTy;
2001}
2002
Chris Lattner4b009652007-07-25 00:24:17 +00002003/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2004/// has code to accommodate several GCC extensions when type checking
2005/// pointers. Here are some objectionable examples that GCC considers warnings:
2006///
2007/// int a, *pint;
2008/// short *pshort;
2009/// struct foo *pfoo;
2010///
2011/// pint = pshort; // warning: assignment from incompatible pointer type
2012/// a = pint; // warning: assignment makes integer from pointer without a cast
2013/// pint = a; // warning: assignment makes pointer from integer without a cast
2014/// pint = pfoo; // warning: assignment from incompatible pointer type
2015///
2016/// As a result, the code for dealing with pointers is more complex than the
2017/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002018///
Chris Lattner005ed752008-01-04 18:04:52 +00002019Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002020Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002021 // Get canonical types. We're not formatting these types, just comparing
2022 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002023 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2024 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002025
2026 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002027 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002028
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002029 // If the left-hand side is a reference type, then we are in a
2030 // (rare!) case where we've allowed the use of references in C,
2031 // e.g., as a parameter type in a built-in function. In this case,
2032 // just make sure that the type referenced is compatible with the
2033 // right-hand side type. The caller is responsible for adjusting
2034 // lhsType so that the resulting expression does not have reference
2035 // type.
2036 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2037 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002038 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002039 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002040 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002041
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002042 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2043 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002044 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002045 // Relax integer conversions like we do for pointers below.
2046 if (rhsType->isIntegerType())
2047 return IntToPointer;
2048 if (lhsType->isIntegerType())
2049 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002050 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002051 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002052
Nate Begemanc5f0f652008-07-14 18:02:46 +00002053 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002054 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002055 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2056 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002057 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002058
Nate Begemanc5f0f652008-07-14 18:02:46 +00002059 // If we are allowing lax vector conversions, and LHS and RHS are both
2060 // vectors, the total size only needs to be the same. This is a bitcast;
2061 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002062 if (getLangOptions().LaxVectorConversions &&
2063 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002064 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2065 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002066 }
2067 return Incompatible;
2068 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002069
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002070 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002071 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002072
Chris Lattner390564e2008-04-07 06:49:41 +00002073 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002074 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002075 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002076
Chris Lattner390564e2008-04-07 06:49:41 +00002077 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002078 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002079
Steve Naroffa982c712008-09-29 18:10:17 +00002080 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002081 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002082 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002083
2084 // Treat block pointers as objects.
2085 if (getLangOptions().ObjC1 &&
2086 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2087 return Compatible;
2088 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002089 return Incompatible;
2090 }
2091
2092 if (isa<BlockPointerType>(lhsType)) {
2093 if (rhsType->isIntegerType())
2094 return IntToPointer;
2095
Steve Naroffa982c712008-09-29 18:10:17 +00002096 // Treat block pointers as objects.
2097 if (getLangOptions().ObjC1 &&
2098 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2099 return Compatible;
2100
Steve Naroff3454b6c2008-09-04 15:10:53 +00002101 if (rhsType->isBlockPointerType())
2102 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2103
2104 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2105 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002106 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002107 }
Chris Lattner1853da22008-01-04 23:18:45 +00002108 return Incompatible;
2109 }
2110
Chris Lattner390564e2008-04-07 06:49:41 +00002111 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002112 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002113 if (lhsType == Context.BoolTy)
2114 return Compatible;
2115
2116 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002117 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002118
Chris Lattner390564e2008-04-07 06:49:41 +00002119 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002120 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002121
2122 if (isa<BlockPointerType>(lhsType) &&
2123 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002124 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002125 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002126 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002127
Chris Lattner1853da22008-01-04 23:18:45 +00002128 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002129 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002130 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002131 }
2132 return Incompatible;
2133}
2134
Chris Lattner005ed752008-01-04 18:04:52 +00002135Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002136Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002137 if (getLangOptions().CPlusPlus) {
2138 if (!lhsType->isRecordType()) {
2139 // C++ 5.17p3: If the left operand is not of class type, the
2140 // expression is implicitly converted (C++ 4) to the
2141 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002142 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2143 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002144 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002145 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002146 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002147 }
2148
2149 // FIXME: Currently, we fall through and treat C++ classes like C
2150 // structures.
2151 }
2152
Steve Naroffcdee22d2007-11-27 17:58:44 +00002153 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2154 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002155 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2156 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002157 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002158 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002159 return Compatible;
2160 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002161
2162 // We don't allow conversion of non-null-pointer constants to integers.
2163 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2164 return IntToBlockPointer;
2165
Chris Lattner5f505bf2007-10-16 02:55:40 +00002166 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002167 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002168 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002169 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002170 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002171 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002172 if (!lhsType->isReferenceType())
2173 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002174
Chris Lattner005ed752008-01-04 18:04:52 +00002175 Sema::AssignConvertType result =
2176 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002177
2178 // C99 6.5.16.1p2: The value of the right operand is converted to the
2179 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002180 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2181 // so that we can use references in built-in functions even in C.
2182 // The getNonReferenceType() call makes sure that the resulting expression
2183 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002184 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002185 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002186 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002187}
2188
Chris Lattner005ed752008-01-04 18:04:52 +00002189Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002190Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2191 return CheckAssignmentConstraints(lhsType, rhsType);
2192}
2193
Chris Lattner1eafdea2008-11-18 01:30:42 +00002194QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002195 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002196 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002197 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002198 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002199}
2200
Chris Lattner1eafdea2008-11-18 01:30:42 +00002201inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002202 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002203 // For conversion purposes, we ignore any qualifiers.
2204 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002205 QualType lhsType =
2206 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2207 QualType rhsType =
2208 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002209
Nate Begemanc5f0f652008-07-14 18:02:46 +00002210 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002211 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002212 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002213
Nate Begemanc5f0f652008-07-14 18:02:46 +00002214 // Handle the case of a vector & extvector type of the same size and element
2215 // type. It would be nice if we only had one vector type someday.
2216 if (getLangOptions().LaxVectorConversions)
2217 if (const VectorType *LV = lhsType->getAsVectorType())
2218 if (const VectorType *RV = rhsType->getAsVectorType())
2219 if (LV->getElementType() == RV->getElementType() &&
2220 LV->getNumElements() == RV->getNumElements())
2221 return lhsType->isExtVectorType() ? lhsType : rhsType;
2222
2223 // If the lhs is an extended vector and the rhs is a scalar of the same type
2224 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002225 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002226 QualType eltType = V->getElementType();
2227
2228 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2229 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2230 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002231 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002232 return lhsType;
2233 }
2234 }
2235
Nate Begemanc5f0f652008-07-14 18:02:46 +00002236 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002237 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002238 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002239 QualType eltType = V->getElementType();
2240
2241 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2242 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2243 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002244 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002245 return rhsType;
2246 }
2247 }
2248
Chris Lattner4b009652007-07-25 00:24:17 +00002249 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002250 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002251 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002252 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002253 return QualType();
2254}
2255
2256inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002257 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002258{
2259 QualType lhsType = lex->getType(), rhsType = rex->getType();
2260
2261 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002262 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002263
Steve Naroff8f708362007-08-24 19:07:16 +00002264 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002265
Chris Lattner4b009652007-07-25 00:24:17 +00002266 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002267 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002268 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002269}
2270
2271inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002272 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002273{
2274 QualType lhsType = lex->getType(), rhsType = rex->getType();
2275
Steve Naroff8f708362007-08-24 19:07:16 +00002276 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002277
Chris Lattner4b009652007-07-25 00:24:17 +00002278 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002279 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002280 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002281}
2282
2283inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002284 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002285{
2286 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002287 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002288
Steve Naroff8f708362007-08-24 19:07:16 +00002289 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002290
Chris Lattner4b009652007-07-25 00:24:17 +00002291 // handle the common case first (both operands are arithmetic).
2292 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002293 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002294
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002295 // Put any potential pointer into PExp
2296 Expr* PExp = lex, *IExp = rex;
2297 if (IExp->getType()->isPointerType())
2298 std::swap(PExp, IExp);
2299
2300 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2301 if (IExp->getType()->isIntegerType()) {
2302 // Check for arithmetic on pointers to incomplete types
2303 if (!PTy->getPointeeType()->isObjectType()) {
2304 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002305 Diag(Loc, diag::ext_gnu_void_ptr)
2306 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002307 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002308 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002309 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002310 return QualType();
2311 }
2312 }
2313 return PExp->getType();
2314 }
2315 }
2316
Chris Lattner1eafdea2008-11-18 01:30:42 +00002317 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002318}
2319
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002320// C99 6.5.6
2321QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002322 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002323 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002324 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002325
Steve Naroff8f708362007-08-24 19:07:16 +00002326 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002327
Chris Lattnerf6da2912007-12-09 21:53:25 +00002328 // Enforce type constraints: C99 6.5.6p3.
2329
2330 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002331 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002332 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002333
2334 // Either ptr - int or ptr - ptr.
2335 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002336 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002337
Chris Lattnerf6da2912007-12-09 21:53:25 +00002338 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002339 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002340 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002341 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002342 Diag(Loc, diag::ext_gnu_void_ptr)
2343 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002344 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002345 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002346 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002347 return QualType();
2348 }
2349 }
2350
2351 // The result type of a pointer-int computation is the pointer type.
2352 if (rex->getType()->isIntegerType())
2353 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002354
Chris Lattnerf6da2912007-12-09 21:53:25 +00002355 // Handle pointer-pointer subtractions.
2356 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002357 QualType rpointee = RHSPTy->getPointeeType();
2358
Chris Lattnerf6da2912007-12-09 21:53:25 +00002359 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002360 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002361 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002362 if (rpointee->isVoidType()) {
2363 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002364 Diag(Loc, diag::ext_gnu_void_ptr)
2365 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002366 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002367 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002368 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002369 return QualType();
2370 }
2371 }
2372
2373 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002374 if (!Context.typesAreCompatible(
2375 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2376 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002377 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002378 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002379 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002380 return QualType();
2381 }
2382
2383 return Context.getPointerDiffType();
2384 }
2385 }
2386
Chris Lattner1eafdea2008-11-18 01:30:42 +00002387 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002388}
2389
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002390// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002391QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002392 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002393 // C99 6.5.7p2: Each of the operands shall have integer type.
2394 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002395 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002396
Chris Lattner2c8bff72007-12-12 05:47:28 +00002397 // Shifts don't perform usual arithmetic conversions, they just do integer
2398 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002399 if (!isCompAssign)
2400 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002401 UsualUnaryConversions(rex);
2402
2403 // "The type of the result is that of the promoted left operand."
2404 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002405}
2406
Eli Friedman0d9549b2008-08-22 00:56:42 +00002407static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2408 ASTContext& Context) {
2409 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2410 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2411 // ID acts sort of like void* for ObjC interfaces
2412 if (LHSIface && Context.isObjCIdType(RHS))
2413 return true;
2414 if (RHSIface && Context.isObjCIdType(LHS))
2415 return true;
2416 if (!LHSIface || !RHSIface)
2417 return false;
2418 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2419 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2420}
2421
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002422// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002423QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002424 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002425 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002426 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002427
Chris Lattner254f3bc2007-08-26 01:18:55 +00002428 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002429 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2430 UsualArithmeticConversions(lex, rex);
2431 else {
2432 UsualUnaryConversions(lex);
2433 UsualUnaryConversions(rex);
2434 }
Chris Lattner4b009652007-07-25 00:24:17 +00002435 QualType lType = lex->getType();
2436 QualType rType = rex->getType();
2437
Ted Kremenek486509e2007-10-29 17:13:39 +00002438 // For non-floating point types, check for self-comparisons of the form
2439 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2440 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002441 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002442 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2443 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002444 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002445 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002446 }
2447
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002448 // The result of comparisons is 'bool' in C++, 'int' in C.
2449 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2450
Chris Lattner254f3bc2007-08-26 01:18:55 +00002451 if (isRelational) {
2452 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002453 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002454 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002455 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002456 if (lType->isFloatingType()) {
2457 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002458 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002459 }
2460
Chris Lattner254f3bc2007-08-26 01:18:55 +00002461 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002462 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002463 }
Chris Lattner4b009652007-07-25 00:24:17 +00002464
Chris Lattner22be8422007-08-26 01:10:14 +00002465 bool LHSIsNull = lex->isNullPointerConstant(Context);
2466 bool RHSIsNull = rex->isNullPointerConstant(Context);
2467
Chris Lattner254f3bc2007-08-26 01:18:55 +00002468 // All of the following pointer related warnings are GCC extensions, except
2469 // when handling null pointer constants. One day, we can consider making them
2470 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002471 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002472 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002473 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002474 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002475 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002476
Steve Naroff3b435622007-11-13 14:57:38 +00002477 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002478 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2479 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002480 RCanPointeeTy.getUnqualifiedType()) &&
2481 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002482 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002483 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002484 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002485 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002486 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002487 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002488 // Handle block pointer types.
2489 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2490 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2491 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2492
2493 if (!LHSIsNull && !RHSIsNull &&
2494 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002495 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002496 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002497 }
2498 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002499 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002500 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002501 // Allow block pointers to be compared with null pointer constants.
2502 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2503 (lType->isPointerType() && rType->isBlockPointerType())) {
2504 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002505 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002506 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002507 }
2508 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002509 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002510 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002511
Steve Naroff936c4362008-06-03 14:04:54 +00002512 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002513 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002514 const PointerType *LPT = lType->getAsPointerType();
2515 const PointerType *RPT = rType->getAsPointerType();
2516 bool LPtrToVoid = LPT ?
2517 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2518 bool RPtrToVoid = RPT ?
2519 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2520
2521 if (!LPtrToVoid && !RPtrToVoid &&
2522 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002523 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002524 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002525 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002526 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002527 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002528 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002529 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002530 }
Steve Naroff936c4362008-06-03 14:04:54 +00002531 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2532 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002533 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002534 } else {
2535 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002536 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002537 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002538 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002539 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002540 }
Steve Naroff936c4362008-06-03 14:04:54 +00002541 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002542 }
Steve Naroff936c4362008-06-03 14:04:54 +00002543 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2544 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002545 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002546 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002547 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002548 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002549 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002550 }
Steve Naroff936c4362008-06-03 14:04:54 +00002551 if (lType->isIntegerType() &&
2552 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002553 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002554 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002555 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002556 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002557 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002558 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002559 // Handle block pointers.
2560 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2561 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002562 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002563 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002564 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002565 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002566 }
2567 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2568 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002569 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002570 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002571 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002572 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002573 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002574 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002575}
2576
Nate Begemanc5f0f652008-07-14 18:02:46 +00002577/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2578/// operates on extended vector types. Instead of producing an IntTy result,
2579/// like a scalar comparison, a vector comparison produces a vector of integer
2580/// types.
2581QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002583 bool isRelational) {
2584 // Check to make sure we're operating on vectors of the same type and width,
2585 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002586 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002587 if (vType.isNull())
2588 return vType;
2589
2590 QualType lType = lex->getType();
2591 QualType rType = rex->getType();
2592
2593 // For non-floating point types, check for self-comparisons of the form
2594 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2595 // often indicate logic errors in the program.
2596 if (!lType->isFloatingType()) {
2597 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2598 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2599 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002600 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002601 }
2602
2603 // Check for comparisons of floating point operands using != and ==.
2604 if (!isRelational && lType->isFloatingType()) {
2605 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002606 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002607 }
2608
2609 // Return the type for the comparison, which is the same as vector type for
2610 // integer vectors, or an integer type of identical size and number of
2611 // elements for floating point vectors.
2612 if (lType->isIntegerType())
2613 return lType;
2614
2615 const VectorType *VTy = lType->getAsVectorType();
2616
2617 // FIXME: need to deal with non-32b int / non-64b long long
2618 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2619 if (TypeSize == 32) {
2620 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2621 }
2622 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2623 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2624}
2625
Chris Lattner4b009652007-07-25 00:24:17 +00002626inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002627 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002628{
2629 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002630 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002631
Steve Naroff8f708362007-08-24 19:07:16 +00002632 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002633
2634 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002635 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002636 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002637}
2638
2639inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002640 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002641{
2642 UsualUnaryConversions(lex);
2643 UsualUnaryConversions(rex);
2644
Eli Friedmanbea3f842008-05-13 20:16:47 +00002645 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002646 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002647 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002648}
2649
Chris Lattner4c2642c2008-11-18 01:22:49 +00002650/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2651/// emit an error and return true. If so, return false.
2652static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2653 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2654 if (IsLV == Expr::MLV_Valid)
2655 return false;
2656
2657 unsigned Diag = 0;
2658 bool NeedType = false;
2659 switch (IsLV) { // C99 6.5.16p2
2660 default: assert(0 && "Unknown result from isModifiableLvalue!");
2661 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002662 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002663 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2664 NeedType = true;
2665 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002666 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002667 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2668 NeedType = true;
2669 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002670 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002671 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2672 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002673 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002674 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2675 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002676 case Expr::MLV_IncompleteType:
2677 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002678 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2679 NeedType = true;
2680 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002681 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002682 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2683 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002684 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002685 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2686 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002687 case Expr::MLV_ReadonlyProperty:
2688 Diag = diag::error_readonly_property_assignment;
2689 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002690 case Expr::MLV_NoSetterProperty:
2691 Diag = diag::error_nosetter_property_assignment;
2692 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002693 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002694
Chris Lattner4c2642c2008-11-18 01:22:49 +00002695 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002696 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002697 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002698 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002699 return true;
2700}
2701
2702
2703
2704// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002705QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2706 SourceLocation Loc,
2707 QualType CompoundType) {
2708 // Verify that LHS is a modifiable lvalue, and emit error if not.
2709 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002710 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002711
2712 QualType LHSType = LHS->getType();
2713 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002714
Chris Lattner005ed752008-01-04 18:04:52 +00002715 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002716 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002717 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002718 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002719
2720 // If the RHS is a unary plus or minus, check to see if they = and + are
2721 // right next to each other. If so, the user may have typo'd "x =+ 4"
2722 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002723 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002724 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2725 RHSCheck = ICE->getSubExpr();
2726 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2727 if ((UO->getOpcode() == UnaryOperator::Plus ||
2728 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002729 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002730 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002732 Diag(Loc, diag::warn_not_compound_assign)
2733 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2734 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002735 }
2736 } else {
2737 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002738 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002739 }
Chris Lattner005ed752008-01-04 18:04:52 +00002740
Chris Lattner1eafdea2008-11-18 01:30:42 +00002741 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2742 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002743 return QualType();
2744
Chris Lattner4b009652007-07-25 00:24:17 +00002745 // C99 6.5.16p3: The type of an assignment expression is the type of the
2746 // left operand unless the left operand has qualified type, in which case
2747 // it is the unqualified version of the type of the left operand.
2748 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2749 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002750 // C++ 5.17p1: the type of the assignment expression is that of its left
2751 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002752 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002753}
2754
Chris Lattner1eafdea2008-11-18 01:30:42 +00002755// C99 6.5.17
2756QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2757 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002758
2759 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002760 DefaultFunctionArrayConversion(RHS);
2761 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002762}
2763
2764/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2765/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002766QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
2767 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002768 QualType ResType = Op->getType();
2769 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002770
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002771 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
2772 // Decrement of bool is not allowed.
2773 if (!isInc) {
2774 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
2775 return QualType();
2776 }
2777 // Increment of bool sets it to true, but is deprecated.
2778 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
2779 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002780 // OK!
2781 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2782 // C99 6.5.2.4p2, 6.5.6p2
2783 if (PT->getPointeeType()->isObjectType()) {
2784 // Pointer to object is ok!
2785 } else if (PT->getPointeeType()->isVoidType()) {
2786 // Pointer to void is extension.
2787 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2788 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002789 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002790 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002791 return QualType();
2792 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002793 } else if (ResType->isComplexType()) {
2794 // C99 does not support ++/-- on complex types, we allow as an extension.
2795 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002796 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002797 } else {
2798 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002799 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002800 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002801 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002802 // At this point, we know we have a real, complex or pointer type.
2803 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002804 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002805 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002806 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002807}
2808
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002809/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002810/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002811/// where the declaration is needed for type checking. We only need to
2812/// handle cases when the expression references a function designator
2813/// or is an lvalue. Here are some examples:
2814/// - &(x) => x
2815/// - &*****f => f for f a function designator.
2816/// - &s.xx => s
2817/// - &s.zz[1].yy -> s, if zz is an array
2818/// - *(x + 1) -> x, if x is an array
2819/// - &"123"[2] -> 0
2820/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002821static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002822 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002823 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002824 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002825 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002826 // Fields cannot be declared with a 'register' storage class.
2827 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002828 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002829 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002830 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002831 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002832 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002833
Douglas Gregord2baafd2008-10-21 16:13:35 +00002834 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002835 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002836 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002837 return 0;
2838 else
2839 return VD;
2840 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002841 case Stmt::UnaryOperatorClass: {
2842 UnaryOperator *UO = cast<UnaryOperator>(E);
2843
2844 switch(UO->getOpcode()) {
2845 case UnaryOperator::Deref: {
2846 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002847 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2848 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2849 if (!VD || VD->getType()->isPointerType())
2850 return 0;
2851 return VD;
2852 }
2853 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002854 }
2855 case UnaryOperator::Real:
2856 case UnaryOperator::Imag:
2857 case UnaryOperator::Extension:
2858 return getPrimaryDecl(UO->getSubExpr());
2859 default:
2860 return 0;
2861 }
2862 }
2863 case Stmt::BinaryOperatorClass: {
2864 BinaryOperator *BO = cast<BinaryOperator>(E);
2865
2866 // Handle cases involving pointer arithmetic. The result of an
2867 // Assign or AddAssign is not an lvalue so they can be ignored.
2868
2869 // (x + n) or (n + x) => x
2870 if (BO->getOpcode() == BinaryOperator::Add) {
2871 if (BO->getLHS()->getType()->isPointerType()) {
2872 return getPrimaryDecl(BO->getLHS());
2873 } else if (BO->getRHS()->getType()->isPointerType()) {
2874 return getPrimaryDecl(BO->getRHS());
2875 }
2876 }
2877
2878 return 0;
2879 }
Chris Lattner4b009652007-07-25 00:24:17 +00002880 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002881 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002882 case Stmt::ImplicitCastExprClass:
2883 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002884 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002885 default:
2886 return 0;
2887 }
2888}
2889
2890/// CheckAddressOfOperand - The operand of & must be either a function
2891/// designator or an lvalue designating an object. If it is an lvalue, the
2892/// object cannot be declared with storage class register or be a bit field.
2893/// Note: The usual conversions are *not* applied to the operand of the &
2894/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002895/// In C++, the operand might be an overloaded function name, in which case
2896/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002897QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00002898 if (op->isTypeDependent())
2899 return Context.DependentTy;
2900
Steve Naroff9c6c3592008-01-13 17:10:08 +00002901 if (getLangOptions().C99) {
2902 // Implement C99-only parts of addressof rules.
2903 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2904 if (uOp->getOpcode() == UnaryOperator::Deref)
2905 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2906 // (assuming the deref expression is valid).
2907 return uOp->getSubExpr()->getType();
2908 }
2909 // Technically, there should be a check for array subscript
2910 // expressions here, but the result of one is always an lvalue anyway.
2911 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002912 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002913 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00002914
Chris Lattner4b009652007-07-25 00:24:17 +00002915 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002916 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2917 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002918 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2919 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002920 return QualType();
2921 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002922 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2923 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002924 Diag(OpLoc, diag::err_typecheck_address_of)
2925 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002926 return QualType();
2927 }
2928 // Check for Apple extension for accessing vector components.
2929 } else if (isa<ArraySubscriptExpr>(op) &&
2930 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002931 Diag(OpLoc, diag::err_typecheck_address_of)
2932 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002933 return QualType();
2934 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002935 // We have an lvalue with a decl. Make sure the decl is not declared
2936 // with the register storage-class specifier.
2937 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2938 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002939 Diag(OpLoc, diag::err_typecheck_address_of)
2940 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002941 return QualType();
2942 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00002943 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002944 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00002945 } else if (isa<FieldDecl>(dcl)) {
2946 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00002947 } else if (isa<FunctionDecl>(dcl)) {
2948 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00002949 }
Nuno Lopesdf239522008-12-16 22:58:26 +00002950 else
Chris Lattner4b009652007-07-25 00:24:17 +00002951 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002952 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002953
Chris Lattner4b009652007-07-25 00:24:17 +00002954 // If the operand has type "type", the result has type "pointer to type".
2955 return Context.getPointerType(op->getType());
2956}
2957
Chris Lattnerda5c0872008-11-23 09:13:29 +00002958QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2959 UsualUnaryConversions(Op);
2960 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002961
Chris Lattnerda5c0872008-11-23 09:13:29 +00002962 // Note that per both C89 and C99, this is always legal, even if ptype is an
2963 // incomplete type or void. It would be possible to warn about dereferencing
2964 // a void pointer, but it's completely well-defined, and such a warning is
2965 // unlikely to catch any mistakes.
2966 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002967 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002968
Chris Lattner77d52da2008-11-20 06:06:08 +00002969 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002970 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002971 return QualType();
2972}
2973
2974static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2975 tok::TokenKind Kind) {
2976 BinaryOperator::Opcode Opc;
2977 switch (Kind) {
2978 default: assert(0 && "Unknown binop!");
2979 case tok::star: Opc = BinaryOperator::Mul; break;
2980 case tok::slash: Opc = BinaryOperator::Div; break;
2981 case tok::percent: Opc = BinaryOperator::Rem; break;
2982 case tok::plus: Opc = BinaryOperator::Add; break;
2983 case tok::minus: Opc = BinaryOperator::Sub; break;
2984 case tok::lessless: Opc = BinaryOperator::Shl; break;
2985 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2986 case tok::lessequal: Opc = BinaryOperator::LE; break;
2987 case tok::less: Opc = BinaryOperator::LT; break;
2988 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2989 case tok::greater: Opc = BinaryOperator::GT; break;
2990 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2991 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2992 case tok::amp: Opc = BinaryOperator::And; break;
2993 case tok::caret: Opc = BinaryOperator::Xor; break;
2994 case tok::pipe: Opc = BinaryOperator::Or; break;
2995 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2996 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2997 case tok::equal: Opc = BinaryOperator::Assign; break;
2998 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2999 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3000 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3001 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3002 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3003 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3004 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3005 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3006 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3007 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3008 case tok::comma: Opc = BinaryOperator::Comma; break;
3009 }
3010 return Opc;
3011}
3012
3013static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3014 tok::TokenKind Kind) {
3015 UnaryOperator::Opcode Opc;
3016 switch (Kind) {
3017 default: assert(0 && "Unknown unary op!");
3018 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3019 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3020 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3021 case tok::star: Opc = UnaryOperator::Deref; break;
3022 case tok::plus: Opc = UnaryOperator::Plus; break;
3023 case tok::minus: Opc = UnaryOperator::Minus; break;
3024 case tok::tilde: Opc = UnaryOperator::Not; break;
3025 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003026 case tok::kw___real: Opc = UnaryOperator::Real; break;
3027 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3028 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3029 }
3030 return Opc;
3031}
3032
Douglas Gregord7f915e2008-11-06 23:29:22 +00003033/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3034/// operator @p Opc at location @c TokLoc. This routine only supports
3035/// built-in operations; ActOnBinOp handles overloaded operators.
3036Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3037 unsigned Op,
3038 Expr *lhs, Expr *rhs) {
3039 QualType ResultTy; // Result type of the binary operator.
3040 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3041 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3042
3043 switch (Opc) {
3044 default:
3045 assert(0 && "Unknown binary expr!");
3046 case BinaryOperator::Assign:
3047 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3048 break;
3049 case BinaryOperator::Mul:
3050 case BinaryOperator::Div:
3051 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3052 break;
3053 case BinaryOperator::Rem:
3054 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3055 break;
3056 case BinaryOperator::Add:
3057 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3058 break;
3059 case BinaryOperator::Sub:
3060 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3061 break;
3062 case BinaryOperator::Shl:
3063 case BinaryOperator::Shr:
3064 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3065 break;
3066 case BinaryOperator::LE:
3067 case BinaryOperator::LT:
3068 case BinaryOperator::GE:
3069 case BinaryOperator::GT:
3070 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3071 break;
3072 case BinaryOperator::EQ:
3073 case BinaryOperator::NE:
3074 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3075 break;
3076 case BinaryOperator::And:
3077 case BinaryOperator::Xor:
3078 case BinaryOperator::Or:
3079 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3080 break;
3081 case BinaryOperator::LAnd:
3082 case BinaryOperator::LOr:
3083 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3084 break;
3085 case BinaryOperator::MulAssign:
3086 case BinaryOperator::DivAssign:
3087 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3088 if (!CompTy.isNull())
3089 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3090 break;
3091 case BinaryOperator::RemAssign:
3092 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3093 if (!CompTy.isNull())
3094 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3095 break;
3096 case BinaryOperator::AddAssign:
3097 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3098 if (!CompTy.isNull())
3099 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3100 break;
3101 case BinaryOperator::SubAssign:
3102 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3103 if (!CompTy.isNull())
3104 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3105 break;
3106 case BinaryOperator::ShlAssign:
3107 case BinaryOperator::ShrAssign:
3108 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3109 if (!CompTy.isNull())
3110 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3111 break;
3112 case BinaryOperator::AndAssign:
3113 case BinaryOperator::XorAssign:
3114 case BinaryOperator::OrAssign:
3115 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3116 if (!CompTy.isNull())
3117 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3118 break;
3119 case BinaryOperator::Comma:
3120 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3121 break;
3122 }
3123 if (ResultTy.isNull())
3124 return true;
3125 if (CompTy.isNull())
3126 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3127 else
3128 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3129}
3130
Chris Lattner4b009652007-07-25 00:24:17 +00003131// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003132Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3133 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003134 ExprTy *LHS, ExprTy *RHS) {
3135 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3136 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3137
Steve Naroff87d58b42007-09-16 03:34:24 +00003138 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3139 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003140
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003141 // If either expression is type-dependent, just build the AST.
3142 // FIXME: We'll need to perform some caching of the result of name
3143 // lookup for operator+.
3144 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3145 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3146 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3147 Context.DependentTy, TokLoc);
3148 else
3149 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3150 }
3151
Douglas Gregord7f915e2008-11-06 23:29:22 +00003152 if (getLangOptions().CPlusPlus &&
3153 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3154 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003155 // If this is one of the assignment operators, we only perform
3156 // overload resolution if the left-hand side is a class or
3157 // enumeration type (C++ [expr.ass]p3).
3158 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3159 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3160 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3161 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003162
3163 // Determine which overloaded operator we're dealing with.
3164 static const OverloadedOperatorKind OverOps[] = {
3165 OO_Star, OO_Slash, OO_Percent,
3166 OO_Plus, OO_Minus,
3167 OO_LessLess, OO_GreaterGreater,
3168 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3169 OO_EqualEqual, OO_ExclaimEqual,
3170 OO_Amp,
3171 OO_Caret,
3172 OO_Pipe,
3173 OO_AmpAmp,
3174 OO_PipePipe,
3175 OO_Equal, OO_StarEqual,
3176 OO_SlashEqual, OO_PercentEqual,
3177 OO_PlusEqual, OO_MinusEqual,
3178 OO_LessLessEqual, OO_GreaterGreaterEqual,
3179 OO_AmpEqual, OO_CaretEqual,
3180 OO_PipeEqual,
3181 OO_Comma
3182 };
3183 OverloadedOperatorKind OverOp = OverOps[Opc];
3184
Douglas Gregor5ed15042008-11-18 23:14:02 +00003185 // Add the appropriate overloaded operators (C++ [over.match.oper])
3186 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003187 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003188 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003189 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003190
3191 // Perform overload resolution.
3192 OverloadCandidateSet::iterator Best;
3193 switch (BestViableFunction(CandidateSet, Best)) {
3194 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003195 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003196 FunctionDecl *FnDecl = Best->Function;
3197
Douglas Gregor70d26122008-11-12 17:17:38 +00003198 if (FnDecl) {
3199 // We matched an overloaded operator. Build a call to that
3200 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003201
Douglas Gregor70d26122008-11-12 17:17:38 +00003202 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003203 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3204 if (PerformObjectArgumentInitialization(lhs, Method) ||
3205 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3206 "passing"))
3207 return true;
3208 } else {
3209 // Convert the arguments.
3210 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3211 "passing") ||
3212 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3213 "passing"))
3214 return true;
3215 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003216
Douglas Gregor70d26122008-11-12 17:17:38 +00003217 // Determine the result type
3218 QualType ResultTy
3219 = FnDecl->getType()->getAsFunctionType()->getResultType();
3220 ResultTy = ResultTy.getNonReferenceType();
3221
3222 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003223 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3224 SourceLocation());
3225 UsualUnaryConversions(FnExpr);
3226
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003227 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003228 } else {
3229 // We matched a built-in operator. Convert the arguments, then
3230 // break out so that we will build the appropriate built-in
3231 // operator node.
3232 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3233 "passing") ||
3234 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3235 "passing"))
3236 return true;
3237
3238 break;
3239 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003240 }
3241
3242 case OR_No_Viable_Function:
3243 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003244 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003245 break;
3246
3247 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003248 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3249 << BinaryOperator::getOpcodeStr(Opc)
3250 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003251 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3252 return true;
3253 }
3254
Douglas Gregor70d26122008-11-12 17:17:38 +00003255 // Either we found no viable overloaded operator or we matched a
3256 // built-in operator. In either case, fall through to trying to
3257 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003258 }
Chris Lattner4b009652007-07-25 00:24:17 +00003259
Douglas Gregord7f915e2008-11-06 23:29:22 +00003260 // Build a built-in binary operation.
3261 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003262}
3263
3264// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003265Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3266 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003267 Expr *Input = (Expr*)input;
3268 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003269
3270 if (getLangOptions().CPlusPlus &&
3271 (Input->getType()->isRecordType()
3272 || Input->getType()->isEnumeralType())) {
3273 // Determine which overloaded operator we're dealing with.
3274 static const OverloadedOperatorKind OverOps[] = {
3275 OO_None, OO_None,
3276 OO_PlusPlus, OO_MinusMinus,
3277 OO_Amp, OO_Star,
3278 OO_Plus, OO_Minus,
3279 OO_Tilde, OO_Exclaim,
3280 OO_None, OO_None,
3281 OO_None,
3282 OO_None
3283 };
3284 OverloadedOperatorKind OverOp = OverOps[Opc];
3285
3286 // Add the appropriate overloaded operators (C++ [over.match.oper])
3287 // to the candidate set.
3288 OverloadCandidateSet CandidateSet;
3289 if (OverOp != OO_None)
3290 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3291
3292 // Perform overload resolution.
3293 OverloadCandidateSet::iterator Best;
3294 switch (BestViableFunction(CandidateSet, Best)) {
3295 case OR_Success: {
3296 // We found a built-in operator or an overloaded operator.
3297 FunctionDecl *FnDecl = Best->Function;
3298
3299 if (FnDecl) {
3300 // We matched an overloaded operator. Build a call to that
3301 // operator.
3302
3303 // Convert the arguments.
3304 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3305 if (PerformObjectArgumentInitialization(Input, Method))
3306 return true;
3307 } else {
3308 // Convert the arguments.
3309 if (PerformCopyInitialization(Input,
3310 FnDecl->getParamDecl(0)->getType(),
3311 "passing"))
3312 return true;
3313 }
3314
3315 // Determine the result type
3316 QualType ResultTy
3317 = FnDecl->getType()->getAsFunctionType()->getResultType();
3318 ResultTy = ResultTy.getNonReferenceType();
3319
3320 // Build the actual expression node.
3321 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3322 SourceLocation());
3323 UsualUnaryConversions(FnExpr);
3324
3325 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3326 } else {
3327 // We matched a built-in operator. Convert the arguments, then
3328 // break out so that we will build the appropriate built-in
3329 // operator node.
3330 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3331 "passing"))
3332 return true;
3333
3334 break;
3335 }
3336 }
3337
3338 case OR_No_Viable_Function:
3339 // No viable function; fall through to handling this as a
3340 // built-in operator, which will produce an error message for us.
3341 break;
3342
3343 case OR_Ambiguous:
3344 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3345 << UnaryOperator::getOpcodeStr(Opc)
3346 << Input->getSourceRange();
3347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3348 return true;
3349 }
3350
3351 // Either we found no viable overloaded operator or we matched a
3352 // built-in operator. In either case, fall through to trying to
3353 // build a built-in operation.
3354 }
3355
Chris Lattner4b009652007-07-25 00:24:17 +00003356 QualType resultType;
3357 switch (Opc) {
3358 default:
3359 assert(0 && "Unimplemented unary expr!");
3360 case UnaryOperator::PreInc:
3361 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003362 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3363 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003364 break;
3365 case UnaryOperator::AddrOf:
3366 resultType = CheckAddressOfOperand(Input, OpLoc);
3367 break;
3368 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003369 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003370 resultType = CheckIndirectionOperand(Input, OpLoc);
3371 break;
3372 case UnaryOperator::Plus:
3373 case UnaryOperator::Minus:
3374 UsualUnaryConversions(Input);
3375 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003376 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3377 break;
3378 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3379 resultType->isEnumeralType())
3380 break;
3381 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3382 Opc == UnaryOperator::Plus &&
3383 resultType->isPointerType())
3384 break;
3385
Chris Lattner77d52da2008-11-20 06:06:08 +00003386 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003387 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003388 case UnaryOperator::Not: // bitwise complement
3389 UsualUnaryConversions(Input);
3390 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003391 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3392 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3393 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003394 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003395 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003396 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003397 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003398 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003399 break;
3400 case UnaryOperator::LNot: // logical negation
3401 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3402 DefaultFunctionArrayConversion(Input);
3403 resultType = Input->getType();
3404 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003405 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003406 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003407 // LNot always has type int. C99 6.5.3.3p5.
3408 resultType = Context.IntTy;
3409 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003410 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003411 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003412 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003413 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003414 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003415 resultType = Input->getType();
3416 break;
3417 }
3418 if (resultType.isNull())
3419 return true;
3420 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3421}
3422
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003423/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3424Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003425 SourceLocation LabLoc,
3426 IdentifierInfo *LabelII) {
3427 // Look up the record for this label identifier.
3428 LabelStmt *&LabelDecl = LabelMap[LabelII];
3429
Daniel Dunbar879788d2008-08-04 16:51:22 +00003430 // If we haven't seen this label yet, create a forward reference. It
3431 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003432 if (LabelDecl == 0)
3433 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3434
3435 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003436 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3437 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003438}
3439
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003440Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003441 SourceLocation RPLoc) { // "({..})"
3442 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3443 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3444 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3445
3446 // FIXME: there are a variety of strange constraints to enforce here, for
3447 // example, it is not possible to goto into a stmt expression apparently.
3448 // More semantic analysis is needed.
3449
3450 // FIXME: the last statement in the compount stmt has its value used. We
3451 // should not warn about it being unused.
3452
3453 // If there are sub stmts in the compound stmt, take the type of the last one
3454 // as the type of the stmtexpr.
3455 QualType Ty = Context.VoidTy;
3456
Chris Lattner200964f2008-07-26 19:51:01 +00003457 if (!Compound->body_empty()) {
3458 Stmt *LastStmt = Compound->body_back();
3459 // If LastStmt is a label, skip down through into the body.
3460 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3461 LastStmt = Label->getSubStmt();
3462
3463 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003464 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003465 }
Chris Lattner4b009652007-07-25 00:24:17 +00003466
3467 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3468}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003469
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003470Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003471 SourceLocation TypeLoc,
3472 TypeTy *argty,
3473 OffsetOfComponent *CompPtr,
3474 unsigned NumComponents,
3475 SourceLocation RPLoc) {
3476 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3477 assert(!ArgTy.isNull() && "Missing type argument!");
3478
3479 // We must have at least one component that refers to the type, and the first
3480 // one is known to be a field designator. Verify that the ArgTy represents
3481 // a struct/union/class.
3482 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003483 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003484
3485 // Otherwise, create a compound literal expression as the base, and
3486 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003487 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003488
Chris Lattnerb37522e2007-08-31 21:49:13 +00003489 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3490 // GCC extension, diagnose them.
3491 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003492 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3493 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003494
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003495 for (unsigned i = 0; i != NumComponents; ++i) {
3496 const OffsetOfComponent &OC = CompPtr[i];
3497 if (OC.isBrackets) {
3498 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003499 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003500 if (!AT) {
3501 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003502 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003503 }
3504
Chris Lattner2af6a802007-08-30 17:59:59 +00003505 // FIXME: C++: Verify that operator[] isn't overloaded.
3506
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003507 // C99 6.5.2.1p1
3508 Expr *Idx = static_cast<Expr*>(OC.U.E);
3509 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003510 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3511 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003512
3513 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3514 continue;
3515 }
3516
3517 const RecordType *RC = Res->getType()->getAsRecordType();
3518 if (!RC) {
3519 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003520 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003521 }
3522
3523 // Get the decl corresponding to this.
3524 RecordDecl *RD = RC->getDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003525 FieldDecl *MemberDecl = 0;
3526 DeclContext::lookup_result Lookup = RD->lookup(Context, OC.U.IdentInfo);
3527 if (Lookup.first != Lookup.second)
3528 MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
3529
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003530 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003531 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3532 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003533
3534 // FIXME: C++: Verify that MemberDecl isn't a static field.
3535 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003536 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3537 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003538 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3539 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003540 }
3541
3542 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3543 BuiltinLoc);
3544}
3545
3546
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003547Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003548 TypeTy *arg1, TypeTy *arg2,
3549 SourceLocation RPLoc) {
3550 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3551 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3552
3553 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3554
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003555 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003556}
3557
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003558Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003559 ExprTy *expr1, ExprTy *expr2,
3560 SourceLocation RPLoc) {
3561 Expr *CondExpr = static_cast<Expr*>(cond);
3562 Expr *LHSExpr = static_cast<Expr*>(expr1);
3563 Expr *RHSExpr = static_cast<Expr*>(expr2);
3564
3565 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3566
3567 // The conditional expression is required to be a constant expression.
3568 llvm::APSInt condEval(32);
3569 SourceLocation ExpLoc;
3570 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003571 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3572 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003573
3574 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3575 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3576 RHSExpr->getType();
3577 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3578}
3579
Steve Naroff52a81c02008-09-03 18:15:37 +00003580//===----------------------------------------------------------------------===//
3581// Clang Extensions.
3582//===----------------------------------------------------------------------===//
3583
3584/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003585void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003586 // Analyze block parameters.
3587 BlockSemaInfo *BSI = new BlockSemaInfo();
3588
3589 // Add BSI to CurBlock.
3590 BSI->PrevBlockInfo = CurBlock;
3591 CurBlock = BSI;
3592
3593 BSI->ReturnType = 0;
3594 BSI->TheScope = BlockScope;
3595
Steve Naroff52059382008-10-10 01:28:17 +00003596 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003597 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003598}
3599
3600void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003601 // Analyze arguments to block.
3602 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3603 "Not a function declarator!");
3604 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3605
Steve Naroff52059382008-10-10 01:28:17 +00003606 CurBlock->hasPrototype = FTI.hasPrototype;
3607 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003608
3609 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3610 // no arguments, not a function that takes a single void argument.
3611 if (FTI.hasPrototype &&
3612 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3613 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3614 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3615 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003616 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003617 } else if (FTI.hasPrototype) {
3618 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003619 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3620 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003621 }
Steve Naroff52059382008-10-10 01:28:17 +00003622 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3623
3624 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3625 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3626 // If this has an identifier, add it to the scope stack.
3627 if ((*AI)->getIdentifier())
3628 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003629}
3630
3631/// ActOnBlockError - If there is an error parsing a block, this callback
3632/// is invoked to pop the information about the block from the action impl.
3633void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3634 // Ensure that CurBlock is deleted.
3635 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3636
3637 // Pop off CurBlock, handle nested blocks.
3638 CurBlock = CurBlock->PrevBlockInfo;
3639
3640 // FIXME: Delete the ParmVarDecl objects as well???
3641
3642}
3643
3644/// ActOnBlockStmtExpr - This is called when the body of a block statement
3645/// literal was successfully completed. ^(int x){...}
3646Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3647 Scope *CurScope) {
3648 // Ensure that CurBlock is deleted.
3649 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3650 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3651
Steve Naroff52059382008-10-10 01:28:17 +00003652 PopDeclContext();
3653
Steve Naroff52a81c02008-09-03 18:15:37 +00003654 // Pop off CurBlock, handle nested blocks.
3655 CurBlock = CurBlock->PrevBlockInfo;
3656
3657 QualType RetTy = Context.VoidTy;
3658 if (BSI->ReturnType)
3659 RetTy = QualType(BSI->ReturnType, 0);
3660
3661 llvm::SmallVector<QualType, 8> ArgTypes;
3662 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3663 ArgTypes.push_back(BSI->Params[i]->getType());
3664
3665 QualType BlockTy;
3666 if (!BSI->hasPrototype)
3667 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3668 else
3669 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003670 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003671
3672 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003673
Steve Naroff95029d92008-10-08 18:44:00 +00003674 BSI->TheDecl->setBody(Body.take());
3675 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003676}
3677
Nate Begemanbd881ef2008-01-30 20:50:20 +00003678/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003679/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003680/// The number of arguments has already been validated to match the number of
3681/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003682static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3683 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003684 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003685 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003686 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3687 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003688
3689 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003690 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003691 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003692 return true;
3693}
3694
3695Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3696 SourceLocation *CommaLocs,
3697 SourceLocation BuiltinLoc,
3698 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003699 // __builtin_overload requires at least 2 arguments
3700 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003701 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3702 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003703
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003704 // The first argument is required to be a constant expression. It tells us
3705 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003706 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003707 Expr *NParamsExpr = Args[0];
3708 llvm::APSInt constEval(32);
3709 SourceLocation ExpLoc;
3710 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003711 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3712 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003713
3714 // Verify that the number of parameters is > 0
3715 unsigned NumParams = constEval.getZExtValue();
3716 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003717 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3718 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003719 // Verify that we have at least 1 + NumParams arguments to the builtin.
3720 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003721 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3722 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003723
3724 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003725 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003726 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003727 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3728 // UsualUnaryConversions will convert the function DeclRefExpr into a
3729 // pointer to function.
3730 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003731 const FunctionTypeProto *FnType = 0;
3732 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3733 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003734
3735 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3736 // parameters, and the number of parameters must match the value passed to
3737 // the builtin.
3738 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003739 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3740 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003741
3742 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003743 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003744 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003745 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003746 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003747 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3748 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003749 // Remember our match, and continue processing the remaining arguments
3750 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003751 OE = new OverloadExpr(Args, NumArgs, i,
3752 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003753 BuiltinLoc, RParenLoc);
3754 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003755 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003756 // Return the newly created OverloadExpr node, if we succeded in matching
3757 // exactly one of the candidate functions.
3758 if (OE)
3759 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003760
3761 // If we didn't find a matching function Expr in the __builtin_overload list
3762 // the return an error.
3763 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003764 for (unsigned i = 0; i != NumParams; ++i) {
3765 if (i != 0) typeNames += ", ";
3766 typeNames += Args[i+1]->getType().getAsString();
3767 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003768
Chris Lattner77d52da2008-11-20 06:06:08 +00003769 return Diag(BuiltinLoc, diag::err_overload_no_match)
3770 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003771}
3772
Anders Carlsson36760332007-10-15 20:28:48 +00003773Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3774 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003775 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003776 Expr *E = static_cast<Expr*>(expr);
3777 QualType T = QualType::getFromOpaquePtr(type);
3778
3779 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003780
3781 // Get the va_list type
3782 QualType VaListType = Context.getBuiltinVaListType();
3783 // Deal with implicit array decay; for example, on x86-64,
3784 // va_list is an array, but it's supposed to decay to
3785 // a pointer for va_arg.
3786 if (VaListType->isArrayType())
3787 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003788 // Make sure the input expression also decays appropriately.
3789 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003790
3791 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003792 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003793 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003794 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003795
3796 // FIXME: Warn if a non-POD type is passed in.
3797
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003798 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003799}
3800
Douglas Gregorad4b3792008-11-29 04:51:27 +00003801Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3802 // The type of __null will be int or long, depending on the size of
3803 // pointers on the target.
3804 QualType Ty;
3805 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3806 Ty = Context.IntTy;
3807 else
3808 Ty = Context.LongTy;
3809
3810 return new GNUNullExpr(Ty, TokenLoc);
3811}
3812
Chris Lattner005ed752008-01-04 18:04:52 +00003813bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3814 SourceLocation Loc,
3815 QualType DstType, QualType SrcType,
3816 Expr *SrcExpr, const char *Flavor) {
3817 // Decode the result (notice that AST's are still created for extensions).
3818 bool isInvalid = false;
3819 unsigned DiagKind;
3820 switch (ConvTy) {
3821 default: assert(0 && "Unknown conversion type");
3822 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003823 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003824 DiagKind = diag::ext_typecheck_convert_pointer_int;
3825 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003826 case IntToPointer:
3827 DiagKind = diag::ext_typecheck_convert_int_pointer;
3828 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003829 case IncompatiblePointer:
3830 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3831 break;
3832 case FunctionVoidPointer:
3833 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3834 break;
3835 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003836 // If the qualifiers lost were because we were applying the
3837 // (deprecated) C++ conversion from a string literal to a char*
3838 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3839 // Ideally, this check would be performed in
3840 // CheckPointerTypesForAssignment. However, that would require a
3841 // bit of refactoring (so that the second argument is an
3842 // expression, rather than a type), which should be done as part
3843 // of a larger effort to fix CheckPointerTypesForAssignment for
3844 // C++ semantics.
3845 if (getLangOptions().CPlusPlus &&
3846 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3847 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003848 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3849 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003850 case IntToBlockPointer:
3851 DiagKind = diag::err_int_to_block_pointer;
3852 break;
3853 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003854 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003855 break;
Steve Naroff19608432008-10-14 22:18:38 +00003856 case IncompatibleObjCQualifiedId:
3857 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3858 // it can give a more specific diagnostic.
3859 DiagKind = diag::warn_incompatible_qualified_id;
3860 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003861 case Incompatible:
3862 DiagKind = diag::err_typecheck_convert_incompatible;
3863 isInvalid = true;
3864 break;
3865 }
3866
Chris Lattner271d4c22008-11-24 05:29:24 +00003867 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3868 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003869 return isInvalid;
3870}
Anders Carlssond5201b92008-11-30 19:50:32 +00003871
3872bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3873{
3874 Expr::EvalResult EvalResult;
3875
3876 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3877 EvalResult.HasSideEffects) {
3878 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3879
3880 if (EvalResult.Diag) {
3881 // We only show the note if it's not the usual "invalid subexpression"
3882 // or if it's actually in a subexpression.
3883 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3884 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3885 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3886 }
3887
3888 return true;
3889 }
3890
3891 if (EvalResult.Diag) {
3892 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3893 E->getSourceRange();
3894
3895 // Print the reason it's not a constant.
3896 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3897 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3898 }
3899
3900 if (Result)
3901 *Result = EvalResult.Val.getInt();
3902 return false;
3903}