blob: 8896f43539091ef2c9d1f2318a4761d4c6825b72 [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"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000017#include "clang/AST/DeclCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Expr.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Chris Lattner299b8842008-07-25 21:10:04 +000031//===----------------------------------------------------------------------===//
32// Standard Promotions and Conversions
33//===----------------------------------------------------------------------===//
34
Chris Lattner299b8842008-07-25 21:10:04 +000035/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
36void Sema::DefaultFunctionArrayConversion(Expr *&E) {
37 QualType Ty = E->getType();
38 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
39
40 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
41 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
42 Ty = E->getType();
43 }
44 if (Ty->isFunctionType())
45 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000046 else if (Ty->isArrayType()) {
47 // In C90 mode, arrays only promote to pointers if the array expression is
48 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
49 // type 'array of type' is converted to an expression that has type 'pointer
50 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
51 // that has type 'array of type' ...". The relevant change is "an lvalue"
52 // (C90) to "an expression" (C99).
Chris Lattner25168a52008-07-26 21:30:36 +000053 if (getLangOptions().C99 || 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
67 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
68 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
69 Ty = Expr->getType();
70 }
71 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
72 ImpCastExprToType(Expr, Context.IntTy);
73 else
74 DefaultFunctionArrayConversion(Expr);
75
76 return Expr;
77}
78
Chris Lattner9305c3d2008-07-25 22:25:12 +000079/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
80/// do not have a prototype. Arguments that have type float are promoted to
81/// double. All other argument types are converted by UsualUnaryConversions().
82void Sema::DefaultArgumentPromotion(Expr *&Expr) {
83 QualType Ty = Expr->getType();
84 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
85
86 // If this is a 'float' (CVR qualified or typedef) promote to double.
87 if (const BuiltinType *BT = Ty->getAsBuiltinType())
88 if (BT->getKind() == BuiltinType::Float)
89 return ImpCastExprToType(Expr, Context.DoubleTy);
90
91 UsualUnaryConversions(Expr);
92}
93
Chris Lattner299b8842008-07-25 21:10:04 +000094/// UsualArithmeticConversions - Performs various conversions that are common to
95/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
96/// routine returns the first non-arithmetic type found. The client is
97/// responsible for emitting appropriate error diagnostics.
98/// FIXME: verify the conversion rules for "complex int" are consistent with
99/// GCC.
100QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
101 bool isCompAssign) {
102 if (!isCompAssign) {
103 UsualUnaryConversions(lhsExpr);
104 UsualUnaryConversions(rhsExpr);
105 }
106 // For conversion purposes, we ignore any qualifiers.
107 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000108 QualType lhs =
109 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
110 QualType rhs =
111 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000112
113 // If both types are identical, no conversion is needed.
114 if (lhs == rhs)
115 return lhs;
116
117 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
118 // The caller can deal with this (e.g. pointer + int).
119 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
120 return lhs;
121
122 // At this point, we have two different arithmetic types.
123
124 // Handle complex types first (C99 6.3.1.8p1).
125 if (lhs->isComplexType() || rhs->isComplexType()) {
126 // if we have an integer operand, the result is the complex type.
127 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
128 // convert the rhs to the lhs complex type.
129 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
130 return lhs;
131 }
132 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
133 // convert the lhs to the rhs complex type.
134 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
135 return rhs;
136 }
137 // This handles complex/complex, complex/float, or float/complex.
138 // When both operands are complex, the shorter operand is converted to the
139 // type of the longer, and that is the type of the result. This corresponds
140 // to what is done when combining two real floating-point operands.
141 // The fun begins when size promotion occur across type domains.
142 // From H&S 6.3.4: When one operand is complex and the other is a real
143 // floating-point type, the less precise type is converted, within it's
144 // real or complex domain, to the precision of the other type. For example,
145 // when combining a "long double" with a "double _Complex", the
146 // "double _Complex" is promoted to "long double _Complex".
147 int result = Context.getFloatingTypeOrder(lhs, rhs);
148
149 if (result > 0) { // The left side is bigger, convert rhs.
150 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
151 if (!isCompAssign)
152 ImpCastExprToType(rhsExpr, rhs);
153 } else if (result < 0) { // The right side is bigger, convert lhs.
154 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
155 if (!isCompAssign)
156 ImpCastExprToType(lhsExpr, lhs);
157 }
158 // At this point, lhs and rhs have the same rank/size. Now, make sure the
159 // domains match. This is a requirement for our implementation, C99
160 // does not require this promotion.
161 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
162 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
163 if (!isCompAssign)
164 ImpCastExprToType(lhsExpr, rhs);
165 return rhs;
166 } else { // handle "_Complex double, double".
167 if (!isCompAssign)
168 ImpCastExprToType(rhsExpr, lhs);
169 return lhs;
170 }
171 }
172 return lhs; // The domain/size match exactly.
173 }
174 // Now handle "real" floating types (i.e. float, double, long double).
175 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
176 // if we have an integer operand, the result is the real floating type.
177 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
178 // convert rhs to the lhs floating point type.
179 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
180 return lhs;
181 }
182 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
183 // convert lhs to the rhs floating point type.
184 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
185 return rhs;
186 }
187 // We have two real floating types, float/complex combos were handled above.
188 // Convert the smaller operand to the bigger result.
189 int result = Context.getFloatingTypeOrder(lhs, rhs);
190
191 if (result > 0) { // convert the rhs
192 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
193 return lhs;
194 }
195 if (result < 0) { // convert the lhs
196 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
197 return rhs;
198 }
199 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
200 }
201 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
202 // Handle GCC complex int extension.
203 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
204 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
205
206 if (lhsComplexInt && rhsComplexInt) {
207 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
208 rhsComplexInt->getElementType()) >= 0) {
209 // convert the rhs
210 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
211 return lhs;
212 }
213 if (!isCompAssign)
214 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
215 return rhs;
216 } else if (lhsComplexInt && rhs->isIntegerType()) {
217 // convert the rhs to the lhs complex type.
218 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
219 return lhs;
220 } else if (rhsComplexInt && lhs->isIntegerType()) {
221 // convert the lhs to the rhs complex type.
222 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
223 return rhs;
224 }
225 }
226 // Finally, we have two differing integer types.
227 // The rules for this case are in C99 6.3.1.8
228 int compare = Context.getIntegerTypeOrder(lhs, rhs);
229 bool lhsSigned = lhs->isSignedIntegerType(),
230 rhsSigned = rhs->isSignedIntegerType();
231 QualType destType;
232 if (lhsSigned == rhsSigned) {
233 // Same signedness; use the higher-ranked type
234 destType = compare >= 0 ? lhs : rhs;
235 } else if (compare != (lhsSigned ? 1 : -1)) {
236 // The unsigned type has greater than or equal rank to the
237 // signed type, so use the unsigned type
238 destType = lhsSigned ? rhs : lhs;
239 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
240 // The two types are different widths; if we are here, that
241 // means the signed type is larger than the unsigned type, so
242 // use the signed type.
243 destType = lhsSigned ? lhs : rhs;
244 } else {
245 // The signed type is higher-ranked than the unsigned type,
246 // but isn't actually any bigger (like unsigned int and long
247 // on most 32-bit systems). Use the unsigned type corresponding
248 // to the signed type.
249 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
250 }
251 if (!isCompAssign) {
252 ImpCastExprToType(lhsExpr, destType);
253 ImpCastExprToType(rhsExpr, destType);
254 }
255 return destType;
256}
257
258//===----------------------------------------------------------------------===//
259// Semantic Analysis for various Expression Types
260//===----------------------------------------------------------------------===//
261
262
Steve Naroff87d58b42007-09-16 03:34:24 +0000263/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000264/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
265/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
266/// multiple tokens. However, the common case is that StringToks points to one
267/// string.
268///
269Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000270Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000271 assert(NumStringToks && "Must have at least one string!");
272
273 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
274 if (Literal.hadError)
275 return ExprResult(true);
276
277 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
278 for (unsigned i = 0; i != NumStringToks; ++i)
279 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000280
281 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000282 if (Literal.Pascal && Literal.GetStringLength() > 256)
283 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
284 SourceRange(StringToks[0].getLocation(),
285 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000286
Chris Lattnera6dcce32008-02-11 00:02:17 +0000287 QualType StrTy = Context.CharTy;
Eli Friedman256b7d72008-05-27 07:57:14 +0000288 if (Literal.AnyWide) StrTy = Context.getWcharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000289 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
290
291 // Get an array type for the string, according to C99 6.4.5. This includes
292 // the nul terminator character as well as the string length for pascal
293 // strings.
294 StrTy = Context.getConstantArrayType(StrTy,
295 llvm::APInt(32, Literal.GetStringLength()+1),
296 ArrayType::Normal, 0);
297
Chris Lattner4b009652007-07-25 00:24:17 +0000298 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
299 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000300 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000301 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000302 StringToks[NumStringToks-1].getLocation());
303}
304
305
Steve Naroff0acc9c92007-09-15 18:49:24 +0000306/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000307/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000308/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000309Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000310 IdentifierInfo &II,
311 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000312 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000313 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000314
315 // If this reference is in an Objective-C method, then ivar lookup happens as
316 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000317 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000318 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000319 // There are two cases to handle here. 1) scoped lookup could have failed,
320 // in which case we should look for an ivar. 2) scoped lookup could have
321 // found a decl, but that decl is outside the current method (i.e. a global
322 // variable). In these two cases, we do a lookup for an ivar with this
323 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000324 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000325 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000326 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000327 // FIXME: This should use a new expr for a direct reference, don't turn
328 // this into Self->ivar, just return a BareIVarExpr or something.
329 IdentifierInfo &II = Context.Idents.get("self");
330 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
331 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
332 static_cast<Expr*>(SelfExpr.Val), true, true);
333 }
334 }
Steve Naroffe90d4cc2008-06-05 18:14:25 +0000335 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000336 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000337 getCurMethodDecl()->getClassInterface()));
Steve Naroff6f786252008-06-02 23:03:37 +0000338 return new ObjCSuperRefExpr(T, Loc);
339 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000340 }
341
Chris Lattner4b009652007-07-25 00:24:17 +0000342 if (D == 0) {
343 // Otherwise, this could be an implicitly declared function reference (legal
344 // in C90, extension in C99).
345 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000346 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000347 D = ImplicitlyDefineFunction(Loc, II, S);
348 else {
349 // If this name wasn't predeclared and if this is not a function call,
350 // diagnose the problem.
351 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
352 }
353 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000354
Steve Naroff91b03f72007-08-28 03:03:08 +0000355 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000356 // check if referencing an identifier with __attribute__((deprecated)).
357 if (VD->getAttr<DeprecatedAttr>())
358 Diag(Loc, diag::warn_deprecated, VD->getName());
359
Steve Naroffcae537d2007-08-28 18:45:29 +0000360 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000361 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000362 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000363 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000364 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000365
366 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
367 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
368 if (MD->isStatic())
369 // "invalid use of member 'x' in static member function"
370 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
371 FD->getName());
372 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
373 // "invalid use of nonstatic data member 'x'"
374 return Diag(Loc, diag::err_invalid_non_static_member_use,
375 FD->getName());
376
377 if (FD->isInvalidDecl())
378 return true;
379
380 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
381 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
382 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
383 true, FD, Loc, FD->getType());
384 }
385
386 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
387 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000388
Chris Lattner4b009652007-07-25 00:24:17 +0000389 if (isa<TypedefDecl>(D))
390 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000391 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000392 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000393 if (isa<NamespaceDecl>(D))
394 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000395
396 assert(0 && "Invalid decl");
397 abort();
398}
399
Steve Naroff87d58b42007-09-16 03:34:24 +0000400Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000401 tok::TokenKind Kind) {
402 PreDefinedExpr::IdentType IT;
403
404 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000405 default: assert(0 && "Unknown simple primary expr!");
406 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
407 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
408 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000409 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000410
411 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000412 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000413 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000414
Chris Lattner7e637512008-01-12 08:14:25 +0000415 // Pre-defined identifiers are of type char[x], where x is the length of the
416 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000417 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000418 if (getCurFunctionDecl())
419 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000420 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000421 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000422
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000423 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000424 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000425 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000426 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000427}
428
Steve Naroff87d58b42007-09-16 03:34:24 +0000429Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000430 llvm::SmallString<16> CharBuffer;
431 CharBuffer.resize(Tok.getLength());
432 const char *ThisTokBegin = &CharBuffer[0];
433 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
434
435 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
436 Tok.getLocation(), PP);
437 if (Literal.hadError())
438 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000439
440 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
441
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000442 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
443 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000444}
445
Steve Naroff87d58b42007-09-16 03:34:24 +0000446Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000447 // fast path for a single digit (which is quite common). A single digit
448 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
449 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000450 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000451
Chris Lattner8cd0e932008-03-05 18:54:05 +0000452 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000453 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000454 Context.IntTy,
455 Tok.getLocation()));
456 }
457 llvm::SmallString<512> IntegerBuffer;
458 IntegerBuffer.resize(Tok.getLength());
459 const char *ThisTokBegin = &IntegerBuffer[0];
460
461 // Get the spelling of the token, which eliminates trigraphs, etc.
462 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
463 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
464 Tok.getLocation(), PP);
465 if (Literal.hadError)
466 return ExprResult(true);
467
Chris Lattner1de66eb2007-08-26 03:42:43 +0000468 Expr *Res;
469
470 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000471 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000472 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000473 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000474 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000475 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000476 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000477 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000478
479 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
480
Ted Kremenekddedbe22007-11-29 00:56:49 +0000481 // isExact will be set by GetFloatValue().
482 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000483 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000484 Ty, Tok.getLocation());
485
Chris Lattner1de66eb2007-08-26 03:42:43 +0000486 } else if (!Literal.isIntegerLiteral()) {
487 return ExprResult(true);
488 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000489 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000490
Neil Booth7421e9c2007-08-29 22:00:19 +0000491 // long long is a C99 feature.
492 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000493 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000494 Diag(Tok.getLocation(), diag::ext_longlong);
495
Chris Lattner4b009652007-07-25 00:24:17 +0000496 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000497 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000498
499 if (Literal.GetIntegerValue(ResultVal)) {
500 // If this value didn't fit into uintmax_t, warn and force to ull.
501 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000502 Ty = Context.UnsignedLongLongTy;
503 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000504 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000505 } else {
506 // If this value fits into a ULL, try to figure out what else it fits into
507 // according to the rules of C99 6.4.4.1p5.
508
509 // Octal, Hexadecimal, and integers with a U suffix are allowed to
510 // be an unsigned int.
511 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
512
513 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000514 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000515 if (!Literal.isLong && !Literal.isLongLong) {
516 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000517 unsigned IntSize = Context.Target.getIntWidth();
518
Chris Lattner4b009652007-07-25 00:24:17 +0000519 // Does it fit in a unsigned int?
520 if (ResultVal.isIntN(IntSize)) {
521 // Does it fit in a signed int?
522 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000523 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000524 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000525 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000526 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000527 }
Chris Lattner4b009652007-07-25 00:24:17 +0000528 }
529
530 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000531 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000532 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000533
534 // Does it fit in a unsigned long?
535 if (ResultVal.isIntN(LongSize)) {
536 // Does it fit in a signed long?
537 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000538 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000539 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000540 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000541 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000542 }
Chris Lattner4b009652007-07-25 00:24:17 +0000543 }
544
545 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000546 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000547 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000548
549 // Does it fit in a unsigned long long?
550 if (ResultVal.isIntN(LongLongSize)) {
551 // Does it fit in a signed long long?
552 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000553 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000554 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000555 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000556 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000557 }
558 }
559
560 // If we still couldn't decide a type, we probably have something that
561 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000562 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000563 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000564 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000565 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000566 }
Chris Lattnere4068872008-05-09 05:59:00 +0000567
568 if (ResultVal.getBitWidth() != Width)
569 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000570 }
571
Chris Lattner48d7f382008-04-02 04:24:33 +0000572 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000573 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000574
575 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
576 if (Literal.isImaginary)
577 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
578
579 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000580}
581
Steve Naroff87d58b42007-09-16 03:34:24 +0000582Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000583 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000584 Expr *E = (Expr *)Val;
585 assert((E != 0) && "ActOnParenExpr() missing expr");
586 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000587}
588
589/// The UsualUnaryConversions() function is *not* called by this routine.
590/// See C99 6.3.2.1p[2-4] for more details.
591QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000592 SourceLocation OpLoc,
593 const SourceRange &ExprRange,
594 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000595 // C99 6.5.3.4p1:
596 if (isa<FunctionType>(exprType) && isSizeof)
597 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000598 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000599 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000600 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
601 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 else if (exprType->isIncompleteType()) {
603 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
604 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000605 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000606 return QualType(); // error
607 }
608 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
609 return Context.getSizeType();
610}
611
612Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000613ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000614 SourceLocation LPLoc, TypeTy *Ty,
615 SourceLocation RPLoc) {
616 // If error parsing type, ignore.
617 if (Ty == 0) return true;
618
619 // Verify that this is a valid expression.
620 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
621
Chris Lattnerf814d882008-07-25 21:45:37 +0000622 QualType resultType =
623 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000624
625 if (resultType.isNull())
626 return true;
627 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
628}
629
Chris Lattner5110ad52007-08-24 21:41:10 +0000630QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000631 DefaultFunctionArrayConversion(V);
632
Chris Lattnera16e42d2007-08-26 05:39:26 +0000633 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000634 if (const ComplexType *CT = V->getType()->getAsComplexType())
635 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000636
637 // Otherwise they pass through real integer and floating point types here.
638 if (V->getType()->isArithmeticType())
639 return V->getType();
640
641 // Reject anything else.
642 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
643 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000644}
645
646
Chris Lattner4b009652007-07-25 00:24:17 +0000647
Steve Naroff87d58b42007-09-16 03:34:24 +0000648Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000649 tok::TokenKind Kind,
650 ExprTy *Input) {
651 UnaryOperator::Opcode Opc;
652 switch (Kind) {
653 default: assert(0 && "Unknown unary op!");
654 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
655 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
656 }
657 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
658 if (result.isNull())
659 return true;
660 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
661}
662
663Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000664ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000665 ExprTy *Idx, SourceLocation RLoc) {
666 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
667
668 // Perform default conversions.
669 DefaultFunctionArrayConversion(LHSExp);
670 DefaultFunctionArrayConversion(RHSExp);
671
672 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
673
674 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000675 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000676 // in the subscript position. As a result, we need to derive the array base
677 // and index from the expression types.
678 Expr *BaseExpr, *IndexExpr;
679 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000680 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000681 BaseExpr = LHSExp;
682 IndexExpr = RHSExp;
683 // FIXME: need to deal with const...
684 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000685 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000686 // Handle the uncommon case of "123[Ptr]".
687 BaseExpr = RHSExp;
688 IndexExpr = LHSExp;
689 // FIXME: need to deal with const...
690 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000691 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
692 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000693 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000694
695 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000696 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
697 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000698 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000699 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000700 // FIXME: need to deal with const...
701 ResultType = VTy->getElementType();
702 } else {
703 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
704 RHSExp->getSourceRange());
705 }
706 // C99 6.5.2.1p1
707 if (!IndexExpr->getType()->isIntegerType())
708 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
709 IndexExpr->getSourceRange());
710
711 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
712 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000713 // void (*)(int)) and pointers to incomplete types. Functions are not
714 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000715 if (!ResultType->isObjectType())
716 return Diag(BaseExpr->getLocStart(),
717 diag::err_typecheck_subscript_not_object,
718 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
719
720 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
721}
722
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000723QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000724CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000725 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000726 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000727
728 // This flag determines whether or not the component is to be treated as a
729 // special name, or a regular GLSL-style component access.
730 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000731
732 // The vector accessor can't exceed the number of elements.
733 const char *compStr = CompName.getName();
734 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000735 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000736 baseType.getAsString(), SourceRange(CompLoc));
737 return QualType();
738 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000739
740 // Check that we've found one of the special components, or that the component
741 // names must come from the same set.
742 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
743 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
744 SpecialComponent = true;
745 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000746 do
747 compStr++;
748 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
749 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
750 do
751 compStr++;
752 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
753 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
754 do
755 compStr++;
756 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
757 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000758
Nate Begemanc8e51f82008-05-09 06:41:27 +0000759 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000760 // We didn't get to the end of the string. This means the component names
761 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000762 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000763 std::string(compStr,compStr+1), SourceRange(CompLoc));
764 return QualType();
765 }
766 // Each component accessor can't exceed the vector type.
767 compStr = CompName.getName();
768 while (*compStr) {
769 if (vecType->isAccessorWithinNumElements(*compStr))
770 compStr++;
771 else
772 break;
773 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000774 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000775 // We didn't get to the end of the string. This means a component accessor
776 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000777 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000778 baseType.getAsString(), SourceRange(CompLoc));
779 return QualType();
780 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000781
782 // If we have a special component name, verify that the current vector length
783 // is an even number, since all special component names return exactly half
784 // the elements.
785 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
786 return QualType();
787 }
788
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000789 // The component accessor looks fine - now we need to compute the actual type.
790 // The vector type is implied by the component accessor. For example,
791 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000792 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
793 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
794 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000795 if (CompSize == 1)
796 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000797
Nate Begemanaf6ed502008-04-18 23:10:10 +0000798 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000799 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000800 // diagostics look bad. We want extended vector types to appear built-in.
801 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
802 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
803 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000804 }
805 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000806}
807
Chris Lattner4b009652007-07-25 00:24:17 +0000808Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000809ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000810 tok::TokenKind OpKind, SourceLocation MemberLoc,
811 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000812 Expr *BaseExpr = static_cast<Expr *>(Base);
813 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000814
815 // Perform default conversions.
816 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000817
Steve Naroff2cb66382007-07-26 03:11:44 +0000818 QualType BaseType = BaseExpr->getType();
819 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000820
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000821 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
822 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000823 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000824 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000825 BaseType = PT->getPointeeType();
826 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000827 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
828 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000829 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000830
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000831 // Handle field access to simple records. This also handles access to fields
832 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000833 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000834 RecordDecl *RDecl = RTy->getDecl();
835 if (RTy->isIncompleteType())
836 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
837 BaseExpr->getSourceRange());
838 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000839 FieldDecl *MemberDecl = RDecl->getMember(&Member);
840 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000841 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
842 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000843
844 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000845 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000846 QualType MemberType = MemberDecl->getType();
847 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000848 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000849 MemberType = MemberType.getQualifiedType(combinedQualifiers);
850
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000851 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000852 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000853 }
854
Chris Lattnere9d71612008-07-21 04:59:05 +0000855 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
856 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000857 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
858 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000859 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000860 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000861 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000862 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000863 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000864 }
865
Chris Lattnere9d71612008-07-21 04:59:05 +0000866 // Handle Objective-C property access, which is "Obj.property" where Obj is a
867 // pointer to a (potentially qualified) interface type.
868 const PointerType *PTy;
869 const ObjCInterfaceType *IFTy;
870 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
871 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
872 ObjCInterfaceDecl *IFace = IFTy->getDecl();
873
Chris Lattner55a24332008-07-21 06:44:27 +0000874 // FIXME: The logic for looking up nullary and unary selectors should be
875 // shared with the code in ActOnInstanceMessage.
876
Chris Lattnere9d71612008-07-21 04:59:05 +0000877 // Before we look for explicit property declarations, we check for
878 // nullary methods (which allow '.' notation).
879 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Chris Lattnere9d71612008-07-21 04:59:05 +0000880 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel))
881 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
882 MemberLoc, BaseExpr);
883
Chris Lattner55a24332008-07-21 06:44:27 +0000884 // If this reference is in an @implementation, check for 'private' methods.
885 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
886 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
887 if (ObjCImplementationDecl *ImpDecl =
888 ObjCImplementations[ClassDecl->getIdentifier()])
889 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel))
890 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
891 MemberLoc, BaseExpr);
892 }
893
Chris Lattnere9d71612008-07-21 04:59:05 +0000894 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
895 // @interface NSBundle : NSObject {}
896 // - (NSString *)bundlePath;
897 // - (void)setBundlePath:(NSString *)x;
898 // @end
899 // void someMethod() { frameworkBundle.bundlePath = 0; }
900 //
901 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
902 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
903
904 // Lastly, check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000905 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
906 E = IFTy->qual_end(); I != E; ++I)
907 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
908 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000909 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000910
911 // Handle 'field access' to vectors, such as 'V.xx'.
912 if (BaseType->isExtVectorType() && OpKind == tok::period) {
913 // Component access limited to variables (reject vec4.rg.g).
914 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
915 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000916 return Diag(MemberLoc, diag::err_ext_vector_component_access,
917 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000918 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
919 if (ret.isNull())
920 return true;
921 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
922 }
923
Chris Lattner7d5a8762008-07-21 05:35:34 +0000924 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
925 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000926}
927
Steve Naroff87d58b42007-09-16 03:34:24 +0000928/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000929/// This provides the location of the left/right parens and a list of comma
930/// locations.
931Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000932ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000933 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000934 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
935 Expr *Fn = static_cast<Expr *>(fn);
936 Expr **Args = reinterpret_cast<Expr**>(args);
937 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000938 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000939
940 // Promote the function operand.
941 UsualUnaryConversions(Fn);
942
943 // If we're directly calling a function, get the declaration for
944 // that function.
945 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
946 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
947 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
948
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000949 // Make the call expr early, before semantic checks. This guarantees cleanup
950 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000951 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000952 Context.BoolTy, RParenLoc));
953
Chris Lattner4b009652007-07-25 00:24:17 +0000954 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
955 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000956 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000957 if (PT == 0)
958 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
959 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000960 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
961 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000962 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
963 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000964
965 // We know the result type of the call, set it.
966 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000967
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000968 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000969 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
970 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000971 unsigned NumArgsInProto = Proto->getNumArgs();
972 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000973
Chris Lattner3e254fb2008-04-08 04:40:51 +0000974 // If too few arguments are available (and we don't have default
975 // arguments for the remaining parameters), don't make the call.
976 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000977 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000978 // Use default arguments for missing arguments
979 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000980 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000981 } else
982 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
983 Fn->getSourceRange());
984 }
985
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000986 // If too many are passed and not variadic, error on the extras and drop
987 // them.
988 if (NumArgs > NumArgsInProto) {
989 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000990 Diag(Args[NumArgsInProto]->getLocStart(),
991 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
992 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000993 Args[NumArgs-1]->getLocEnd()));
994 // This deletes the extra arguments.
995 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000996 }
997 NumArgsToCheck = NumArgsInProto;
998 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000999
Chris Lattner4b009652007-07-25 00:24:17 +00001000 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001001 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001002 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001003
1004 Expr *Arg;
1005 if (i < NumArgs)
1006 Arg = Args[i];
1007 else
1008 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001009 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001010
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001011 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001012 AssignConvertType ConvTy =
1013 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001014 TheCall->setArg(i, Arg);
1015
Chris Lattner005ed752008-01-04 18:04:52 +00001016 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1017 ArgType, Arg, "passing"))
1018 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001019 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001020
1021 // If this is a variadic call, handle args passed through "...".
1022 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001023 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001024 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1025 Expr *Arg = Args[i];
1026 DefaultArgumentPromotion(Arg);
1027 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001028 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001029 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001030 } else {
1031 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1032
Steve Naroffdb65e052007-08-28 23:30:39 +00001033 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001034 for (unsigned i = 0; i != NumArgs; i++) {
1035 Expr *Arg = Args[i];
1036 DefaultArgumentPromotion(Arg);
1037 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001038 }
Chris Lattner4b009652007-07-25 00:24:17 +00001039 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001040
Chris Lattner2e64c072007-08-10 20:18:51 +00001041 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001042 if (FDecl)
1043 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001044
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001045 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001046}
1047
1048Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001049ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001050 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001051 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001052 QualType literalType = QualType::getFromOpaquePtr(Ty);
1053 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001054 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001055 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001056
Eli Friedman8c2173d2008-05-20 05:22:08 +00001057 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001058 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001059 return Diag(LParenLoc,
1060 diag::err_variable_object_no_init,
1061 SourceRange(LParenLoc,
1062 literalExpr->getSourceRange().getEnd()));
1063 } else if (literalType->isIncompleteType()) {
1064 return Diag(LParenLoc,
1065 diag::err_typecheck_decl_incomplete_type,
1066 literalType.getAsString(),
1067 SourceRange(LParenLoc,
1068 literalExpr->getSourceRange().getEnd()));
1069 }
1070
Steve Narofff0b23542008-01-10 22:15:12 +00001071 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001072 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001073
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001074 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001075 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001076 if (CheckForConstantInitializer(literalExpr, literalType))
1077 return true;
1078 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001079 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001080}
1081
1082Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001083ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001084 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001085 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001086
Steve Naroff0acc9c92007-09-15 18:49:24 +00001087 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001088 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001089
Chris Lattner48d7f382008-04-02 04:24:33 +00001090 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1091 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1092 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001093}
1094
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001095bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001096 assert(VectorTy->isVectorType() && "Not a vector type!");
1097
1098 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001099 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001100 return Diag(R.getBegin(),
1101 Ty->isVectorType() ?
1102 diag::err_invalid_conversion_between_vectors :
1103 diag::err_invalid_conversion_between_vector_and_integer,
1104 VectorTy.getAsString().c_str(),
1105 Ty.getAsString().c_str(), R);
1106 } else
1107 return Diag(R.getBegin(),
1108 diag::err_invalid_conversion_between_vector_and_scalar,
1109 VectorTy.getAsString().c_str(),
1110 Ty.getAsString().c_str(), R);
1111
1112 return false;
1113}
1114
Chris Lattner4b009652007-07-25 00:24:17 +00001115Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001116ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001117 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001118 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001119
1120 Expr *castExpr = static_cast<Expr*>(Op);
1121 QualType castType = QualType::getFromOpaquePtr(Ty);
1122
Steve Naroff68adb482007-08-31 00:32:44 +00001123 UsualUnaryConversions(castExpr);
1124
Chris Lattner4b009652007-07-25 00:24:17 +00001125 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1126 // type needs to be scalar.
Chris Lattner08b3c472008-07-25 22:06:10 +00001127 if (castType->isVoidType()) {
1128 // Cast to void allows any expr type.
1129 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1130 // GCC struct/union extension: allow cast to self.
1131 if (Context.getCanonicalType(castType) !=
1132 Context.getCanonicalType(castExpr->getType()) ||
1133 (!castType->isStructureType() && !castType->isUnionType())) {
1134 // Reject any other conversions to non-scalar types.
1135 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
1136 castType.getAsString(), castExpr->getSourceRange());
Steve Naroff5ad85292008-06-03 12:56:35 +00001137 }
Chris Lattner08b3c472008-07-25 22:06:10 +00001138
1139 // accept this, but emit an ext-warn.
1140 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
1141 castType.getAsString(), castExpr->getSourceRange());
1142 } else if (!castExpr->getType()->isScalarType() &&
1143 !castExpr->getType()->isVectorType()) {
1144 return Diag(castExpr->getLocStart(),
1145 diag::err_typecheck_expect_scalar_operand,
1146 castExpr->getType().getAsString(),castExpr->getSourceRange());
1147 } else if (castExpr->getType()->isVectorType()) {
1148 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1149 castExpr->getType(), castType))
1150 return true;
1151 } else if (castType->isVectorType()) {
1152 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1153 castType, castExpr->getType()))
1154 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001155 }
1156 return new CastExpr(castType, castExpr, LParenLoc);
1157}
1158
Chris Lattner98a425c2007-11-26 01:40:58 +00001159/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1160/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001161inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1162 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1163 UsualUnaryConversions(cond);
1164 UsualUnaryConversions(lex);
1165 UsualUnaryConversions(rex);
1166 QualType condT = cond->getType();
1167 QualType lexT = lex->getType();
1168 QualType rexT = rex->getType();
1169
1170 // first, check the condition.
1171 if (!condT->isScalarType()) { // C99 6.5.15p2
1172 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1173 condT.getAsString());
1174 return QualType();
1175 }
Chris Lattner992ae932008-01-06 22:42:25 +00001176
1177 // Now check the two expressions.
1178
1179 // If both operands have arithmetic type, do the usual arithmetic conversions
1180 // to find a common type: C99 6.5.15p3,5.
1181 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001182 UsualArithmeticConversions(lex, rex);
1183 return lex->getType();
1184 }
Chris Lattner992ae932008-01-06 22:42:25 +00001185
1186 // If both operands are the same structure or union type, the result is that
1187 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001188 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001189 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001190 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001191 // "If both the operands have structure or union type, the result has
1192 // that type." This implies that CV qualifiers are dropped.
1193 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001194 }
Chris Lattner992ae932008-01-06 22:42:25 +00001195
1196 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001197 // The following || allows only one side to be void (a GCC-ism).
1198 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001199 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001200 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1201 rex->getSourceRange());
1202 if (!rexT->isVoidType())
1203 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001204 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001205 ImpCastExprToType(lex, Context.VoidTy);
1206 ImpCastExprToType(rex, Context.VoidTy);
1207 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001208 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001209 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1210 // the type of the other operand."
1211 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001212 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001213 return lexT;
1214 }
1215 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001216 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001217 return rexT;
1218 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001219 // Handle the case where both operands are pointers before we handle null
1220 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001221 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1222 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1223 // get the "pointed to" types
1224 QualType lhptee = LHSPT->getPointeeType();
1225 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001226
Chris Lattner71225142007-07-31 21:27:01 +00001227 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1228 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001229 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001230 // Figure out necessary qualifiers (C99 6.5.15p6)
1231 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001232 QualType destType = Context.getPointerType(destPointee);
1233 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1234 ImpCastExprToType(rex, destType); // promote to void*
1235 return destType;
1236 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001237 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001238 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001239 QualType destType = Context.getPointerType(destPointee);
1240 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1241 ImpCastExprToType(rex, destType); // promote to void*
1242 return destType;
1243 }
Chris Lattner4b009652007-07-25 00:24:17 +00001244
Steve Naroff85f0dc52007-10-15 20:41:53 +00001245 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1246 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001247 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001248 lexT.getAsString(), rexT.getAsString(),
1249 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +00001250 // In this situation, we assume void* type. No especially good
1251 // reason, but this is what gcc does, and we do have to pick
1252 // to get a consistent AST.
1253 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1254 ImpCastExprToType(lex, voidPtrTy);
1255 ImpCastExprToType(rex, voidPtrTy);
1256 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +00001257 }
1258 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001259 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1260 // differently qualified versions of compatible types, the result type is
1261 // a pointer to an appropriately qualified version of the *composite*
1262 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001263 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001264 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001265 QualType compositeType = lexT;
1266 ImpCastExprToType(lex, compositeType);
1267 ImpCastExprToType(rex, compositeType);
1268 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001269 }
Chris Lattner4b009652007-07-25 00:24:17 +00001270 }
Steve Naroff605896f2008-05-31 22:33:45 +00001271 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1272 // evaluates to "struct objc_object *" (and is handled above when comparing
1273 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1274 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1275 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1276 return Context.getObjCIdType();
1277 }
Chris Lattner992ae932008-01-06 22:42:25 +00001278 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001279 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1280 lexT.getAsString(), rexT.getAsString(),
1281 lex->getSourceRange(), rex->getSourceRange());
1282 return QualType();
1283}
1284
Steve Naroff87d58b42007-09-16 03:34:24 +00001285/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001286/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001287Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001288 SourceLocation ColonLoc,
1289 ExprTy *Cond, ExprTy *LHS,
1290 ExprTy *RHS) {
1291 Expr *CondExpr = (Expr *) Cond;
1292 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001293
1294 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1295 // was the condition.
1296 bool isLHSNull = LHSExpr == 0;
1297 if (isLHSNull)
1298 LHSExpr = CondExpr;
1299
Chris Lattner4b009652007-07-25 00:24:17 +00001300 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1301 RHSExpr, QuestionLoc);
1302 if (result.isNull())
1303 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001304 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1305 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001306}
1307
Chris Lattner4b009652007-07-25 00:24:17 +00001308
1309// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1310// being closely modeled after the C99 spec:-). The odd characteristic of this
1311// routine is it effectively iqnores the qualifiers on the top level pointee.
1312// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1313// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001314Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001315Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1316 QualType lhptee, rhptee;
1317
1318 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001319 lhptee = lhsType->getAsPointerType()->getPointeeType();
1320 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001321
1322 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001323 lhptee = Context.getCanonicalType(lhptee);
1324 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001325
Chris Lattner005ed752008-01-04 18:04:52 +00001326 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001327
1328 // C99 6.5.16.1p1: This following citation is common to constraints
1329 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1330 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001331 // FIXME: Handle ASQualType
1332 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1333 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001334 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001335
1336 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1337 // incomplete type and the other is a pointer to a qualified or unqualified
1338 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001339 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001340 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001341 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001342
1343 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001344 assert(rhptee->isFunctionType());
1345 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001346 }
1347
1348 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001349 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001350 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001351
1352 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001353 assert(lhptee->isFunctionType());
1354 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001355 }
1356
Chris Lattner4b009652007-07-25 00:24:17 +00001357 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1358 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001359 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1360 rhptee.getUnqualifiedType()))
1361 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001362 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001363}
1364
1365/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1366/// has code to accommodate several GCC extensions when type checking
1367/// pointers. Here are some objectionable examples that GCC considers warnings:
1368///
1369/// int a, *pint;
1370/// short *pshort;
1371/// struct foo *pfoo;
1372///
1373/// pint = pshort; // warning: assignment from incompatible pointer type
1374/// a = pint; // warning: assignment makes integer from pointer without a cast
1375/// pint = a; // warning: assignment makes pointer from integer without a cast
1376/// pint = pfoo; // warning: assignment from incompatible pointer type
1377///
1378/// As a result, the code for dealing with pointers is more complex than the
1379/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001380///
Chris Lattner005ed752008-01-04 18:04:52 +00001381Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001382Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001383 // Get canonical types. We're not formatting these types, just comparing
1384 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001385 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1386 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001387
1388 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001389 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001390
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001391 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001392 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001393 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001394 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001395 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001396
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001397 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1398 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001399 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001400 // Relax integer conversions like we do for pointers below.
1401 if (rhsType->isIntegerType())
1402 return IntToPointer;
1403 if (lhsType->isIntegerType())
1404 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001405 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001406 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001407
Nate Begemanc5f0f652008-07-14 18:02:46 +00001408 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001409 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001410 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1411 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001412 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001413
Nate Begemanc5f0f652008-07-14 18:02:46 +00001414 // If we are allowing lax vector conversions, and LHS and RHS are both
1415 // vectors, the total size only needs to be the same. This is a bitcast;
1416 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001417 if (getLangOptions().LaxVectorConversions &&
1418 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001419 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1420 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001421 }
1422 return Incompatible;
1423 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001424
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001425 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001426 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001427
Chris Lattner390564e2008-04-07 06:49:41 +00001428 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001429 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001430 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001431
Chris Lattner390564e2008-04-07 06:49:41 +00001432 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001433 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001434 return Incompatible;
1435 }
1436
Chris Lattner390564e2008-04-07 06:49:41 +00001437 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001438 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001439 if (lhsType == Context.BoolTy)
1440 return Compatible;
1441
1442 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001443 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001444
Chris Lattner390564e2008-04-07 06:49:41 +00001445 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001446 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001447 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001448 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001449
Chris Lattner1853da22008-01-04 23:18:45 +00001450 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001451 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001452 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001453 }
1454 return Incompatible;
1455}
1456
Chris Lattner005ed752008-01-04 18:04:52 +00001457Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001458Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001459 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1460 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001461 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001462 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001463 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001464 return Compatible;
1465 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001466 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001467 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001468 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001469 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001470 //
1471 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1472 // are better understood.
1473 if (!lhsType->isReferenceType())
1474 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001475
Chris Lattner005ed752008-01-04 18:04:52 +00001476 Sema::AssignConvertType result =
1477 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001478
1479 // C99 6.5.16.1p2: The value of the right operand is converted to the
1480 // type of the assignment expression.
1481 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001482 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001483 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001484}
1485
Chris Lattner005ed752008-01-04 18:04:52 +00001486Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001487Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1488 return CheckAssignmentConstraints(lhsType, rhsType);
1489}
1490
Chris Lattner2c8bff72007-12-12 05:47:28 +00001491QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001492 Diag(loc, diag::err_typecheck_invalid_operands,
1493 lex->getType().getAsString(), rex->getType().getAsString(),
1494 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001495 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001496}
1497
1498inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1499 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001500 // For conversion purposes, we ignore any qualifiers.
1501 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001502 QualType lhsType =
1503 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1504 QualType rhsType =
1505 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001506
Nate Begemanc5f0f652008-07-14 18:02:46 +00001507 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001508 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001509 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001510
Nate Begemanc5f0f652008-07-14 18:02:46 +00001511 // Handle the case of a vector & extvector type of the same size and element
1512 // type. It would be nice if we only had one vector type someday.
1513 if (getLangOptions().LaxVectorConversions)
1514 if (const VectorType *LV = lhsType->getAsVectorType())
1515 if (const VectorType *RV = rhsType->getAsVectorType())
1516 if (LV->getElementType() == RV->getElementType() &&
1517 LV->getNumElements() == RV->getNumElements())
1518 return lhsType->isExtVectorType() ? lhsType : rhsType;
1519
1520 // If the lhs is an extended vector and the rhs is a scalar of the same type
1521 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001522 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001523 QualType eltType = V->getElementType();
1524
1525 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1526 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1527 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001528 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001529 return lhsType;
1530 }
1531 }
1532
Nate Begemanc5f0f652008-07-14 18:02:46 +00001533 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001534 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001535 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001536 QualType eltType = V->getElementType();
1537
1538 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1539 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1540 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001541 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001542 return rhsType;
1543 }
1544 }
1545
Chris Lattner4b009652007-07-25 00:24:17 +00001546 // You cannot convert between vector values of different size.
1547 Diag(loc, diag::err_typecheck_vector_not_convertable,
1548 lex->getType().getAsString(), rex->getType().getAsString(),
1549 lex->getSourceRange(), rex->getSourceRange());
1550 return QualType();
1551}
1552
1553inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001554 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001555{
1556 QualType lhsType = lex->getType(), rhsType = rex->getType();
1557
1558 if (lhsType->isVectorType() || rhsType->isVectorType())
1559 return CheckVectorOperands(loc, lex, rex);
1560
Steve Naroff8f708362007-08-24 19:07:16 +00001561 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001562
Chris Lattner4b009652007-07-25 00:24:17 +00001563 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001564 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001565 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001566}
1567
1568inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001569 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001570{
1571 QualType lhsType = lex->getType(), rhsType = rex->getType();
1572
Steve Naroff8f708362007-08-24 19:07:16 +00001573 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001574
Chris Lattner4b009652007-07-25 00:24:17 +00001575 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001576 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001577 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001578}
1579
1580inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001581 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001582{
1583 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1584 return CheckVectorOperands(loc, lex, rex);
1585
Steve Naroff8f708362007-08-24 19:07:16 +00001586 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001587
Chris Lattner4b009652007-07-25 00:24:17 +00001588 // handle the common case first (both operands are arithmetic).
1589 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001590 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001591
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001592 // Put any potential pointer into PExp
1593 Expr* PExp = lex, *IExp = rex;
1594 if (IExp->getType()->isPointerType())
1595 std::swap(PExp, IExp);
1596
1597 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1598 if (IExp->getType()->isIntegerType()) {
1599 // Check for arithmetic on pointers to incomplete types
1600 if (!PTy->getPointeeType()->isObjectType()) {
1601 if (PTy->getPointeeType()->isVoidType()) {
1602 Diag(loc, diag::ext_gnu_void_ptr,
1603 lex->getSourceRange(), rex->getSourceRange());
1604 } else {
1605 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1606 lex->getType().getAsString(), lex->getSourceRange());
1607 return QualType();
1608 }
1609 }
1610 return PExp->getType();
1611 }
1612 }
1613
Chris Lattner2c8bff72007-12-12 05:47:28 +00001614 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001615}
1616
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001617// C99 6.5.6
1618QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1619 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001620 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1621 return CheckVectorOperands(loc, lex, rex);
1622
Steve Naroff8f708362007-08-24 19:07:16 +00001623 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001624
Chris Lattnerf6da2912007-12-09 21:53:25 +00001625 // Enforce type constraints: C99 6.5.6p3.
1626
1627 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001628 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001629 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001630
1631 // Either ptr - int or ptr - ptr.
1632 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001633 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001634
Chris Lattnerf6da2912007-12-09 21:53:25 +00001635 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001636 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001637 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001638 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001639 Diag(loc, diag::ext_gnu_void_ptr,
1640 lex->getSourceRange(), rex->getSourceRange());
1641 } else {
1642 Diag(loc, diag::err_typecheck_sub_ptr_object,
1643 lex->getType().getAsString(), lex->getSourceRange());
1644 return QualType();
1645 }
1646 }
1647
1648 // The result type of a pointer-int computation is the pointer type.
1649 if (rex->getType()->isIntegerType())
1650 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001651
Chris Lattnerf6da2912007-12-09 21:53:25 +00001652 // Handle pointer-pointer subtractions.
1653 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001654 QualType rpointee = RHSPTy->getPointeeType();
1655
Chris Lattnerf6da2912007-12-09 21:53:25 +00001656 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001657 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001658 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001659 if (rpointee->isVoidType()) {
1660 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001661 Diag(loc, diag::ext_gnu_void_ptr,
1662 lex->getSourceRange(), rex->getSourceRange());
1663 } else {
1664 Diag(loc, diag::err_typecheck_sub_ptr_object,
1665 rex->getType().getAsString(), rex->getSourceRange());
1666 return QualType();
1667 }
1668 }
1669
1670 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001671 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1672 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001673 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1674 lex->getType().getAsString(), rex->getType().getAsString(),
1675 lex->getSourceRange(), rex->getSourceRange());
1676 return QualType();
1677 }
1678
1679 return Context.getPointerDiffType();
1680 }
1681 }
1682
Chris Lattner2c8bff72007-12-12 05:47:28 +00001683 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001684}
1685
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001686// C99 6.5.7
1687QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1688 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001689 // C99 6.5.7p2: Each of the operands shall have integer type.
1690 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1691 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001692
Chris Lattner2c8bff72007-12-12 05:47:28 +00001693 // Shifts don't perform usual arithmetic conversions, they just do integer
1694 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001695 if (!isCompAssign)
1696 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001697 UsualUnaryConversions(rex);
1698
1699 // "The type of the result is that of the promoted left operand."
1700 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001701}
1702
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001703// C99 6.5.8
1704QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1705 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001706 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1707 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1708
Chris Lattner254f3bc2007-08-26 01:18:55 +00001709 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001710 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1711 UsualArithmeticConversions(lex, rex);
1712 else {
1713 UsualUnaryConversions(lex);
1714 UsualUnaryConversions(rex);
1715 }
Chris Lattner4b009652007-07-25 00:24:17 +00001716 QualType lType = lex->getType();
1717 QualType rType = rex->getType();
1718
Ted Kremenek486509e2007-10-29 17:13:39 +00001719 // For non-floating point types, check for self-comparisons of the form
1720 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1721 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001722 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001723 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1724 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001725 if (DRL->getDecl() == DRR->getDecl())
1726 Diag(loc, diag::warn_selfcomparison);
1727 }
1728
Chris Lattner254f3bc2007-08-26 01:18:55 +00001729 if (isRelational) {
1730 if (lType->isRealType() && rType->isRealType())
1731 return Context.IntTy;
1732 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001733 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001734 if (lType->isFloatingType()) {
1735 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001736 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001737 }
1738
Chris Lattner254f3bc2007-08-26 01:18:55 +00001739 if (lType->isArithmeticType() && rType->isArithmeticType())
1740 return Context.IntTy;
1741 }
Chris Lattner4b009652007-07-25 00:24:17 +00001742
Chris Lattner22be8422007-08-26 01:10:14 +00001743 bool LHSIsNull = lex->isNullPointerConstant(Context);
1744 bool RHSIsNull = rex->isNullPointerConstant(Context);
1745
Chris Lattner254f3bc2007-08-26 01:18:55 +00001746 // All of the following pointer related warnings are GCC extensions, except
1747 // when handling null pointer constants. One day, we can consider making them
1748 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001749 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001750 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001751 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001752 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001753 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00001754
Steve Naroff3b435622007-11-13 14:57:38 +00001755 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001756 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1757 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1758 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001759 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1760 lType.getAsString(), rType.getAsString(),
1761 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001762 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001763 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001764 return Context.IntTy;
1765 }
Steve Naroff936c4362008-06-03 14:04:54 +00001766 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1767 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1768 ImpCastExprToType(rex, lType);
1769 return Context.IntTy;
1770 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001771 }
Steve Naroff936c4362008-06-03 14:04:54 +00001772 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1773 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001774 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001775 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1776 lType.getAsString(), rType.getAsString(),
1777 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001778 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001779 return Context.IntTy;
1780 }
Steve Naroff936c4362008-06-03 14:04:54 +00001781 if (lType->isIntegerType() &&
1782 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001783 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001784 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1785 lType.getAsString(), rType.getAsString(),
1786 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001787 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001788 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001789 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001790 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001791}
1792
Nate Begemanc5f0f652008-07-14 18:02:46 +00001793/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1794/// operates on extended vector types. Instead of producing an IntTy result,
1795/// like a scalar comparison, a vector comparison produces a vector of integer
1796/// types.
1797QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1798 SourceLocation loc,
1799 bool isRelational) {
1800 // Check to make sure we're operating on vectors of the same type and width,
1801 // Allowing one side to be a scalar of element type.
1802 QualType vType = CheckVectorOperands(loc, lex, rex);
1803 if (vType.isNull())
1804 return vType;
1805
1806 QualType lType = lex->getType();
1807 QualType rType = rex->getType();
1808
1809 // For non-floating point types, check for self-comparisons of the form
1810 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1811 // often indicate logic errors in the program.
1812 if (!lType->isFloatingType()) {
1813 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1814 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1815 if (DRL->getDecl() == DRR->getDecl())
1816 Diag(loc, diag::warn_selfcomparison);
1817 }
1818
1819 // Check for comparisons of floating point operands using != and ==.
1820 if (!isRelational && lType->isFloatingType()) {
1821 assert (rType->isFloatingType());
1822 CheckFloatComparison(loc,lex,rex);
1823 }
1824
1825 // Return the type for the comparison, which is the same as vector type for
1826 // integer vectors, or an integer type of identical size and number of
1827 // elements for floating point vectors.
1828 if (lType->isIntegerType())
1829 return lType;
1830
1831 const VectorType *VTy = lType->getAsVectorType();
1832
1833 // FIXME: need to deal with non-32b int / non-64b long long
1834 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1835 if (TypeSize == 32) {
1836 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1837 }
1838 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1839 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1840}
1841
Chris Lattner4b009652007-07-25 00:24:17 +00001842inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001843 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001844{
1845 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1846 return CheckVectorOperands(loc, lex, rex);
1847
Steve Naroff8f708362007-08-24 19:07:16 +00001848 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001849
1850 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001851 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001852 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001853}
1854
1855inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1856 Expr *&lex, Expr *&rex, SourceLocation loc)
1857{
1858 UsualUnaryConversions(lex);
1859 UsualUnaryConversions(rex);
1860
Eli Friedmanbea3f842008-05-13 20:16:47 +00001861 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001862 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001863 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001864}
1865
1866inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001867 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001868{
1869 QualType lhsType = lex->getType();
1870 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00001871 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001872
1873 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001874 case Expr::MLV_Valid:
1875 break;
1876 case Expr::MLV_ConstQualified:
1877 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1878 return QualType();
1879 case Expr::MLV_ArrayType:
1880 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1881 lhsType.getAsString(), lex->getSourceRange());
1882 return QualType();
1883 case Expr::MLV_NotObjectType:
1884 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1885 lhsType.getAsString(), lex->getSourceRange());
1886 return QualType();
1887 case Expr::MLV_InvalidExpression:
1888 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1889 lex->getSourceRange());
1890 return QualType();
1891 case Expr::MLV_IncompleteType:
1892 case Expr::MLV_IncompleteVoidType:
1893 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1894 lhsType.getAsString(), lex->getSourceRange());
1895 return QualType();
1896 case Expr::MLV_DuplicateVectorComponents:
1897 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1898 lex->getSourceRange());
1899 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001900 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001901
Chris Lattner005ed752008-01-04 18:04:52 +00001902 AssignConvertType ConvTy;
1903 if (compoundType.isNull())
1904 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1905 else
1906 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1907
1908 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1909 rex, "assigning"))
1910 return QualType();
1911
Chris Lattner4b009652007-07-25 00:24:17 +00001912 // C99 6.5.16p3: The type of an assignment expression is the type of the
1913 // left operand unless the left operand has qualified type, in which case
1914 // it is the unqualified version of the type of the left operand.
1915 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1916 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001917 // C++ 5.17p1: the type of the assignment expression is that of its left
1918 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001919 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001920}
1921
1922inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1923 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00001924
1925 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
1926 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001927 return rex->getType();
1928}
1929
1930/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1931/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1932QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1933 QualType resType = op->getType();
1934 assert(!resType.isNull() && "no type for increment/decrement expression");
1935
Steve Naroffd30e1932007-08-24 17:20:07 +00001936 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001937 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001938 if (pt->getPointeeType()->isVoidType()) {
1939 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1940 } else if (!pt->getPointeeType()->isObjectType()) {
1941 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001942 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1943 resType.getAsString(), op->getSourceRange());
1944 return QualType();
1945 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001946 } else if (!resType->isRealType()) {
1947 if (resType->isComplexType())
1948 // C99 does not support ++/-- on complex types.
1949 Diag(OpLoc, diag::ext_integer_increment_complex,
1950 resType.getAsString(), op->getSourceRange());
1951 else {
1952 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1953 resType.getAsString(), op->getSourceRange());
1954 return QualType();
1955 }
Chris Lattner4b009652007-07-25 00:24:17 +00001956 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001957 // At this point, we know we have a real, complex or pointer type.
1958 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00001959 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001960 if (mlval != Expr::MLV_Valid) {
1961 // FIXME: emit a more precise diagnostic...
1962 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1963 op->getSourceRange());
1964 return QualType();
1965 }
1966 return resType;
1967}
1968
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001969/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001970/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00001971/// where the declaration is needed for type checking. We only need to
1972/// handle cases when the expression references a function designator
1973/// or is an lvalue. Here are some examples:
1974/// - &(x) => x
1975/// - &*****f => f for f a function designator.
1976/// - &s.xx => s
1977/// - &s.zz[1].yy -> s, if zz is an array
1978/// - *(x + 1) -> x, if x is an array
1979/// - &"123"[2] -> 0
1980/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00001981static ValueDecl *getPrimaryDecl(Expr *E) {
1982 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001983 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001984 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001985 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001986 // Fields cannot be declared with a 'register' storage class.
1987 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001988 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001989 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001990 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001991 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00001992 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001993
Chris Lattner48d7f382008-04-02 04:24:33 +00001994 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001995 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001996 return 0;
1997 else
1998 return VD;
1999 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002000 case Stmt::UnaryOperatorClass: {
2001 UnaryOperator *UO = cast<UnaryOperator>(E);
2002
2003 switch(UO->getOpcode()) {
2004 case UnaryOperator::Deref: {
2005 // *(X + 1) refers to X if X is not a pointer.
2006 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2007 if (!VD || VD->getType()->isPointerType())
2008 return 0;
2009 return VD;
2010 }
2011 case UnaryOperator::Real:
2012 case UnaryOperator::Imag:
2013 case UnaryOperator::Extension:
2014 return getPrimaryDecl(UO->getSubExpr());
2015 default:
2016 return 0;
2017 }
2018 }
2019 case Stmt::BinaryOperatorClass: {
2020 BinaryOperator *BO = cast<BinaryOperator>(E);
2021
2022 // Handle cases involving pointer arithmetic. The result of an
2023 // Assign or AddAssign is not an lvalue so they can be ignored.
2024
2025 // (x + n) or (n + x) => x
2026 if (BO->getOpcode() == BinaryOperator::Add) {
2027 if (BO->getLHS()->getType()->isPointerType()) {
2028 return getPrimaryDecl(BO->getLHS());
2029 } else if (BO->getRHS()->getType()->isPointerType()) {
2030 return getPrimaryDecl(BO->getRHS());
2031 }
2032 }
2033
2034 return 0;
2035 }
Chris Lattner4b009652007-07-25 00:24:17 +00002036 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002037 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002038 case Stmt::ImplicitCastExprClass:
2039 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002040 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002041 default:
2042 return 0;
2043 }
2044}
2045
2046/// CheckAddressOfOperand - The operand of & must be either a function
2047/// designator or an lvalue designating an object. If it is an lvalue, the
2048/// object cannot be declared with storage class register or be a bit field.
2049/// Note: The usual conversions are *not* applied to the operand of the &
2050/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2051QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002052 if (getLangOptions().C99) {
2053 // Implement C99-only parts of addressof rules.
2054 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2055 if (uOp->getOpcode() == UnaryOperator::Deref)
2056 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2057 // (assuming the deref expression is valid).
2058 return uOp->getSubExpr()->getType();
2059 }
2060 // Technically, there should be a check for array subscript
2061 // expressions here, but the result of one is always an lvalue anyway.
2062 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002063 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002064 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002065
2066 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002067 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2068 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002069 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2070 op->getSourceRange());
2071 return QualType();
2072 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002073 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2074 if (MemExpr->getMemberDecl()->isBitField()) {
2075 Diag(OpLoc, diag::err_typecheck_address_of,
2076 std::string("bit-field"), op->getSourceRange());
2077 return QualType();
2078 }
2079 // Check for Apple extension for accessing vector components.
2080 } else if (isa<ArraySubscriptExpr>(op) &&
2081 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2082 Diag(OpLoc, diag::err_typecheck_address_of,
2083 std::string("vector"), op->getSourceRange());
2084 return QualType();
2085 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002086 // We have an lvalue with a decl. Make sure the decl is not declared
2087 // with the register storage-class specifier.
2088 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2089 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002090 Diag(OpLoc, diag::err_typecheck_address_of,
2091 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002092 return QualType();
2093 }
2094 } else
2095 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002096 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002097
Chris Lattner4b009652007-07-25 00:24:17 +00002098 // If the operand has type "type", the result has type "pointer to type".
2099 return Context.getPointerType(op->getType());
2100}
2101
2102QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2103 UsualUnaryConversions(op);
2104 QualType qType = op->getType();
2105
Chris Lattner7931f4a2007-07-31 16:53:04 +00002106 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002107 // Note that per both C89 and C99, this is always legal, even
2108 // if ptype is an incomplete type or void.
2109 // It would be possible to warn about dereferencing a
2110 // void pointer, but it's completely well-defined,
2111 // and such a warning is unlikely to catch any mistakes.
2112 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002113 }
2114 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2115 qType.getAsString(), op->getSourceRange());
2116 return QualType();
2117}
2118
2119static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2120 tok::TokenKind Kind) {
2121 BinaryOperator::Opcode Opc;
2122 switch (Kind) {
2123 default: assert(0 && "Unknown binop!");
2124 case tok::star: Opc = BinaryOperator::Mul; break;
2125 case tok::slash: Opc = BinaryOperator::Div; break;
2126 case tok::percent: Opc = BinaryOperator::Rem; break;
2127 case tok::plus: Opc = BinaryOperator::Add; break;
2128 case tok::minus: Opc = BinaryOperator::Sub; break;
2129 case tok::lessless: Opc = BinaryOperator::Shl; break;
2130 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2131 case tok::lessequal: Opc = BinaryOperator::LE; break;
2132 case tok::less: Opc = BinaryOperator::LT; break;
2133 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2134 case tok::greater: Opc = BinaryOperator::GT; break;
2135 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2136 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2137 case tok::amp: Opc = BinaryOperator::And; break;
2138 case tok::caret: Opc = BinaryOperator::Xor; break;
2139 case tok::pipe: Opc = BinaryOperator::Or; break;
2140 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2141 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2142 case tok::equal: Opc = BinaryOperator::Assign; break;
2143 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2144 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2145 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2146 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2147 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2148 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2149 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2150 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2151 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2152 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2153 case tok::comma: Opc = BinaryOperator::Comma; break;
2154 }
2155 return Opc;
2156}
2157
2158static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2159 tok::TokenKind Kind) {
2160 UnaryOperator::Opcode Opc;
2161 switch (Kind) {
2162 default: assert(0 && "Unknown unary op!");
2163 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2164 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2165 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2166 case tok::star: Opc = UnaryOperator::Deref; break;
2167 case tok::plus: Opc = UnaryOperator::Plus; break;
2168 case tok::minus: Opc = UnaryOperator::Minus; break;
2169 case tok::tilde: Opc = UnaryOperator::Not; break;
2170 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2171 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2172 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2173 case tok::kw___real: Opc = UnaryOperator::Real; break;
2174 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2175 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2176 }
2177 return Opc;
2178}
2179
2180// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002181Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002182 ExprTy *LHS, ExprTy *RHS) {
2183 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2184 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2185
Steve Naroff87d58b42007-09-16 03:34:24 +00002186 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2187 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002188
2189 QualType ResultTy; // Result type of the binary operator.
2190 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2191
2192 switch (Opc) {
2193 default:
2194 assert(0 && "Unknown binary expr!");
2195 case BinaryOperator::Assign:
2196 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2197 break;
2198 case BinaryOperator::Mul:
2199 case BinaryOperator::Div:
2200 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2201 break;
2202 case BinaryOperator::Rem:
2203 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2204 break;
2205 case BinaryOperator::Add:
2206 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2207 break;
2208 case BinaryOperator::Sub:
2209 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2210 break;
2211 case BinaryOperator::Shl:
2212 case BinaryOperator::Shr:
2213 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2214 break;
2215 case BinaryOperator::LE:
2216 case BinaryOperator::LT:
2217 case BinaryOperator::GE:
2218 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002219 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002220 break;
2221 case BinaryOperator::EQ:
2222 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002223 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002224 break;
2225 case BinaryOperator::And:
2226 case BinaryOperator::Xor:
2227 case BinaryOperator::Or:
2228 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2229 break;
2230 case BinaryOperator::LAnd:
2231 case BinaryOperator::LOr:
2232 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2233 break;
2234 case BinaryOperator::MulAssign:
2235 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002236 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002237 if (!CompTy.isNull())
2238 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2239 break;
2240 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002241 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002242 if (!CompTy.isNull())
2243 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2244 break;
2245 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002246 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002247 if (!CompTy.isNull())
2248 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2249 break;
2250 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002251 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002252 if (!CompTy.isNull())
2253 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2254 break;
2255 case BinaryOperator::ShlAssign:
2256 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002257 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002258 if (!CompTy.isNull())
2259 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2260 break;
2261 case BinaryOperator::AndAssign:
2262 case BinaryOperator::XorAssign:
2263 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002264 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002265 if (!CompTy.isNull())
2266 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2267 break;
2268 case BinaryOperator::Comma:
2269 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2270 break;
2271 }
2272 if (ResultTy.isNull())
2273 return true;
2274 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002275 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002276 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002277 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002278}
2279
2280// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002281Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002282 ExprTy *input) {
2283 Expr *Input = (Expr*)input;
2284 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2285 QualType resultType;
2286 switch (Opc) {
2287 default:
2288 assert(0 && "Unimplemented unary expr!");
2289 case UnaryOperator::PreInc:
2290 case UnaryOperator::PreDec:
2291 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2292 break;
2293 case UnaryOperator::AddrOf:
2294 resultType = CheckAddressOfOperand(Input, OpLoc);
2295 break;
2296 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002297 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002298 resultType = CheckIndirectionOperand(Input, OpLoc);
2299 break;
2300 case UnaryOperator::Plus:
2301 case UnaryOperator::Minus:
2302 UsualUnaryConversions(Input);
2303 resultType = Input->getType();
2304 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2305 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2306 resultType.getAsString());
2307 break;
2308 case UnaryOperator::Not: // bitwise complement
2309 UsualUnaryConversions(Input);
2310 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002311 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2312 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2313 // C99 does not support '~' for complex conjugation.
2314 Diag(OpLoc, diag::ext_integer_complement_complex,
2315 resultType.getAsString(), Input->getSourceRange());
2316 else if (!resultType->isIntegerType())
2317 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2318 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002319 break;
2320 case UnaryOperator::LNot: // logical negation
2321 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2322 DefaultFunctionArrayConversion(Input);
2323 resultType = Input->getType();
2324 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2325 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2326 resultType.getAsString());
2327 // LNot always has type int. C99 6.5.3.3p5.
2328 resultType = Context.IntTy;
2329 break;
2330 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002331 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2332 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002333 break;
2334 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002335 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2336 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002337 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002338 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002339 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002340 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002341 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002342 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002343 resultType = Input->getType();
2344 break;
2345 }
2346 if (resultType.isNull())
2347 return true;
2348 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2349}
2350
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002351/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2352Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002353 SourceLocation LabLoc,
2354 IdentifierInfo *LabelII) {
2355 // Look up the record for this label identifier.
2356 LabelStmt *&LabelDecl = LabelMap[LabelII];
2357
Daniel Dunbar879788d2008-08-04 16:51:22 +00002358 // If we haven't seen this label yet, create a forward reference. It
2359 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002360 if (LabelDecl == 0)
2361 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2362
2363 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002364 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2365 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002366}
2367
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002368Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002369 SourceLocation RPLoc) { // "({..})"
2370 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2371 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2372 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2373
2374 // FIXME: there are a variety of strange constraints to enforce here, for
2375 // example, it is not possible to goto into a stmt expression apparently.
2376 // More semantic analysis is needed.
2377
2378 // FIXME: the last statement in the compount stmt has its value used. We
2379 // should not warn about it being unused.
2380
2381 // If there are sub stmts in the compound stmt, take the type of the last one
2382 // as the type of the stmtexpr.
2383 QualType Ty = Context.VoidTy;
2384
Chris Lattner200964f2008-07-26 19:51:01 +00002385 if (!Compound->body_empty()) {
2386 Stmt *LastStmt = Compound->body_back();
2387 // If LastStmt is a label, skip down through into the body.
2388 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2389 LastStmt = Label->getSubStmt();
2390
2391 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002392 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002393 }
Chris Lattner4b009652007-07-25 00:24:17 +00002394
2395 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2396}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002397
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002398Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002399 SourceLocation TypeLoc,
2400 TypeTy *argty,
2401 OffsetOfComponent *CompPtr,
2402 unsigned NumComponents,
2403 SourceLocation RPLoc) {
2404 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2405 assert(!ArgTy.isNull() && "Missing type argument!");
2406
2407 // We must have at least one component that refers to the type, and the first
2408 // one is known to be a field designator. Verify that the ArgTy represents
2409 // a struct/union/class.
2410 if (!ArgTy->isRecordType())
2411 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2412
2413 // Otherwise, create a compound literal expression as the base, and
2414 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002415 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002416
Chris Lattnerb37522e2007-08-31 21:49:13 +00002417 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2418 // GCC extension, diagnose them.
2419 if (NumComponents != 1)
2420 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2421 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2422
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002423 for (unsigned i = 0; i != NumComponents; ++i) {
2424 const OffsetOfComponent &OC = CompPtr[i];
2425 if (OC.isBrackets) {
2426 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002427 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002428 if (!AT) {
2429 delete Res;
2430 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2431 Res->getType().getAsString());
2432 }
2433
Chris Lattner2af6a802007-08-30 17:59:59 +00002434 // FIXME: C++: Verify that operator[] isn't overloaded.
2435
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002436 // C99 6.5.2.1p1
2437 Expr *Idx = static_cast<Expr*>(OC.U.E);
2438 if (!Idx->getType()->isIntegerType())
2439 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2440 Idx->getSourceRange());
2441
2442 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2443 continue;
2444 }
2445
2446 const RecordType *RC = Res->getType()->getAsRecordType();
2447 if (!RC) {
2448 delete Res;
2449 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2450 Res->getType().getAsString());
2451 }
2452
2453 // Get the decl corresponding to this.
2454 RecordDecl *RD = RC->getDecl();
2455 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2456 if (!MemberDecl)
2457 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2458 OC.U.IdentInfo->getName(),
2459 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002460
2461 // FIXME: C++: Verify that MemberDecl isn't a static field.
2462 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002463 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2464 // matter here.
2465 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002466 }
2467
2468 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2469 BuiltinLoc);
2470}
2471
2472
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002473Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002474 TypeTy *arg1, TypeTy *arg2,
2475 SourceLocation RPLoc) {
2476 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2477 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2478
2479 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2480
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002481 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002482}
2483
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002484Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002485 ExprTy *expr1, ExprTy *expr2,
2486 SourceLocation RPLoc) {
2487 Expr *CondExpr = static_cast<Expr*>(cond);
2488 Expr *LHSExpr = static_cast<Expr*>(expr1);
2489 Expr *RHSExpr = static_cast<Expr*>(expr2);
2490
2491 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2492
2493 // The conditional expression is required to be a constant expression.
2494 llvm::APSInt condEval(32);
2495 SourceLocation ExpLoc;
2496 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2497 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2498 CondExpr->getSourceRange());
2499
2500 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2501 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2502 RHSExpr->getType();
2503 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2504}
2505
Nate Begemanbd881ef2008-01-30 20:50:20 +00002506/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002507/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002508/// The number of arguments has already been validated to match the number of
2509/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002510static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2511 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002512 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002513 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002514 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2515 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002516
2517 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002518 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002519 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002520 return true;
2521}
2522
2523Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2524 SourceLocation *CommaLocs,
2525 SourceLocation BuiltinLoc,
2526 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002527 // __builtin_overload requires at least 2 arguments
2528 if (NumArgs < 2)
2529 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2530 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002531
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002532 // The first argument is required to be a constant expression. It tells us
2533 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002534 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002535 Expr *NParamsExpr = Args[0];
2536 llvm::APSInt constEval(32);
2537 SourceLocation ExpLoc;
2538 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2539 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2540 NParamsExpr->getSourceRange());
2541
2542 // Verify that the number of parameters is > 0
2543 unsigned NumParams = constEval.getZExtValue();
2544 if (NumParams == 0)
2545 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2546 NParamsExpr->getSourceRange());
2547 // Verify that we have at least 1 + NumParams arguments to the builtin.
2548 if ((NumParams + 1) > NumArgs)
2549 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2550 SourceRange(BuiltinLoc, RParenLoc));
2551
2552 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002553 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002554 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002555 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2556 // UsualUnaryConversions will convert the function DeclRefExpr into a
2557 // pointer to function.
2558 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002559 const FunctionTypeProto *FnType = 0;
2560 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2561 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002562
2563 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2564 // parameters, and the number of parameters must match the value passed to
2565 // the builtin.
2566 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002567 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2568 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002569
2570 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002571 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002572 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002573 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002574 if (OE)
2575 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2576 OE->getFn()->getSourceRange());
2577 // Remember our match, and continue processing the remaining arguments
2578 // to catch any errors.
2579 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2580 BuiltinLoc, RParenLoc);
2581 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002582 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002583 // Return the newly created OverloadExpr node, if we succeded in matching
2584 // exactly one of the candidate functions.
2585 if (OE)
2586 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002587
2588 // If we didn't find a matching function Expr in the __builtin_overload list
2589 // the return an error.
2590 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002591 for (unsigned i = 0; i != NumParams; ++i) {
2592 if (i != 0) typeNames += ", ";
2593 typeNames += Args[i+1]->getType().getAsString();
2594 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002595
2596 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2597 SourceRange(BuiltinLoc, RParenLoc));
2598}
2599
Anders Carlsson36760332007-10-15 20:28:48 +00002600Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2601 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002602 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002603 Expr *E = static_cast<Expr*>(expr);
2604 QualType T = QualType::getFromOpaquePtr(type);
2605
2606 InitBuiltinVaListType();
2607
Chris Lattner005ed752008-01-04 18:04:52 +00002608 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2609 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002610 return Diag(E->getLocStart(),
2611 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2612 E->getType().getAsString(),
2613 E->getSourceRange());
2614
2615 // FIXME: Warn if a non-POD type is passed in.
2616
2617 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2618}
2619
Chris Lattner005ed752008-01-04 18:04:52 +00002620bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2621 SourceLocation Loc,
2622 QualType DstType, QualType SrcType,
2623 Expr *SrcExpr, const char *Flavor) {
2624 // Decode the result (notice that AST's are still created for extensions).
2625 bool isInvalid = false;
2626 unsigned DiagKind;
2627 switch (ConvTy) {
2628 default: assert(0 && "Unknown conversion type");
2629 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002630 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002631 DiagKind = diag::ext_typecheck_convert_pointer_int;
2632 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002633 case IntToPointer:
2634 DiagKind = diag::ext_typecheck_convert_int_pointer;
2635 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002636 case IncompatiblePointer:
2637 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2638 break;
2639 case FunctionVoidPointer:
2640 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2641 break;
2642 case CompatiblePointerDiscardsQualifiers:
2643 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2644 break;
2645 case Incompatible:
2646 DiagKind = diag::err_typecheck_convert_incompatible;
2647 isInvalid = true;
2648 break;
2649 }
2650
2651 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2652 SrcExpr->getSourceRange());
2653 return isInvalid;
2654}