blob: d49626c590b6f6f33132bce88775f6c990c7382e [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"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000024#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31
Chris Lattner299b8842008-07-25 21:10:04 +000032//===----------------------------------------------------------------------===//
33// Standard Promotions and Conversions
34//===----------------------------------------------------------------------===//
35
Chris Lattner299b8842008-07-25 21:10:04 +000036/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
37void Sema::DefaultFunctionArrayConversion(Expr *&E) {
38 QualType Ty = E->getType();
39 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
40
41 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
42 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
43 Ty = E->getType();
44 }
45 if (Ty->isFunctionType())
46 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000047 else if (Ty->isArrayType()) {
48 // In C90 mode, arrays only promote to pointers if the array expression is
49 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
50 // type 'array of type' is converted to an expression that has type 'pointer
51 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
52 // that has type 'array of type' ...". The relevant change is "an lvalue"
53 // (C90) to "an expression" (C99).
Chris Lattner25168a52008-07-26 21:30:36 +000054 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000055 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
56 }
Chris Lattner299b8842008-07-25 21:10:04 +000057}
58
59/// UsualUnaryConversions - Performs various conversions that are common to most
60/// operators (C99 6.3). The conversions of array and function types are
61/// sometimes surpressed. For example, the array->pointer conversion doesn't
62/// apply if the array is an argument to the sizeof or address (&) operators.
63/// In these instances, this routine should *not* be called.
64Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
65 QualType Ty = Expr->getType();
66 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
67
68 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
69 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
70 Ty = Expr->getType();
71 }
72 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
73 ImpCastExprToType(Expr, Context.IntTy);
74 else
75 DefaultFunctionArrayConversion(Expr);
76
77 return Expr;
78}
79
Chris Lattner9305c3d2008-07-25 22:25:12 +000080/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
81/// do not have a prototype. Arguments that have type float are promoted to
82/// double. All other argument types are converted by UsualUnaryConversions().
83void Sema::DefaultArgumentPromotion(Expr *&Expr) {
84 QualType Ty = Expr->getType();
85 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
86
87 // If this is a 'float' (CVR qualified or typedef) promote to double.
88 if (const BuiltinType *BT = Ty->getAsBuiltinType())
89 if (BT->getKind() == BuiltinType::Float)
90 return ImpCastExprToType(Expr, Context.DoubleTy);
91
92 UsualUnaryConversions(Expr);
93}
94
Chris Lattner299b8842008-07-25 21:10:04 +000095/// UsualArithmeticConversions - Performs various conversions that are common to
96/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
97/// routine returns the first non-arithmetic type found. The client is
98/// responsible for emitting appropriate error diagnostics.
99/// FIXME: verify the conversion rules for "complex int" are consistent with
100/// GCC.
101QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
102 bool isCompAssign) {
103 if (!isCompAssign) {
104 UsualUnaryConversions(lhsExpr);
105 UsualUnaryConversions(rhsExpr);
106 }
107 // For conversion purposes, we ignore any qualifiers.
108 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000109 QualType lhs =
110 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
111 QualType rhs =
112 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000113
114 // If both types are identical, no conversion is needed.
115 if (lhs == rhs)
116 return lhs;
117
118 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
119 // The caller can deal with this (e.g. pointer + int).
120 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
121 return lhs;
122
123 // At this point, we have two different arithmetic types.
124
125 // Handle complex types first (C99 6.3.1.8p1).
126 if (lhs->isComplexType() || rhs->isComplexType()) {
127 // if we have an integer operand, the result is the complex type.
128 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
129 // convert the rhs to the lhs complex type.
130 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
131 return lhs;
132 }
133 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
134 // convert the lhs to the rhs complex type.
135 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
136 return rhs;
137 }
138 // This handles complex/complex, complex/float, or float/complex.
139 // When both operands are complex, the shorter operand is converted to the
140 // type of the longer, and that is the type of the result. This corresponds
141 // to what is done when combining two real floating-point operands.
142 // The fun begins when size promotion occur across type domains.
143 // From H&S 6.3.4: When one operand is complex and the other is a real
144 // floating-point type, the less precise type is converted, within it's
145 // real or complex domain, to the precision of the other type. For example,
146 // when combining a "long double" with a "double _Complex", the
147 // "double _Complex" is promoted to "long double _Complex".
148 int result = Context.getFloatingTypeOrder(lhs, rhs);
149
150 if (result > 0) { // The left side is bigger, convert rhs.
151 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
152 if (!isCompAssign)
153 ImpCastExprToType(rhsExpr, rhs);
154 } else if (result < 0) { // The right side is bigger, convert lhs.
155 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
156 if (!isCompAssign)
157 ImpCastExprToType(lhsExpr, lhs);
158 }
159 // At this point, lhs and rhs have the same rank/size. Now, make sure the
160 // domains match. This is a requirement for our implementation, C99
161 // does not require this promotion.
162 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
163 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
164 if (!isCompAssign)
165 ImpCastExprToType(lhsExpr, rhs);
166 return rhs;
167 } else { // handle "_Complex double, double".
168 if (!isCompAssign)
169 ImpCastExprToType(rhsExpr, lhs);
170 return lhs;
171 }
172 }
173 return lhs; // The domain/size match exactly.
174 }
175 // Now handle "real" floating types (i.e. float, double, long double).
176 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
177 // if we have an integer operand, the result is the real floating type.
178 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
179 // convert rhs to the lhs floating point type.
180 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
181 return lhs;
182 }
183 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
184 // convert lhs to the rhs floating point type.
185 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
186 return rhs;
187 }
188 // We have two real floating types, float/complex combos were handled above.
189 // Convert the smaller operand to the bigger result.
190 int result = Context.getFloatingTypeOrder(lhs, rhs);
191
192 if (result > 0) { // convert the rhs
193 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
194 return lhs;
195 }
196 if (result < 0) { // convert the lhs
197 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
198 return rhs;
199 }
200 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
201 }
202 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
203 // Handle GCC complex int extension.
204 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
205 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
206
207 if (lhsComplexInt && rhsComplexInt) {
208 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
209 rhsComplexInt->getElementType()) >= 0) {
210 // convert the rhs
211 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
212 return lhs;
213 }
214 if (!isCompAssign)
215 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
216 return rhs;
217 } else if (lhsComplexInt && rhs->isIntegerType()) {
218 // convert the rhs to the lhs complex type.
219 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
220 return lhs;
221 } else if (rhsComplexInt && lhs->isIntegerType()) {
222 // convert the lhs to the rhs complex type.
223 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
224 return rhs;
225 }
226 }
227 // Finally, we have two differing integer types.
228 // The rules for this case are in C99 6.3.1.8
229 int compare = Context.getIntegerTypeOrder(lhs, rhs);
230 bool lhsSigned = lhs->isSignedIntegerType(),
231 rhsSigned = rhs->isSignedIntegerType();
232 QualType destType;
233 if (lhsSigned == rhsSigned) {
234 // Same signedness; use the higher-ranked type
235 destType = compare >= 0 ? lhs : rhs;
236 } else if (compare != (lhsSigned ? 1 : -1)) {
237 // The unsigned type has greater than or equal rank to the
238 // signed type, so use the unsigned type
239 destType = lhsSigned ? rhs : lhs;
240 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
241 // The two types are different widths; if we are here, that
242 // means the signed type is larger than the unsigned type, so
243 // use the signed type.
244 destType = lhsSigned ? lhs : rhs;
245 } else {
246 // The signed type is higher-ranked than the unsigned type,
247 // but isn't actually any bigger (like unsigned int and long
248 // on most 32-bit systems). Use the unsigned type corresponding
249 // to the signed type.
250 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
251 }
252 if (!isCompAssign) {
253 ImpCastExprToType(lhsExpr, destType);
254 ImpCastExprToType(rhsExpr, destType);
255 }
256 return destType;
257}
258
259//===----------------------------------------------------------------------===//
260// Semantic Analysis for various Expression Types
261//===----------------------------------------------------------------------===//
262
263
Steve Naroff87d58b42007-09-16 03:34:24 +0000264/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000265/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
266/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
267/// multiple tokens. However, the common case is that StringToks points to one
268/// string.
269///
270Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000271Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000272 assert(NumStringToks && "Must have at least one string!");
273
274 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
275 if (Literal.hadError)
276 return ExprResult(true);
277
278 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
279 for (unsigned i = 0; i != NumStringToks; ++i)
280 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000281
282 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000283 if (Literal.Pascal && Literal.GetStringLength() > 256)
284 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
285 SourceRange(StringToks[0].getLocation(),
286 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000287
Chris Lattnera6dcce32008-02-11 00:02:17 +0000288 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000289 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
291
292 // Get an array type for the string, according to C99 6.4.5. This includes
293 // the nul terminator character as well as the string length for pascal
294 // strings.
295 StrTy = Context.getConstantArrayType(StrTy,
296 llvm::APInt(32, Literal.GetStringLength()+1),
297 ArrayType::Normal, 0);
298
Chris Lattner4b009652007-07-25 00:24:17 +0000299 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
300 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000301 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000302 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000303 StringToks[NumStringToks-1].getLocation());
304}
305
306
Steve Naroff0acc9c92007-09-15 18:49:24 +0000307/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000308/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000309/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000310Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000311 IdentifierInfo &II,
312 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000313 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000314 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000315
316 // If this reference is in an Objective-C method, then ivar lookup happens as
317 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000318 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000319 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000320 // There are two cases to handle here. 1) scoped lookup could have failed,
321 // in which case we should look for an ivar. 2) scoped lookup could have
322 // found a decl, but that decl is outside the current method (i.e. a global
323 // variable). In these two cases, we do a lookup for an ivar with this
324 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000325 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000326 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000327 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000328 // FIXME: This should use a new expr for a direct reference, don't turn
329 // this into Self->ivar, just return a BareIVarExpr or something.
330 IdentifierInfo &II = Context.Idents.get("self");
331 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
332 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
333 static_cast<Expr*>(SelfExpr.Val), true, true);
334 }
335 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000336 // Needed to implement property "super.method" notation.
Steve Naroffe90d4cc2008-06-05 18:14:25 +0000337 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000338 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000339 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000340 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000341 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000342 }
343
Chris Lattner4b009652007-07-25 00:24:17 +0000344 if (D == 0) {
345 // Otherwise, this could be an implicitly declared function reference (legal
346 // in C90, extension in C99).
347 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000348 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000349 D = ImplicitlyDefineFunction(Loc, II, S);
350 else {
351 // If this name wasn't predeclared and if this is not a function call,
352 // diagnose the problem.
353 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
354 }
355 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000356
Steve Naroff91b03f72007-08-28 03:03:08 +0000357 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000358 // check if referencing an identifier with __attribute__((deprecated)).
359 if (VD->getAttr<DeprecatedAttr>())
360 Diag(Loc, diag::warn_deprecated, VD->getName());
361
Steve Naroffcae537d2007-08-28 18:45:29 +0000362 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000363 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000364 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000365 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000366 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000367
368 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
369 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
370 if (MD->isStatic())
371 // "invalid use of member 'x' in static member function"
372 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
373 FD->getName());
374 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
375 // "invalid use of nonstatic data member 'x'"
376 return Diag(Loc, diag::err_invalid_non_static_member_use,
377 FD->getName());
378
379 if (FD->isInvalidDecl())
380 return true;
381
382 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
383 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
384 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
385 true, FD, Loc, FD->getType());
386 }
387
388 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
389 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000390
Chris Lattner4b009652007-07-25 00:24:17 +0000391 if (isa<TypedefDecl>(D))
392 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000393 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000394 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000395 if (isa<NamespaceDecl>(D))
396 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000397
398 assert(0 && "Invalid decl");
399 abort();
400}
401
Chris Lattner69909292008-08-10 01:53:14 +0000402Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000403 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000404 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000405
406 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000407 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000408 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
409 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
410 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000411 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000412
413 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000414 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000415 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000416
Chris Lattner7e637512008-01-12 08:14:25 +0000417 // Pre-defined identifiers are of type char[x], where x is the length of the
418 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000419 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000420 if (getCurFunctionDecl())
421 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000422 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000423 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000424
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000425 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000426 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000427 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000428 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000429}
430
Steve Naroff87d58b42007-09-16 03:34:24 +0000431Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000432 llvm::SmallString<16> CharBuffer;
433 CharBuffer.resize(Tok.getLength());
434 const char *ThisTokBegin = &CharBuffer[0];
435 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
436
437 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
438 Tok.getLocation(), PP);
439 if (Literal.hadError())
440 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000441
442 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
443
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000444 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
445 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000446}
447
Steve Naroff87d58b42007-09-16 03:34:24 +0000448Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000449 // fast path for a single digit (which is quite common). A single digit
450 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
451 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000452 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000453
Chris Lattner8cd0e932008-03-05 18:54:05 +0000454 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000455 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000456 Context.IntTy,
457 Tok.getLocation()));
458 }
459 llvm::SmallString<512> IntegerBuffer;
460 IntegerBuffer.resize(Tok.getLength());
461 const char *ThisTokBegin = &IntegerBuffer[0];
462
463 // Get the spelling of the token, which eliminates trigraphs, etc.
464 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
465 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
466 Tok.getLocation(), PP);
467 if (Literal.hadError)
468 return ExprResult(true);
469
Chris Lattner1de66eb2007-08-26 03:42:43 +0000470 Expr *Res;
471
472 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000473 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000474 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000475 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000476 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000477 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000478 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000479 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000480
481 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
482
Ted Kremenekddedbe22007-11-29 00:56:49 +0000483 // isExact will be set by GetFloatValue().
484 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000485 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000486 Ty, Tok.getLocation());
487
Chris Lattner1de66eb2007-08-26 03:42:43 +0000488 } else if (!Literal.isIntegerLiteral()) {
489 return ExprResult(true);
490 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000491 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000492
Neil Booth7421e9c2007-08-29 22:00:19 +0000493 // long long is a C99 feature.
494 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000495 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000496 Diag(Tok.getLocation(), diag::ext_longlong);
497
Chris Lattner4b009652007-07-25 00:24:17 +0000498 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000499 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000500
501 if (Literal.GetIntegerValue(ResultVal)) {
502 // If this value didn't fit into uintmax_t, warn and force to ull.
503 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000504 Ty = Context.UnsignedLongLongTy;
505 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000506 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000507 } else {
508 // If this value fits into a ULL, try to figure out what else it fits into
509 // according to the rules of C99 6.4.4.1p5.
510
511 // Octal, Hexadecimal, and integers with a U suffix are allowed to
512 // be an unsigned int.
513 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
514
515 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000516 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000517 if (!Literal.isLong && !Literal.isLongLong) {
518 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000519 unsigned IntSize = Context.Target.getIntWidth();
520
Chris Lattner4b009652007-07-25 00:24:17 +0000521 // Does it fit in a unsigned int?
522 if (ResultVal.isIntN(IntSize)) {
523 // Does it fit in a signed int?
524 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000525 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000526 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000527 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000528 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000529 }
Chris Lattner4b009652007-07-25 00:24:17 +0000530 }
531
532 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000533 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000534 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000535
536 // Does it fit in a unsigned long?
537 if (ResultVal.isIntN(LongSize)) {
538 // Does it fit in a signed long?
539 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000540 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000541 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000542 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000543 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000544 }
Chris Lattner4b009652007-07-25 00:24:17 +0000545 }
546
547 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000548 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000549 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000550
551 // Does it fit in a unsigned long long?
552 if (ResultVal.isIntN(LongLongSize)) {
553 // Does it fit in a signed long long?
554 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000555 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000556 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000557 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000558 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000559 }
560 }
561
562 // If we still couldn't decide a type, we probably have something that
563 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000564 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000565 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000566 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000567 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000568 }
Chris Lattnere4068872008-05-09 05:59:00 +0000569
570 if (ResultVal.getBitWidth() != Width)
571 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000572 }
573
Chris Lattner48d7f382008-04-02 04:24:33 +0000574 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000575 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000576
577 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
578 if (Literal.isImaginary)
579 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
580
581 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000582}
583
Steve Naroff87d58b42007-09-16 03:34:24 +0000584Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000585 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000586 Expr *E = (Expr *)Val;
587 assert((E != 0) && "ActOnParenExpr() missing expr");
588 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000589}
590
591/// The UsualUnaryConversions() function is *not* called by this routine.
592/// See C99 6.3.2.1p[2-4] for more details.
593QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000594 SourceLocation OpLoc,
595 const SourceRange &ExprRange,
596 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000597 // C99 6.5.3.4p1:
598 if (isa<FunctionType>(exprType) && isSizeof)
599 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000600 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000601 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000602 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
603 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000604 else if (exprType->isIncompleteType()) {
605 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
606 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000607 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000608 return QualType(); // error
609 }
610 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
611 return Context.getSizeType();
612}
613
614Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000615ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000616 SourceLocation LPLoc, TypeTy *Ty,
617 SourceLocation RPLoc) {
618 // If error parsing type, ignore.
619 if (Ty == 0) return true;
620
621 // Verify that this is a valid expression.
622 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
623
Chris Lattnerf814d882008-07-25 21:45:37 +0000624 QualType resultType =
625 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000626
627 if (resultType.isNull())
628 return true;
629 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
630}
631
Chris Lattner5110ad52007-08-24 21:41:10 +0000632QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000633 DefaultFunctionArrayConversion(V);
634
Chris Lattnera16e42d2007-08-26 05:39:26 +0000635 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000636 if (const ComplexType *CT = V->getType()->getAsComplexType())
637 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000638
639 // Otherwise they pass through real integer and floating point types here.
640 if (V->getType()->isArithmeticType())
641 return V->getType();
642
643 // Reject anything else.
644 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
645 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000646}
647
648
Chris Lattner4b009652007-07-25 00:24:17 +0000649
Steve Naroff87d58b42007-09-16 03:34:24 +0000650Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000651 tok::TokenKind Kind,
652 ExprTy *Input) {
653 UnaryOperator::Opcode Opc;
654 switch (Kind) {
655 default: assert(0 && "Unknown unary op!");
656 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
657 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
658 }
659 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
660 if (result.isNull())
661 return true;
662 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
663}
664
665Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000666ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000667 ExprTy *Idx, SourceLocation RLoc) {
668 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
669
670 // Perform default conversions.
671 DefaultFunctionArrayConversion(LHSExp);
672 DefaultFunctionArrayConversion(RHSExp);
673
674 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
675
676 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000677 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000678 // in the subscript position. As a result, we need to derive the array base
679 // and index from the expression types.
680 Expr *BaseExpr, *IndexExpr;
681 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000682 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000683 BaseExpr = LHSExp;
684 IndexExpr = RHSExp;
685 // FIXME: need to deal with const...
686 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000687 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000688 // Handle the uncommon case of "123[Ptr]".
689 BaseExpr = RHSExp;
690 IndexExpr = LHSExp;
691 // FIXME: need to deal with const...
692 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000693 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
694 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000695 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000696
697 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000698 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
699 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000700 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000701 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000702 // FIXME: need to deal with const...
703 ResultType = VTy->getElementType();
704 } else {
705 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
706 RHSExp->getSourceRange());
707 }
708 // C99 6.5.2.1p1
709 if (!IndexExpr->getType()->isIntegerType())
710 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
711 IndexExpr->getSourceRange());
712
713 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
714 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000715 // void (*)(int)) and pointers to incomplete types. Functions are not
716 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000717 if (!ResultType->isObjectType())
718 return Diag(BaseExpr->getLocStart(),
719 diag::err_typecheck_subscript_not_object,
720 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
721
722 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
723}
724
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000725QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000726CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000727 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000728 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000729
730 // This flag determines whether or not the component is to be treated as a
731 // special name, or a regular GLSL-style component access.
732 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000733
734 // The vector accessor can't exceed the number of elements.
735 const char *compStr = CompName.getName();
736 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000737 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000738 baseType.getAsString(), SourceRange(CompLoc));
739 return QualType();
740 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000741
742 // Check that we've found one of the special components, or that the component
743 // names must come from the same set.
744 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
745 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
746 SpecialComponent = true;
747 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000748 do
749 compStr++;
750 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
751 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
752 do
753 compStr++;
754 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
755 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
756 do
757 compStr++;
758 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
759 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000760
Nate Begemanc8e51f82008-05-09 06:41:27 +0000761 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000762 // We didn't get to the end of the string. This means the component names
763 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000764 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000765 std::string(compStr,compStr+1), SourceRange(CompLoc));
766 return QualType();
767 }
768 // Each component accessor can't exceed the vector type.
769 compStr = CompName.getName();
770 while (*compStr) {
771 if (vecType->isAccessorWithinNumElements(*compStr))
772 compStr++;
773 else
774 break;
775 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000776 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000777 // We didn't get to the end of the string. This means a component accessor
778 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000779 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000780 baseType.getAsString(), SourceRange(CompLoc));
781 return QualType();
782 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000783
784 // If we have a special component name, verify that the current vector length
785 // is an even number, since all special component names return exactly half
786 // the elements.
787 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
788 return QualType();
789 }
790
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000791 // The component accessor looks fine - now we need to compute the actual type.
792 // The vector type is implied by the component accessor. For example,
793 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000794 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
795 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
796 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000797 if (CompSize == 1)
798 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000799
Nate Begemanaf6ed502008-04-18 23:10:10 +0000800 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000801 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000802 // diagostics look bad. We want extended vector types to appear built-in.
803 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
804 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
805 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000806 }
807 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000808}
809
Chris Lattner4b009652007-07-25 00:24:17 +0000810Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000811ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000812 tok::TokenKind OpKind, SourceLocation MemberLoc,
813 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000814 Expr *BaseExpr = static_cast<Expr *>(Base);
815 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000816
817 // Perform default conversions.
818 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000819
Steve Naroff2cb66382007-07-26 03:11:44 +0000820 QualType BaseType = BaseExpr->getType();
821 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000822
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000823 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
824 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000825 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000826 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000827 BaseType = PT->getPointeeType();
828 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000829 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
830 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000831 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000832
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000833 // Handle field access to simple records. This also handles access to fields
834 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000835 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000836 RecordDecl *RDecl = RTy->getDecl();
837 if (RTy->isIncompleteType())
838 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
839 BaseExpr->getSourceRange());
840 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000841 FieldDecl *MemberDecl = RDecl->getMember(&Member);
842 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000843 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
844 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000845
846 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000847 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000848 QualType MemberType = MemberDecl->getType();
849 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000850 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000851 MemberType = MemberType.getQualifiedType(combinedQualifiers);
852
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000853 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000854 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000855 }
856
Chris Lattnere9d71612008-07-21 04:59:05 +0000857 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
858 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000859 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
860 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000861 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000862 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000863 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000864 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000865 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000866 }
867
Chris Lattnere9d71612008-07-21 04:59:05 +0000868 // Handle Objective-C property access, which is "Obj.property" where Obj is a
869 // pointer to a (potentially qualified) interface type.
870 const PointerType *PTy;
871 const ObjCInterfaceType *IFTy;
872 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
873 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
874 ObjCInterfaceDecl *IFace = IFTy->getDecl();
875
Chris Lattner55a24332008-07-21 06:44:27 +0000876 // FIXME: The logic for looking up nullary and unary selectors should be
877 // shared with the code in ActOnInstanceMessage.
878
Chris Lattnere9d71612008-07-21 04:59:05 +0000879 // Before we look for explicit property declarations, we check for
880 // nullary methods (which allow '.' notation).
881 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Chris Lattnere9d71612008-07-21 04:59:05 +0000882 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel))
883 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
884 MemberLoc, BaseExpr);
885
Chris Lattner55a24332008-07-21 06:44:27 +0000886 // If this reference is in an @implementation, check for 'private' methods.
887 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
888 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
889 if (ObjCImplementationDecl *ImpDecl =
890 ObjCImplementations[ClassDecl->getIdentifier()])
891 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel))
892 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
893 MemberLoc, BaseExpr);
894 }
895
Chris Lattnere9d71612008-07-21 04:59:05 +0000896 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
897 // @interface NSBundle : NSObject {}
898 // - (NSString *)bundlePath;
899 // - (void)setBundlePath:(NSString *)x;
900 // @end
901 // void someMethod() { frameworkBundle.bundlePath = 0; }
902 //
903 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
904 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
905
906 // Lastly, check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000907 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
908 E = IFTy->qual_end(); I != E; ++I)
909 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
910 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000911 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000912
913 // Handle 'field access' to vectors, such as 'V.xx'.
914 if (BaseType->isExtVectorType() && OpKind == tok::period) {
915 // Component access limited to variables (reject vec4.rg.g).
916 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
917 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000918 return Diag(MemberLoc, diag::err_ext_vector_component_access,
919 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000920 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
921 if (ret.isNull())
922 return true;
923 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
924 }
925
Chris Lattner7d5a8762008-07-21 05:35:34 +0000926 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
927 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000928}
929
Steve Naroff87d58b42007-09-16 03:34:24 +0000930/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000931/// This provides the location of the left/right parens and a list of comma
932/// locations.
933Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000934ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000935 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000936 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
937 Expr *Fn = static_cast<Expr *>(fn);
938 Expr **Args = reinterpret_cast<Expr**>(args);
939 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000940 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000941
942 // Promote the function operand.
943 UsualUnaryConversions(Fn);
944
945 // If we're directly calling a function, get the declaration for
946 // that function.
947 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
948 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
949 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
950
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000951 // Make the call expr early, before semantic checks. This guarantees cleanup
952 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000953 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000954 Context.BoolTy, RParenLoc));
955
Chris Lattner4b009652007-07-25 00:24:17 +0000956 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
957 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000958 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000959 if (PT == 0)
960 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
961 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000962 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
963 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000964 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
965 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000966
967 // We know the result type of the call, set it.
968 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000969
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000970 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000971 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
972 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000973 unsigned NumArgsInProto = Proto->getNumArgs();
974 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000975
Chris Lattner3e254fb2008-04-08 04:40:51 +0000976 // If too few arguments are available (and we don't have default
977 // arguments for the remaining parameters), don't make the call.
978 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000979 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000980 // Use default arguments for missing arguments
981 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000982 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000983 } else
984 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
985 Fn->getSourceRange());
986 }
987
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000988 // If too many are passed and not variadic, error on the extras and drop
989 // them.
990 if (NumArgs > NumArgsInProto) {
991 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000992 Diag(Args[NumArgsInProto]->getLocStart(),
993 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
994 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000995 Args[NumArgs-1]->getLocEnd()));
996 // This deletes the extra arguments.
997 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000998 }
999 NumArgsToCheck = NumArgsInProto;
1000 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001001
Chris Lattner4b009652007-07-25 00:24:17 +00001002 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001003 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001004 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001005
1006 Expr *Arg;
1007 if (i < NumArgs)
1008 Arg = Args[i];
1009 else
1010 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001011 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001012
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001013 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001014 AssignConvertType ConvTy =
1015 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001016 TheCall->setArg(i, Arg);
1017
Chris Lattner005ed752008-01-04 18:04:52 +00001018 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1019 ArgType, Arg, "passing"))
1020 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001021 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001022
1023 // If this is a variadic call, handle args passed through "...".
1024 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001025 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001026 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1027 Expr *Arg = Args[i];
1028 DefaultArgumentPromotion(Arg);
1029 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001030 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001031 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001032 } else {
1033 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1034
Steve Naroffdb65e052007-08-28 23:30:39 +00001035 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001036 for (unsigned i = 0; i != NumArgs; i++) {
1037 Expr *Arg = Args[i];
1038 DefaultArgumentPromotion(Arg);
1039 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001040 }
Chris Lattner4b009652007-07-25 00:24:17 +00001041 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001042
Chris Lattner2e64c072007-08-10 20:18:51 +00001043 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001044 if (FDecl)
1045 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001046
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001047 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001048}
1049
1050Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001051ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001052 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001053 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001054 QualType literalType = QualType::getFromOpaquePtr(Ty);
1055 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001056 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001057 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001058
Eli Friedman8c2173d2008-05-20 05:22:08 +00001059 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001060 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001061 return Diag(LParenLoc,
1062 diag::err_variable_object_no_init,
1063 SourceRange(LParenLoc,
1064 literalExpr->getSourceRange().getEnd()));
1065 } else if (literalType->isIncompleteType()) {
1066 return Diag(LParenLoc,
1067 diag::err_typecheck_decl_incomplete_type,
1068 literalType.getAsString(),
1069 SourceRange(LParenLoc,
1070 literalExpr->getSourceRange().getEnd()));
1071 }
1072
Steve Narofff0b23542008-01-10 22:15:12 +00001073 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001074 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001075
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001076 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001077 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001078 if (CheckForConstantInitializer(literalExpr, literalType))
1079 return true;
1080 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001081 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001082}
1083
1084Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001085ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001086 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001087 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001088
Steve Naroff0acc9c92007-09-15 18:49:24 +00001089 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001090 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001091
Chris Lattner48d7f382008-04-02 04:24:33 +00001092 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1093 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1094 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001095}
1096
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001097bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001098 assert(VectorTy->isVectorType() && "Not a vector type!");
1099
1100 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001101 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001102 return Diag(R.getBegin(),
1103 Ty->isVectorType() ?
1104 diag::err_invalid_conversion_between_vectors :
1105 diag::err_invalid_conversion_between_vector_and_integer,
1106 VectorTy.getAsString().c_str(),
1107 Ty.getAsString().c_str(), R);
1108 } else
1109 return Diag(R.getBegin(),
1110 diag::err_invalid_conversion_between_vector_and_scalar,
1111 VectorTy.getAsString().c_str(),
1112 Ty.getAsString().c_str(), R);
1113
1114 return false;
1115}
1116
Chris Lattner4b009652007-07-25 00:24:17 +00001117Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001118ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001119 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001120 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001121
1122 Expr *castExpr = static_cast<Expr*>(Op);
1123 QualType castType = QualType::getFromOpaquePtr(Ty);
1124
Steve Naroff68adb482007-08-31 00:32:44 +00001125 UsualUnaryConversions(castExpr);
1126
Chris Lattner4b009652007-07-25 00:24:17 +00001127 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1128 // type needs to be scalar.
Chris Lattner08b3c472008-07-25 22:06:10 +00001129 if (castType->isVoidType()) {
1130 // Cast to void allows any expr type.
1131 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1132 // GCC struct/union extension: allow cast to self.
1133 if (Context.getCanonicalType(castType) !=
1134 Context.getCanonicalType(castExpr->getType()) ||
1135 (!castType->isStructureType() && !castType->isUnionType())) {
1136 // Reject any other conversions to non-scalar types.
1137 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
1138 castType.getAsString(), castExpr->getSourceRange());
Steve Naroff5ad85292008-06-03 12:56:35 +00001139 }
Chris Lattner08b3c472008-07-25 22:06:10 +00001140
1141 // accept this, but emit an ext-warn.
1142 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
1143 castType.getAsString(), castExpr->getSourceRange());
1144 } else if (!castExpr->getType()->isScalarType() &&
1145 !castExpr->getType()->isVectorType()) {
1146 return Diag(castExpr->getLocStart(),
1147 diag::err_typecheck_expect_scalar_operand,
1148 castExpr->getType().getAsString(),castExpr->getSourceRange());
1149 } else if (castExpr->getType()->isVectorType()) {
1150 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1151 castExpr->getType(), castType))
1152 return true;
1153 } else if (castType->isVectorType()) {
1154 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1155 castType, castExpr->getType()))
1156 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001157 }
1158 return new CastExpr(castType, castExpr, LParenLoc);
1159}
1160
Chris Lattner98a425c2007-11-26 01:40:58 +00001161/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1162/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001163inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1164 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1165 UsualUnaryConversions(cond);
1166 UsualUnaryConversions(lex);
1167 UsualUnaryConversions(rex);
1168 QualType condT = cond->getType();
1169 QualType lexT = lex->getType();
1170 QualType rexT = rex->getType();
1171
1172 // first, check the condition.
1173 if (!condT->isScalarType()) { // C99 6.5.15p2
1174 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1175 condT.getAsString());
1176 return QualType();
1177 }
Chris Lattner992ae932008-01-06 22:42:25 +00001178
1179 // Now check the two expressions.
1180
1181 // If both operands have arithmetic type, do the usual arithmetic conversions
1182 // to find a common type: C99 6.5.15p3,5.
1183 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001184 UsualArithmeticConversions(lex, rex);
1185 return lex->getType();
1186 }
Chris Lattner992ae932008-01-06 22:42:25 +00001187
1188 // If both operands are the same structure or union type, the result is that
1189 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001190 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001191 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001192 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001193 // "If both the operands have structure or union type, the result has
1194 // that type." This implies that CV qualifiers are dropped.
1195 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001196 }
Chris Lattner992ae932008-01-06 22:42:25 +00001197
1198 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001199 // The following || allows only one side to be void (a GCC-ism).
1200 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001201 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001202 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1203 rex->getSourceRange());
1204 if (!rexT->isVoidType())
1205 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001206 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001207 ImpCastExprToType(lex, Context.VoidTy);
1208 ImpCastExprToType(rex, Context.VoidTy);
1209 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001210 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001211 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1212 // the type of the other operand."
1213 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001214 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001215 return lexT;
1216 }
1217 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001218 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001219 return rexT;
1220 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001221 // Handle the case where both operands are pointers before we handle null
1222 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001223 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1224 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1225 // get the "pointed to" types
1226 QualType lhptee = LHSPT->getPointeeType();
1227 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001228
Chris Lattner71225142007-07-31 21:27:01 +00001229 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1230 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001231 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001232 // Figure out necessary qualifiers (C99 6.5.15p6)
1233 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001234 QualType destType = Context.getPointerType(destPointee);
1235 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1236 ImpCastExprToType(rex, destType); // promote to void*
1237 return destType;
1238 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001239 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001240 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001241 QualType destType = Context.getPointerType(destPointee);
1242 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1243 ImpCastExprToType(rex, destType); // promote to void*
1244 return destType;
1245 }
Chris Lattner4b009652007-07-25 00:24:17 +00001246
Steve Naroff85f0dc52007-10-15 20:41:53 +00001247 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1248 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001249 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001250 lexT.getAsString(), rexT.getAsString(),
1251 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +00001252 // In this situation, we assume void* type. No especially good
1253 // reason, but this is what gcc does, and we do have to pick
1254 // to get a consistent AST.
1255 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1256 ImpCastExprToType(lex, voidPtrTy);
1257 ImpCastExprToType(rex, voidPtrTy);
1258 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +00001259 }
1260 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001261 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1262 // differently qualified versions of compatible types, the result type is
1263 // a pointer to an appropriately qualified version of the *composite*
1264 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001265 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001266 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001267 QualType compositeType = lexT;
1268 ImpCastExprToType(lex, compositeType);
1269 ImpCastExprToType(rex, compositeType);
1270 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001271 }
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Steve Naroff605896f2008-05-31 22:33:45 +00001273 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1274 // evaluates to "struct objc_object *" (and is handled above when comparing
1275 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1276 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1277 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1278 return Context.getObjCIdType();
1279 }
Chris Lattner992ae932008-01-06 22:42:25 +00001280 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001281 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1282 lexT.getAsString(), rexT.getAsString(),
1283 lex->getSourceRange(), rex->getSourceRange());
1284 return QualType();
1285}
1286
Steve Naroff87d58b42007-09-16 03:34:24 +00001287/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001288/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001289Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001290 SourceLocation ColonLoc,
1291 ExprTy *Cond, ExprTy *LHS,
1292 ExprTy *RHS) {
1293 Expr *CondExpr = (Expr *) Cond;
1294 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001295
1296 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1297 // was the condition.
1298 bool isLHSNull = LHSExpr == 0;
1299 if (isLHSNull)
1300 LHSExpr = CondExpr;
1301
Chris Lattner4b009652007-07-25 00:24:17 +00001302 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1303 RHSExpr, QuestionLoc);
1304 if (result.isNull())
1305 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001306 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1307 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001308}
1309
Chris Lattner4b009652007-07-25 00:24:17 +00001310
1311// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1312// being closely modeled after the C99 spec:-). The odd characteristic of this
1313// routine is it effectively iqnores the qualifiers on the top level pointee.
1314// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1315// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001316Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001317Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1318 QualType lhptee, rhptee;
1319
1320 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001321 lhptee = lhsType->getAsPointerType()->getPointeeType();
1322 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001323
1324 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001325 lhptee = Context.getCanonicalType(lhptee);
1326 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001327
Chris Lattner005ed752008-01-04 18:04:52 +00001328 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001329
1330 // C99 6.5.16.1p1: This following citation is common to constraints
1331 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1332 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001333 // FIXME: Handle ASQualType
1334 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1335 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001336 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001337
1338 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1339 // incomplete type and the other is a pointer to a qualified or unqualified
1340 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001341 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001342 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001343 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001344
1345 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001346 assert(rhptee->isFunctionType());
1347 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001348 }
1349
1350 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001351 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001352 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001353
1354 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001355 assert(lhptee->isFunctionType());
1356 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001357 }
1358
Chris Lattner4b009652007-07-25 00:24:17 +00001359 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1360 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001361 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1362 rhptee.getUnqualifiedType()))
1363 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001364 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001365}
1366
1367/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1368/// has code to accommodate several GCC extensions when type checking
1369/// pointers. Here are some objectionable examples that GCC considers warnings:
1370///
1371/// int a, *pint;
1372/// short *pshort;
1373/// struct foo *pfoo;
1374///
1375/// pint = pshort; // warning: assignment from incompatible pointer type
1376/// a = pint; // warning: assignment makes integer from pointer without a cast
1377/// pint = a; // warning: assignment makes pointer from integer without a cast
1378/// pint = pfoo; // warning: assignment from incompatible pointer type
1379///
1380/// As a result, the code for dealing with pointers is more complex than the
1381/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001382///
Chris Lattner005ed752008-01-04 18:04:52 +00001383Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001384Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001385 // Get canonical types. We're not formatting these types, just comparing
1386 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001387 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1388 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001389
1390 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001391 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001392
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001393 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001394 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001395 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001396 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001397 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001398
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001399 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1400 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001401 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001402 // Relax integer conversions like we do for pointers below.
1403 if (rhsType->isIntegerType())
1404 return IntToPointer;
1405 if (lhsType->isIntegerType())
1406 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001407 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001408 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001409
Nate Begemanc5f0f652008-07-14 18:02:46 +00001410 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001411 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001412 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1413 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001414 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001415
Nate Begemanc5f0f652008-07-14 18:02:46 +00001416 // If we are allowing lax vector conversions, and LHS and RHS are both
1417 // vectors, the total size only needs to be the same. This is a bitcast;
1418 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001419 if (getLangOptions().LaxVectorConversions &&
1420 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001421 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1422 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001423 }
1424 return Incompatible;
1425 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001426
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001427 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001428 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001429
Chris Lattner390564e2008-04-07 06:49:41 +00001430 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001431 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001432 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001433
Chris Lattner390564e2008-04-07 06:49:41 +00001434 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001435 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001436 return Incompatible;
1437 }
1438
Chris Lattner390564e2008-04-07 06:49:41 +00001439 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001441 if (lhsType == Context.BoolTy)
1442 return Compatible;
1443
1444 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001445 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001446
Chris Lattner390564e2008-04-07 06:49:41 +00001447 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001448 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001449 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001450 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001451
Chris Lattner1853da22008-01-04 23:18:45 +00001452 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001453 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001454 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001455 }
1456 return Incompatible;
1457}
1458
Chris Lattner005ed752008-01-04 18:04:52 +00001459Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001460Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001461 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1462 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001463 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001464 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001465 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001466 return Compatible;
1467 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001468 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001469 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001470 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001471 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001472 //
1473 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1474 // are better understood.
1475 if (!lhsType->isReferenceType())
1476 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001477
Chris Lattner005ed752008-01-04 18:04:52 +00001478 Sema::AssignConvertType result =
1479 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001480
1481 // C99 6.5.16.1p2: The value of the right operand is converted to the
1482 // type of the assignment expression.
1483 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001484 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001485 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001486}
1487
Chris Lattner005ed752008-01-04 18:04:52 +00001488Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001489Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1490 return CheckAssignmentConstraints(lhsType, rhsType);
1491}
1492
Chris Lattner2c8bff72007-12-12 05:47:28 +00001493QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001494 Diag(loc, diag::err_typecheck_invalid_operands,
1495 lex->getType().getAsString(), rex->getType().getAsString(),
1496 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001497 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001498}
1499
1500inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1501 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001502 // For conversion purposes, we ignore any qualifiers.
1503 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001504 QualType lhsType =
1505 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1506 QualType rhsType =
1507 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001508
Nate Begemanc5f0f652008-07-14 18:02:46 +00001509 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001510 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001511 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001512
Nate Begemanc5f0f652008-07-14 18:02:46 +00001513 // Handle the case of a vector & extvector type of the same size and element
1514 // type. It would be nice if we only had one vector type someday.
1515 if (getLangOptions().LaxVectorConversions)
1516 if (const VectorType *LV = lhsType->getAsVectorType())
1517 if (const VectorType *RV = rhsType->getAsVectorType())
1518 if (LV->getElementType() == RV->getElementType() &&
1519 LV->getNumElements() == RV->getNumElements())
1520 return lhsType->isExtVectorType() ? lhsType : rhsType;
1521
1522 // If the lhs is an extended vector and the rhs is a scalar of the same type
1523 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001524 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001525 QualType eltType = V->getElementType();
1526
1527 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1528 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1529 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001530 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001531 return lhsType;
1532 }
1533 }
1534
Nate Begemanc5f0f652008-07-14 18:02:46 +00001535 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001536 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001537 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001538 QualType eltType = V->getElementType();
1539
1540 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1541 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1542 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001543 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001544 return rhsType;
1545 }
1546 }
1547
Chris Lattner4b009652007-07-25 00:24:17 +00001548 // You cannot convert between vector values of different size.
1549 Diag(loc, diag::err_typecheck_vector_not_convertable,
1550 lex->getType().getAsString(), rex->getType().getAsString(),
1551 lex->getSourceRange(), rex->getSourceRange());
1552 return QualType();
1553}
1554
1555inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001556 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001557{
1558 QualType lhsType = lex->getType(), rhsType = rex->getType();
1559
1560 if (lhsType->isVectorType() || rhsType->isVectorType())
1561 return CheckVectorOperands(loc, lex, rex);
1562
Steve Naroff8f708362007-08-24 19:07:16 +00001563 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001564
Chris Lattner4b009652007-07-25 00:24:17 +00001565 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001566 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001567 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001568}
1569
1570inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001571 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001572{
1573 QualType lhsType = lex->getType(), rhsType = rex->getType();
1574
Steve Naroff8f708362007-08-24 19:07:16 +00001575 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001576
Chris Lattner4b009652007-07-25 00:24:17 +00001577 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001578 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001579 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001580}
1581
1582inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001583 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001584{
1585 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1586 return CheckVectorOperands(loc, lex, rex);
1587
Steve Naroff8f708362007-08-24 19:07:16 +00001588 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001589
Chris Lattner4b009652007-07-25 00:24:17 +00001590 // handle the common case first (both operands are arithmetic).
1591 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001592 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001593
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001594 // Put any potential pointer into PExp
1595 Expr* PExp = lex, *IExp = rex;
1596 if (IExp->getType()->isPointerType())
1597 std::swap(PExp, IExp);
1598
1599 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1600 if (IExp->getType()->isIntegerType()) {
1601 // Check for arithmetic on pointers to incomplete types
1602 if (!PTy->getPointeeType()->isObjectType()) {
1603 if (PTy->getPointeeType()->isVoidType()) {
1604 Diag(loc, diag::ext_gnu_void_ptr,
1605 lex->getSourceRange(), rex->getSourceRange());
1606 } else {
1607 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1608 lex->getType().getAsString(), lex->getSourceRange());
1609 return QualType();
1610 }
1611 }
1612 return PExp->getType();
1613 }
1614 }
1615
Chris Lattner2c8bff72007-12-12 05:47:28 +00001616 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001617}
1618
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001619// C99 6.5.6
1620QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1621 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001622 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1623 return CheckVectorOperands(loc, lex, rex);
1624
Steve Naroff8f708362007-08-24 19:07:16 +00001625 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001626
Chris Lattnerf6da2912007-12-09 21:53:25 +00001627 // Enforce type constraints: C99 6.5.6p3.
1628
1629 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001630 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001631 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001632
1633 // Either ptr - int or ptr - ptr.
1634 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001635 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001636
Chris Lattnerf6da2912007-12-09 21:53:25 +00001637 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001638 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001639 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001640 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001641 Diag(loc, diag::ext_gnu_void_ptr,
1642 lex->getSourceRange(), rex->getSourceRange());
1643 } else {
1644 Diag(loc, diag::err_typecheck_sub_ptr_object,
1645 lex->getType().getAsString(), lex->getSourceRange());
1646 return QualType();
1647 }
1648 }
1649
1650 // The result type of a pointer-int computation is the pointer type.
1651 if (rex->getType()->isIntegerType())
1652 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001653
Chris Lattnerf6da2912007-12-09 21:53:25 +00001654 // Handle pointer-pointer subtractions.
1655 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001656 QualType rpointee = RHSPTy->getPointeeType();
1657
Chris Lattnerf6da2912007-12-09 21:53:25 +00001658 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001659 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001660 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001661 if (rpointee->isVoidType()) {
1662 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001663 Diag(loc, diag::ext_gnu_void_ptr,
1664 lex->getSourceRange(), rex->getSourceRange());
1665 } else {
1666 Diag(loc, diag::err_typecheck_sub_ptr_object,
1667 rex->getType().getAsString(), rex->getSourceRange());
1668 return QualType();
1669 }
1670 }
1671
1672 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001673 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1674 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001675 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1676 lex->getType().getAsString(), rex->getType().getAsString(),
1677 lex->getSourceRange(), rex->getSourceRange());
1678 return QualType();
1679 }
1680
1681 return Context.getPointerDiffType();
1682 }
1683 }
1684
Chris Lattner2c8bff72007-12-12 05:47:28 +00001685 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001686}
1687
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001688// C99 6.5.7
1689QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1690 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001691 // C99 6.5.7p2: Each of the operands shall have integer type.
1692 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1693 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001694
Chris Lattner2c8bff72007-12-12 05:47:28 +00001695 // Shifts don't perform usual arithmetic conversions, they just do integer
1696 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001697 if (!isCompAssign)
1698 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001699 UsualUnaryConversions(rex);
1700
1701 // "The type of the result is that of the promoted left operand."
1702 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001703}
1704
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001705// C99 6.5.8
1706QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1707 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001708 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1709 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1710
Chris Lattner254f3bc2007-08-26 01:18:55 +00001711 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001712 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1713 UsualArithmeticConversions(lex, rex);
1714 else {
1715 UsualUnaryConversions(lex);
1716 UsualUnaryConversions(rex);
1717 }
Chris Lattner4b009652007-07-25 00:24:17 +00001718 QualType lType = lex->getType();
1719 QualType rType = rex->getType();
1720
Ted Kremenek486509e2007-10-29 17:13:39 +00001721 // For non-floating point types, check for self-comparisons of the form
1722 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1723 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001724 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001725 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1726 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001727 if (DRL->getDecl() == DRR->getDecl())
1728 Diag(loc, diag::warn_selfcomparison);
1729 }
1730
Chris Lattner254f3bc2007-08-26 01:18:55 +00001731 if (isRelational) {
1732 if (lType->isRealType() && rType->isRealType())
1733 return Context.IntTy;
1734 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001735 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001736 if (lType->isFloatingType()) {
1737 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001738 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001739 }
1740
Chris Lattner254f3bc2007-08-26 01:18:55 +00001741 if (lType->isArithmeticType() && rType->isArithmeticType())
1742 return Context.IntTy;
1743 }
Chris Lattner4b009652007-07-25 00:24:17 +00001744
Chris Lattner22be8422007-08-26 01:10:14 +00001745 bool LHSIsNull = lex->isNullPointerConstant(Context);
1746 bool RHSIsNull = rex->isNullPointerConstant(Context);
1747
Chris Lattner254f3bc2007-08-26 01:18:55 +00001748 // All of the following pointer related warnings are GCC extensions, except
1749 // when handling null pointer constants. One day, we can consider making them
1750 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001751 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001752 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001753 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001754 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001755 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00001756
Steve Naroff3b435622007-11-13 14:57:38 +00001757 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001758 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1759 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1760 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001761 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1762 lType.getAsString(), rType.getAsString(),
1763 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001764 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001765 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001766 return Context.IntTy;
1767 }
Steve Naroff936c4362008-06-03 14:04:54 +00001768 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1769 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1770 ImpCastExprToType(rex, lType);
1771 return Context.IntTy;
1772 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001773 }
Steve Naroff936c4362008-06-03 14:04:54 +00001774 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1775 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001776 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001777 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1778 lType.getAsString(), rType.getAsString(),
1779 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001780 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001781 return Context.IntTy;
1782 }
Steve Naroff936c4362008-06-03 14:04:54 +00001783 if (lType->isIntegerType() &&
1784 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001785 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001786 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1787 lType.getAsString(), rType.getAsString(),
1788 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001789 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001790 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001791 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001792 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001793}
1794
Nate Begemanc5f0f652008-07-14 18:02:46 +00001795/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1796/// operates on extended vector types. Instead of producing an IntTy result,
1797/// like a scalar comparison, a vector comparison produces a vector of integer
1798/// types.
1799QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1800 SourceLocation loc,
1801 bool isRelational) {
1802 // Check to make sure we're operating on vectors of the same type and width,
1803 // Allowing one side to be a scalar of element type.
1804 QualType vType = CheckVectorOperands(loc, lex, rex);
1805 if (vType.isNull())
1806 return vType;
1807
1808 QualType lType = lex->getType();
1809 QualType rType = rex->getType();
1810
1811 // For non-floating point types, check for self-comparisons of the form
1812 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1813 // often indicate logic errors in the program.
1814 if (!lType->isFloatingType()) {
1815 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1816 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1817 if (DRL->getDecl() == DRR->getDecl())
1818 Diag(loc, diag::warn_selfcomparison);
1819 }
1820
1821 // Check for comparisons of floating point operands using != and ==.
1822 if (!isRelational && lType->isFloatingType()) {
1823 assert (rType->isFloatingType());
1824 CheckFloatComparison(loc,lex,rex);
1825 }
1826
1827 // Return the type for the comparison, which is the same as vector type for
1828 // integer vectors, or an integer type of identical size and number of
1829 // elements for floating point vectors.
1830 if (lType->isIntegerType())
1831 return lType;
1832
1833 const VectorType *VTy = lType->getAsVectorType();
1834
1835 // FIXME: need to deal with non-32b int / non-64b long long
1836 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1837 if (TypeSize == 32) {
1838 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1839 }
1840 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1841 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1842}
1843
Chris Lattner4b009652007-07-25 00:24:17 +00001844inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001845 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001846{
1847 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1848 return CheckVectorOperands(loc, lex, rex);
1849
Steve Naroff8f708362007-08-24 19:07:16 +00001850 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001851
1852 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001853 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001854 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001855}
1856
1857inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1858 Expr *&lex, Expr *&rex, SourceLocation loc)
1859{
1860 UsualUnaryConversions(lex);
1861 UsualUnaryConversions(rex);
1862
Eli Friedmanbea3f842008-05-13 20:16:47 +00001863 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001864 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001865 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001866}
1867
1868inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001869 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001870{
1871 QualType lhsType = lex->getType();
1872 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00001873 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001874
1875 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001876 case Expr::MLV_Valid:
1877 break;
1878 case Expr::MLV_ConstQualified:
1879 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1880 return QualType();
1881 case Expr::MLV_ArrayType:
1882 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1883 lhsType.getAsString(), lex->getSourceRange());
1884 return QualType();
1885 case Expr::MLV_NotObjectType:
1886 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1887 lhsType.getAsString(), lex->getSourceRange());
1888 return QualType();
1889 case Expr::MLV_InvalidExpression:
1890 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1891 lex->getSourceRange());
1892 return QualType();
1893 case Expr::MLV_IncompleteType:
1894 case Expr::MLV_IncompleteVoidType:
1895 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1896 lhsType.getAsString(), lex->getSourceRange());
1897 return QualType();
1898 case Expr::MLV_DuplicateVectorComponents:
1899 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1900 lex->getSourceRange());
1901 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001902 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001903
Chris Lattner005ed752008-01-04 18:04:52 +00001904 AssignConvertType ConvTy;
1905 if (compoundType.isNull())
1906 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1907 else
1908 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1909
1910 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1911 rex, "assigning"))
1912 return QualType();
1913
Chris Lattner4b009652007-07-25 00:24:17 +00001914 // C99 6.5.16p3: The type of an assignment expression is the type of the
1915 // left operand unless the left operand has qualified type, in which case
1916 // it is the unqualified version of the type of the left operand.
1917 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1918 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001919 // C++ 5.17p1: the type of the assignment expression is that of its left
1920 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001921 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001922}
1923
1924inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1925 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00001926
1927 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
1928 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001929 return rex->getType();
1930}
1931
1932/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1933/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1934QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1935 QualType resType = op->getType();
1936 assert(!resType.isNull() && "no type for increment/decrement expression");
1937
Steve Naroffd30e1932007-08-24 17:20:07 +00001938 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001939 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001940 if (pt->getPointeeType()->isVoidType()) {
1941 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1942 } else if (!pt->getPointeeType()->isObjectType()) {
1943 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001944 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1945 resType.getAsString(), op->getSourceRange());
1946 return QualType();
1947 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001948 } else if (!resType->isRealType()) {
1949 if (resType->isComplexType())
1950 // C99 does not support ++/-- on complex types.
1951 Diag(OpLoc, diag::ext_integer_increment_complex,
1952 resType.getAsString(), op->getSourceRange());
1953 else {
1954 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1955 resType.getAsString(), op->getSourceRange());
1956 return QualType();
1957 }
Chris Lattner4b009652007-07-25 00:24:17 +00001958 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001959 // At this point, we know we have a real, complex or pointer type.
1960 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00001961 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001962 if (mlval != Expr::MLV_Valid) {
1963 // FIXME: emit a more precise diagnostic...
1964 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1965 op->getSourceRange());
1966 return QualType();
1967 }
1968 return resType;
1969}
1970
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001971/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001972/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00001973/// where the declaration is needed for type checking. We only need to
1974/// handle cases when the expression references a function designator
1975/// or is an lvalue. Here are some examples:
1976/// - &(x) => x
1977/// - &*****f => f for f a function designator.
1978/// - &s.xx => s
1979/// - &s.zz[1].yy -> s, if zz is an array
1980/// - *(x + 1) -> x, if x is an array
1981/// - &"123"[2] -> 0
1982/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00001983static ValueDecl *getPrimaryDecl(Expr *E) {
1984 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001985 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001986 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001987 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001988 // Fields cannot be declared with a 'register' storage class.
1989 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001990 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001991 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001992 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001993 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00001994 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001995
Chris Lattner48d7f382008-04-02 04:24:33 +00001996 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001997 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001998 return 0;
1999 else
2000 return VD;
2001 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002002 case Stmt::UnaryOperatorClass: {
2003 UnaryOperator *UO = cast<UnaryOperator>(E);
2004
2005 switch(UO->getOpcode()) {
2006 case UnaryOperator::Deref: {
2007 // *(X + 1) refers to X if X is not a pointer.
2008 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2009 if (!VD || VD->getType()->isPointerType())
2010 return 0;
2011 return VD;
2012 }
2013 case UnaryOperator::Real:
2014 case UnaryOperator::Imag:
2015 case UnaryOperator::Extension:
2016 return getPrimaryDecl(UO->getSubExpr());
2017 default:
2018 return 0;
2019 }
2020 }
2021 case Stmt::BinaryOperatorClass: {
2022 BinaryOperator *BO = cast<BinaryOperator>(E);
2023
2024 // Handle cases involving pointer arithmetic. The result of an
2025 // Assign or AddAssign is not an lvalue so they can be ignored.
2026
2027 // (x + n) or (n + x) => x
2028 if (BO->getOpcode() == BinaryOperator::Add) {
2029 if (BO->getLHS()->getType()->isPointerType()) {
2030 return getPrimaryDecl(BO->getLHS());
2031 } else if (BO->getRHS()->getType()->isPointerType()) {
2032 return getPrimaryDecl(BO->getRHS());
2033 }
2034 }
2035
2036 return 0;
2037 }
Chris Lattner4b009652007-07-25 00:24:17 +00002038 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002039 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002040 case Stmt::ImplicitCastExprClass:
2041 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002042 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002043 default:
2044 return 0;
2045 }
2046}
2047
2048/// CheckAddressOfOperand - The operand of & must be either a function
2049/// designator or an lvalue designating an object. If it is an lvalue, the
2050/// object cannot be declared with storage class register or be a bit field.
2051/// Note: The usual conversions are *not* applied to the operand of the &
2052/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2053QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002054 if (getLangOptions().C99) {
2055 // Implement C99-only parts of addressof rules.
2056 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2057 if (uOp->getOpcode() == UnaryOperator::Deref)
2058 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2059 // (assuming the deref expression is valid).
2060 return uOp->getSubExpr()->getType();
2061 }
2062 // Technically, there should be a check for array subscript
2063 // expressions here, but the result of one is always an lvalue anyway.
2064 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002065 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002066 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002067
2068 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002069 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2070 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002071 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2072 op->getSourceRange());
2073 return QualType();
2074 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002075 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2076 if (MemExpr->getMemberDecl()->isBitField()) {
2077 Diag(OpLoc, diag::err_typecheck_address_of,
2078 std::string("bit-field"), op->getSourceRange());
2079 return QualType();
2080 }
2081 // Check for Apple extension for accessing vector components.
2082 } else if (isa<ArraySubscriptExpr>(op) &&
2083 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2084 Diag(OpLoc, diag::err_typecheck_address_of,
2085 std::string("vector"), op->getSourceRange());
2086 return QualType();
2087 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002088 // We have an lvalue with a decl. Make sure the decl is not declared
2089 // with the register storage-class specifier.
2090 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2091 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002092 Diag(OpLoc, diag::err_typecheck_address_of,
2093 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002094 return QualType();
2095 }
2096 } else
2097 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002098 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002099
Chris Lattner4b009652007-07-25 00:24:17 +00002100 // If the operand has type "type", the result has type "pointer to type".
2101 return Context.getPointerType(op->getType());
2102}
2103
2104QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2105 UsualUnaryConversions(op);
2106 QualType qType = op->getType();
2107
Chris Lattner7931f4a2007-07-31 16:53:04 +00002108 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002109 // Note that per both C89 and C99, this is always legal, even
2110 // if ptype is an incomplete type or void.
2111 // It would be possible to warn about dereferencing a
2112 // void pointer, but it's completely well-defined,
2113 // and such a warning is unlikely to catch any mistakes.
2114 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002115 }
2116 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2117 qType.getAsString(), op->getSourceRange());
2118 return QualType();
2119}
2120
2121static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2122 tok::TokenKind Kind) {
2123 BinaryOperator::Opcode Opc;
2124 switch (Kind) {
2125 default: assert(0 && "Unknown binop!");
2126 case tok::star: Opc = BinaryOperator::Mul; break;
2127 case tok::slash: Opc = BinaryOperator::Div; break;
2128 case tok::percent: Opc = BinaryOperator::Rem; break;
2129 case tok::plus: Opc = BinaryOperator::Add; break;
2130 case tok::minus: Opc = BinaryOperator::Sub; break;
2131 case tok::lessless: Opc = BinaryOperator::Shl; break;
2132 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2133 case tok::lessequal: Opc = BinaryOperator::LE; break;
2134 case tok::less: Opc = BinaryOperator::LT; break;
2135 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2136 case tok::greater: Opc = BinaryOperator::GT; break;
2137 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2138 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2139 case tok::amp: Opc = BinaryOperator::And; break;
2140 case tok::caret: Opc = BinaryOperator::Xor; break;
2141 case tok::pipe: Opc = BinaryOperator::Or; break;
2142 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2143 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2144 case tok::equal: Opc = BinaryOperator::Assign; break;
2145 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2146 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2147 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2148 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2149 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2150 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2151 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2152 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2153 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2154 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2155 case tok::comma: Opc = BinaryOperator::Comma; break;
2156 }
2157 return Opc;
2158}
2159
2160static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2161 tok::TokenKind Kind) {
2162 UnaryOperator::Opcode Opc;
2163 switch (Kind) {
2164 default: assert(0 && "Unknown unary op!");
2165 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2166 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2167 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2168 case tok::star: Opc = UnaryOperator::Deref; break;
2169 case tok::plus: Opc = UnaryOperator::Plus; break;
2170 case tok::minus: Opc = UnaryOperator::Minus; break;
2171 case tok::tilde: Opc = UnaryOperator::Not; break;
2172 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2173 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2174 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2175 case tok::kw___real: Opc = UnaryOperator::Real; break;
2176 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2177 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2178 }
2179 return Opc;
2180}
2181
2182// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002183Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002184 ExprTy *LHS, ExprTy *RHS) {
2185 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2186 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2187
Steve Naroff87d58b42007-09-16 03:34:24 +00002188 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2189 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002190
2191 QualType ResultTy; // Result type of the binary operator.
2192 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2193
2194 switch (Opc) {
2195 default:
2196 assert(0 && "Unknown binary expr!");
2197 case BinaryOperator::Assign:
2198 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2199 break;
2200 case BinaryOperator::Mul:
2201 case BinaryOperator::Div:
2202 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2203 break;
2204 case BinaryOperator::Rem:
2205 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2206 break;
2207 case BinaryOperator::Add:
2208 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2209 break;
2210 case BinaryOperator::Sub:
2211 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2212 break;
2213 case BinaryOperator::Shl:
2214 case BinaryOperator::Shr:
2215 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2216 break;
2217 case BinaryOperator::LE:
2218 case BinaryOperator::LT:
2219 case BinaryOperator::GE:
2220 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002221 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002222 break;
2223 case BinaryOperator::EQ:
2224 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002225 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002226 break;
2227 case BinaryOperator::And:
2228 case BinaryOperator::Xor:
2229 case BinaryOperator::Or:
2230 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2231 break;
2232 case BinaryOperator::LAnd:
2233 case BinaryOperator::LOr:
2234 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2235 break;
2236 case BinaryOperator::MulAssign:
2237 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002238 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002239 if (!CompTy.isNull())
2240 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2241 break;
2242 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002243 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002244 if (!CompTy.isNull())
2245 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2246 break;
2247 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002248 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002249 if (!CompTy.isNull())
2250 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2251 break;
2252 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002253 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002254 if (!CompTy.isNull())
2255 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2256 break;
2257 case BinaryOperator::ShlAssign:
2258 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002259 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002260 if (!CompTy.isNull())
2261 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2262 break;
2263 case BinaryOperator::AndAssign:
2264 case BinaryOperator::XorAssign:
2265 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002266 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002267 if (!CompTy.isNull())
2268 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2269 break;
2270 case BinaryOperator::Comma:
2271 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2272 break;
2273 }
2274 if (ResultTy.isNull())
2275 return true;
2276 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002277 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002278 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002279 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002280}
2281
2282// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002283Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002284 ExprTy *input) {
2285 Expr *Input = (Expr*)input;
2286 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2287 QualType resultType;
2288 switch (Opc) {
2289 default:
2290 assert(0 && "Unimplemented unary expr!");
2291 case UnaryOperator::PreInc:
2292 case UnaryOperator::PreDec:
2293 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2294 break;
2295 case UnaryOperator::AddrOf:
2296 resultType = CheckAddressOfOperand(Input, OpLoc);
2297 break;
2298 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002299 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002300 resultType = CheckIndirectionOperand(Input, OpLoc);
2301 break;
2302 case UnaryOperator::Plus:
2303 case UnaryOperator::Minus:
2304 UsualUnaryConversions(Input);
2305 resultType = Input->getType();
2306 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2307 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2308 resultType.getAsString());
2309 break;
2310 case UnaryOperator::Not: // bitwise complement
2311 UsualUnaryConversions(Input);
2312 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002313 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2314 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2315 // C99 does not support '~' for complex conjugation.
2316 Diag(OpLoc, diag::ext_integer_complement_complex,
2317 resultType.getAsString(), Input->getSourceRange());
2318 else if (!resultType->isIntegerType())
2319 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2320 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002321 break;
2322 case UnaryOperator::LNot: // logical negation
2323 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2324 DefaultFunctionArrayConversion(Input);
2325 resultType = Input->getType();
2326 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2327 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2328 resultType.getAsString());
2329 // LNot always has type int. C99 6.5.3.3p5.
2330 resultType = Context.IntTy;
2331 break;
2332 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002333 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2334 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002335 break;
2336 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002337 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2338 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002339 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002340 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002341 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002342 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002343 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002344 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002345 resultType = Input->getType();
2346 break;
2347 }
2348 if (resultType.isNull())
2349 return true;
2350 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2351}
2352
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002353/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2354Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002355 SourceLocation LabLoc,
2356 IdentifierInfo *LabelII) {
2357 // Look up the record for this label identifier.
2358 LabelStmt *&LabelDecl = LabelMap[LabelII];
2359
Daniel Dunbar879788d2008-08-04 16:51:22 +00002360 // If we haven't seen this label yet, create a forward reference. It
2361 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002362 if (LabelDecl == 0)
2363 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2364
2365 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002366 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2367 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002368}
2369
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002370Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002371 SourceLocation RPLoc) { // "({..})"
2372 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2373 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2374 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2375
2376 // FIXME: there are a variety of strange constraints to enforce here, for
2377 // example, it is not possible to goto into a stmt expression apparently.
2378 // More semantic analysis is needed.
2379
2380 // FIXME: the last statement in the compount stmt has its value used. We
2381 // should not warn about it being unused.
2382
2383 // If there are sub stmts in the compound stmt, take the type of the last one
2384 // as the type of the stmtexpr.
2385 QualType Ty = Context.VoidTy;
2386
Chris Lattner200964f2008-07-26 19:51:01 +00002387 if (!Compound->body_empty()) {
2388 Stmt *LastStmt = Compound->body_back();
2389 // If LastStmt is a label, skip down through into the body.
2390 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2391 LastStmt = Label->getSubStmt();
2392
2393 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002394 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002395 }
Chris Lattner4b009652007-07-25 00:24:17 +00002396
2397 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2398}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002399
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002400Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002401 SourceLocation TypeLoc,
2402 TypeTy *argty,
2403 OffsetOfComponent *CompPtr,
2404 unsigned NumComponents,
2405 SourceLocation RPLoc) {
2406 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2407 assert(!ArgTy.isNull() && "Missing type argument!");
2408
2409 // We must have at least one component that refers to the type, and the first
2410 // one is known to be a field designator. Verify that the ArgTy represents
2411 // a struct/union/class.
2412 if (!ArgTy->isRecordType())
2413 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2414
2415 // Otherwise, create a compound literal expression as the base, and
2416 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002417 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002418
Chris Lattnerb37522e2007-08-31 21:49:13 +00002419 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2420 // GCC extension, diagnose them.
2421 if (NumComponents != 1)
2422 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2423 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2424
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002425 for (unsigned i = 0; i != NumComponents; ++i) {
2426 const OffsetOfComponent &OC = CompPtr[i];
2427 if (OC.isBrackets) {
2428 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002429 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002430 if (!AT) {
2431 delete Res;
2432 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2433 Res->getType().getAsString());
2434 }
2435
Chris Lattner2af6a802007-08-30 17:59:59 +00002436 // FIXME: C++: Verify that operator[] isn't overloaded.
2437
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002438 // C99 6.5.2.1p1
2439 Expr *Idx = static_cast<Expr*>(OC.U.E);
2440 if (!Idx->getType()->isIntegerType())
2441 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2442 Idx->getSourceRange());
2443
2444 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2445 continue;
2446 }
2447
2448 const RecordType *RC = Res->getType()->getAsRecordType();
2449 if (!RC) {
2450 delete Res;
2451 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2452 Res->getType().getAsString());
2453 }
2454
2455 // Get the decl corresponding to this.
2456 RecordDecl *RD = RC->getDecl();
2457 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2458 if (!MemberDecl)
2459 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2460 OC.U.IdentInfo->getName(),
2461 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002462
2463 // FIXME: C++: Verify that MemberDecl isn't a static field.
2464 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002465 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2466 // matter here.
2467 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002468 }
2469
2470 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2471 BuiltinLoc);
2472}
2473
2474
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002475Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002476 TypeTy *arg1, TypeTy *arg2,
2477 SourceLocation RPLoc) {
2478 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2479 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2480
2481 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2482
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002483 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002484}
2485
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002486Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002487 ExprTy *expr1, ExprTy *expr2,
2488 SourceLocation RPLoc) {
2489 Expr *CondExpr = static_cast<Expr*>(cond);
2490 Expr *LHSExpr = static_cast<Expr*>(expr1);
2491 Expr *RHSExpr = static_cast<Expr*>(expr2);
2492
2493 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2494
2495 // The conditional expression is required to be a constant expression.
2496 llvm::APSInt condEval(32);
2497 SourceLocation ExpLoc;
2498 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2499 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2500 CondExpr->getSourceRange());
2501
2502 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2503 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2504 RHSExpr->getType();
2505 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2506}
2507
Nate Begemanbd881ef2008-01-30 20:50:20 +00002508/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002509/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002510/// The number of arguments has already been validated to match the number of
2511/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002512static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2513 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002514 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002515 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002516 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2517 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002518
2519 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002520 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002521 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002522 return true;
2523}
2524
2525Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2526 SourceLocation *CommaLocs,
2527 SourceLocation BuiltinLoc,
2528 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002529 // __builtin_overload requires at least 2 arguments
2530 if (NumArgs < 2)
2531 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2532 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002533
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002534 // The first argument is required to be a constant expression. It tells us
2535 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002536 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002537 Expr *NParamsExpr = Args[0];
2538 llvm::APSInt constEval(32);
2539 SourceLocation ExpLoc;
2540 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2541 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2542 NParamsExpr->getSourceRange());
2543
2544 // Verify that the number of parameters is > 0
2545 unsigned NumParams = constEval.getZExtValue();
2546 if (NumParams == 0)
2547 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2548 NParamsExpr->getSourceRange());
2549 // Verify that we have at least 1 + NumParams arguments to the builtin.
2550 if ((NumParams + 1) > NumArgs)
2551 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2552 SourceRange(BuiltinLoc, RParenLoc));
2553
2554 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002555 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002556 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002557 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2558 // UsualUnaryConversions will convert the function DeclRefExpr into a
2559 // pointer to function.
2560 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002561 const FunctionTypeProto *FnType = 0;
2562 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2563 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002564
2565 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2566 // parameters, and the number of parameters must match the value passed to
2567 // the builtin.
2568 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002569 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2570 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002571
2572 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002573 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002574 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002575 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002576 if (OE)
2577 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2578 OE->getFn()->getSourceRange());
2579 // Remember our match, and continue processing the remaining arguments
2580 // to catch any errors.
2581 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2582 BuiltinLoc, RParenLoc);
2583 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002584 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002585 // Return the newly created OverloadExpr node, if we succeded in matching
2586 // exactly one of the candidate functions.
2587 if (OE)
2588 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002589
2590 // If we didn't find a matching function Expr in the __builtin_overload list
2591 // the return an error.
2592 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002593 for (unsigned i = 0; i != NumParams; ++i) {
2594 if (i != 0) typeNames += ", ";
2595 typeNames += Args[i+1]->getType().getAsString();
2596 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002597
2598 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2599 SourceRange(BuiltinLoc, RParenLoc));
2600}
2601
Anders Carlsson36760332007-10-15 20:28:48 +00002602Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2603 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002604 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002605 Expr *E = static_cast<Expr*>(expr);
2606 QualType T = QualType::getFromOpaquePtr(type);
2607
2608 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002609
2610 // Get the va_list type
2611 QualType VaListType = Context.getBuiltinVaListType();
2612 // Deal with implicit array decay; for example, on x86-64,
2613 // va_list is an array, but it's supposed to decay to
2614 // a pointer for va_arg.
2615 if (VaListType->isArrayType())
2616 VaListType = Context.getArrayDecayedType(VaListType);
2617
2618 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002619 return Diag(E->getLocStart(),
2620 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2621 E->getType().getAsString(),
2622 E->getSourceRange());
2623
2624 // FIXME: Warn if a non-POD type is passed in.
2625
2626 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2627}
2628
Chris Lattner005ed752008-01-04 18:04:52 +00002629bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2630 SourceLocation Loc,
2631 QualType DstType, QualType SrcType,
2632 Expr *SrcExpr, const char *Flavor) {
2633 // Decode the result (notice that AST's are still created for extensions).
2634 bool isInvalid = false;
2635 unsigned DiagKind;
2636 switch (ConvTy) {
2637 default: assert(0 && "Unknown conversion type");
2638 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002639 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002640 DiagKind = diag::ext_typecheck_convert_pointer_int;
2641 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002642 case IntToPointer:
2643 DiagKind = diag::ext_typecheck_convert_int_pointer;
2644 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002645 case IncompatiblePointer:
2646 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2647 break;
2648 case FunctionVoidPointer:
2649 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2650 break;
2651 case CompatiblePointerDiscardsQualifiers:
2652 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2653 break;
2654 case Incompatible:
2655 DiagKind = diag::err_typecheck_convert_incompatible;
2656 isInvalid = true;
2657 break;
2658 }
2659
2660 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2661 SrcExpr->getSourceRange());
2662 return isInvalid;
2663}