blob: 2e99b3dfe81299f1a8a9e405860f5eec7094f9e0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Chris Lattnere7a2e912008-07-25 21:10:04 +000026//===----------------------------------------------------------------------===//
27// Standard Promotions and Conversions
28//===----------------------------------------------------------------------===//
29
Chris Lattnere7a2e912008-07-25 21:10:04 +000030/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
31void Sema::DefaultFunctionArrayConversion(Expr *&E) {
32 QualType Ty = E->getType();
33 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
34
35 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
36 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
37 Ty = E->getType();
38 }
39 if (Ty->isFunctionType())
40 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000041 else if (Ty->isArrayType()) {
42 // In C90 mode, arrays only promote to pointers if the array expression is
43 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
44 // type 'array of type' is converted to an expression that has type 'pointer
45 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
46 // that has type 'array of type' ...". The relevant change is "an lvalue"
47 // (C90) to "an expression" (C99).
Chris Lattner28be73f2008-07-26 21:30:36 +000048 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000049 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
50 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000051}
52
53/// UsualUnaryConversions - Performs various conversions that are common to most
54/// operators (C99 6.3). The conversions of array and function types are
55/// sometimes surpressed. For example, the array->pointer conversion doesn't
56/// apply if the array is an argument to the sizeof or address (&) operators.
57/// In these instances, this routine should *not* be called.
58Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
59 QualType Ty = Expr->getType();
60 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
61
62 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
63 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
64 Ty = Expr->getType();
65 }
66 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67 ImpCastExprToType(Expr, Context.IntTy);
68 else
69 DefaultFunctionArrayConversion(Expr);
70
71 return Expr;
72}
73
Chris Lattner05faf172008-07-25 22:25:12 +000074/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78 QualType Ty = Expr->getType();
79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81 // If this is a 'float' (CVR qualified or typedef) promote to double.
82 if (const BuiltinType *BT = Ty->getAsBuiltinType())
83 if (BT->getKind() == BuiltinType::Float)
84 return ImpCastExprToType(Expr, Context.DoubleTy);
85
86 UsualUnaryConversions(Expr);
87}
88
Chris Lattnere7a2e912008-07-25 21:10:04 +000089/// UsualArithmeticConversions - Performs various conversions that are common to
90/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
91/// routine returns the first non-arithmetic type found. The client is
92/// responsible for emitting appropriate error diagnostics.
93/// FIXME: verify the conversion rules for "complex int" are consistent with
94/// GCC.
95QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
96 bool isCompAssign) {
97 if (!isCompAssign) {
98 UsualUnaryConversions(lhsExpr);
99 UsualUnaryConversions(rhsExpr);
100 }
101 // For conversion purposes, we ignore any qualifiers.
102 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000103 QualType lhs =
104 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
105 QualType rhs =
106 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000107
108 // If both types are identical, no conversion is needed.
109 if (lhs == rhs)
110 return lhs;
111
112 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
113 // The caller can deal with this (e.g. pointer + int).
114 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
115 return lhs;
116
117 // At this point, we have two different arithmetic types.
118
119 // Handle complex types first (C99 6.3.1.8p1).
120 if (lhs->isComplexType() || rhs->isComplexType()) {
121 // if we have an integer operand, the result is the complex type.
122 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
123 // convert the rhs to the lhs complex type.
124 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
125 return lhs;
126 }
127 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
128 // convert the lhs to the rhs complex type.
129 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
130 return rhs;
131 }
132 // This handles complex/complex, complex/float, or float/complex.
133 // When both operands are complex, the shorter operand is converted to the
134 // type of the longer, and that is the type of the result. This corresponds
135 // to what is done when combining two real floating-point operands.
136 // The fun begins when size promotion occur across type domains.
137 // From H&S 6.3.4: When one operand is complex and the other is a real
138 // floating-point type, the less precise type is converted, within it's
139 // real or complex domain, to the precision of the other type. For example,
140 // when combining a "long double" with a "double _Complex", the
141 // "double _Complex" is promoted to "long double _Complex".
142 int result = Context.getFloatingTypeOrder(lhs, rhs);
143
144 if (result > 0) { // The left side is bigger, convert rhs.
145 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
146 if (!isCompAssign)
147 ImpCastExprToType(rhsExpr, rhs);
148 } else if (result < 0) { // The right side is bigger, convert lhs.
149 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
150 if (!isCompAssign)
151 ImpCastExprToType(lhsExpr, lhs);
152 }
153 // At this point, lhs and rhs have the same rank/size. Now, make sure the
154 // domains match. This is a requirement for our implementation, C99
155 // does not require this promotion.
156 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
157 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
158 if (!isCompAssign)
159 ImpCastExprToType(lhsExpr, rhs);
160 return rhs;
161 } else { // handle "_Complex double, double".
162 if (!isCompAssign)
163 ImpCastExprToType(rhsExpr, lhs);
164 return lhs;
165 }
166 }
167 return lhs; // The domain/size match exactly.
168 }
169 // Now handle "real" floating types (i.e. float, double, long double).
170 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
171 // if we have an integer operand, the result is the real floating type.
172 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
173 // convert rhs to the lhs floating point type.
174 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
175 return lhs;
176 }
177 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
178 // convert lhs to the rhs floating point type.
179 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
180 return rhs;
181 }
182 // We have two real floating types, float/complex combos were handled above.
183 // Convert the smaller operand to the bigger result.
184 int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186 if (result > 0) { // convert the rhs
187 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
188 return lhs;
189 }
190 if (result < 0) { // convert the lhs
191 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
192 return rhs;
193 }
194 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
195 }
196 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
197 // Handle GCC complex int extension.
198 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
199 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
200
201 if (lhsComplexInt && rhsComplexInt) {
202 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
203 rhsComplexInt->getElementType()) >= 0) {
204 // convert the rhs
205 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
206 return lhs;
207 }
208 if (!isCompAssign)
209 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
210 return rhs;
211 } else if (lhsComplexInt && rhs->isIntegerType()) {
212 // convert the rhs to the lhs complex type.
213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214 return lhs;
215 } else if (rhsComplexInt && lhs->isIntegerType()) {
216 // convert the lhs to the rhs complex type.
217 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
218 return rhs;
219 }
220 }
221 // Finally, we have two differing integer types.
222 // The rules for this case are in C99 6.3.1.8
223 int compare = Context.getIntegerTypeOrder(lhs, rhs);
224 bool lhsSigned = lhs->isSignedIntegerType(),
225 rhsSigned = rhs->isSignedIntegerType();
226 QualType destType;
227 if (lhsSigned == rhsSigned) {
228 // Same signedness; use the higher-ranked type
229 destType = compare >= 0 ? lhs : rhs;
230 } else if (compare != (lhsSigned ? 1 : -1)) {
231 // The unsigned type has greater than or equal rank to the
232 // signed type, so use the unsigned type
233 destType = lhsSigned ? rhs : lhs;
234 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
235 // The two types are different widths; if we are here, that
236 // means the signed type is larger than the unsigned type, so
237 // use the signed type.
238 destType = lhsSigned ? lhs : rhs;
239 } else {
240 // The signed type is higher-ranked than the unsigned type,
241 // but isn't actually any bigger (like unsigned int and long
242 // on most 32-bit systems). Use the unsigned type corresponding
243 // to the signed type.
244 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
245 }
246 if (!isCompAssign) {
247 ImpCastExprToType(lhsExpr, destType);
248 ImpCastExprToType(rhsExpr, destType);
249 }
250 return destType;
251}
252
253//===----------------------------------------------------------------------===//
254// Semantic Analysis for various Expression Types
255//===----------------------------------------------------------------------===//
256
257
Steve Narofff69936d2007-09-16 03:34:24 +0000258/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000259/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
260/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
261/// multiple tokens. However, the common case is that StringToks points to one
262/// string.
263///
264Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000265Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 assert(NumStringToks && "Must have at least one string!");
267
268 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
269 if (Literal.hadError)
270 return ExprResult(true);
271
272 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
273 for (unsigned i = 0; i != NumStringToks; ++i)
274 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000275
276 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000277 if (Literal.Pascal && Literal.GetStringLength() > 256)
278 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
279 SourceRange(StringToks[0].getLocation(),
280 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000281
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000282 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000283 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000284 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
285
286 // Get an array type for the string, according to C99 6.4.5. This includes
287 // the nul terminator character as well as the string length for pascal
288 // strings.
289 StrTy = Context.getConstantArrayType(StrTy,
290 llvm::APInt(32, Literal.GetStringLength()+1),
291 ArrayType::Normal, 0);
292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
294 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000295 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000296 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 StringToks[NumStringToks-1].getLocation());
298}
299
300
Steve Naroff08d92e42007-09-15 18:49:24 +0000301/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000302/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000303/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000304Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 IdentifierInfo &II,
306 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000307 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000308 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000309
310 // If this reference is in an Objective-C method, then ivar lookup happens as
311 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000312 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000313 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000314 // There are two cases to handle here. 1) scoped lookup could have failed,
315 // in which case we should look for an ivar. 2) scoped lookup could have
316 // found a decl, but that decl is outside the current method (i.e. a global
317 // variable). In these two cases, we do a lookup for an ivar with this
318 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000319 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000320 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000321 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000322 // FIXME: This should use a new expr for a direct reference, don't turn
323 // this into Self->ivar, just return a BareIVarExpr or something.
324 IdentifierInfo &II = Context.Idents.get("self");
325 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
326 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
327 static_cast<Expr*>(SelfExpr.Val), true, true);
328 }
329 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000330 // Needed to implement property "super.method" notation.
Steve Naroff8f0b1022008-06-05 18:14:25 +0000331 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000332 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000333 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000334 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000335 }
Chris Lattner8a934232008-03-31 00:36:02 +0000336 }
337
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 if (D == 0) {
339 // Otherwise, this could be an implicitly declared function reference (legal
340 // in C90, extension in C99).
341 if (HasTrailingLParen &&
Chris Lattner8a934232008-03-31 00:36:02 +0000342 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 D = ImplicitlyDefineFunction(Loc, II, S);
344 else {
345 // If this name wasn't predeclared and if this is not a function call,
346 // diagnose the problem.
347 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
348 }
349 }
Chris Lattner8a934232008-03-31 00:36:02 +0000350
Steve Naroffe1223f72007-08-28 03:03:08 +0000351 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner7e669b22008-02-29 16:48:43 +0000352 // check if referencing an identifier with __attribute__((deprecated)).
353 if (VD->getAttr<DeprecatedAttr>())
354 Diag(Loc, diag::warn_deprecated, VD->getName());
355
Steve Naroff53a32342007-08-28 18:45:29 +0000356 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000357 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000358 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000360 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000361
362 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
364 if (MD->isStatic())
365 // "invalid use of member 'x' in static member function"
366 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
367 FD->getName());
368 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
369 // "invalid use of nonstatic data member 'x'"
370 return Diag(Loc, diag::err_invalid_non_static_member_use,
371 FD->getName());
372
373 if (FD->isInvalidDecl())
374 return true;
375
376 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
377 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
378 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
379 true, FD, Loc, FD->getType());
380 }
381
382 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
383 }
Chris Lattner8a934232008-03-31 00:36:02 +0000384
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 if (isa<TypedefDecl>(D))
386 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000388 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000389 if (isa<NamespaceDecl>(D))
390 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
392 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000393 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000394}
395
Chris Lattnerd9f69102008-08-10 01:53:14 +0000396Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000397 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000398 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000401 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000402 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
403 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
404 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000406
407 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000408 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000409 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000410
Chris Lattnerfa28b302008-01-12 08:14:25 +0000411 // Pre-defined identifiers are of type char[x], where x is the length of the
412 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000413 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000414 if (getCurFunctionDecl())
415 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000416 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000417 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000418
Chris Lattner8f978d52008-01-12 19:32:28 +0000419 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000420 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000421 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000422 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000423}
424
Steve Narofff69936d2007-09-16 03:34:24 +0000425Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 llvm::SmallString<16> CharBuffer;
427 CharBuffer.resize(Tok.getLength());
428 const char *ThisTokBegin = &CharBuffer[0];
429 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
430
431 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
432 Tok.getLocation(), PP);
433 if (Literal.hadError())
434 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000435
436 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
437
Chris Lattnerc250aae2008-06-07 22:35:38 +0000438 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
439 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
Steve Narofff69936d2007-09-16 03:34:24 +0000442Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // fast path for a single digit (which is quite common). A single digit
444 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
445 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000446 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000447
Chris Lattner98be4942008-03-05 18:54:05 +0000448 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000449 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 Context.IntTy,
451 Tok.getLocation()));
452 }
453 llvm::SmallString<512> IntegerBuffer;
454 IntegerBuffer.resize(Tok.getLength());
455 const char *ThisTokBegin = &IntegerBuffer[0];
456
457 // Get the spelling of the token, which eliminates trigraphs, etc.
458 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
459 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
460 Tok.getLocation(), PP);
461 if (Literal.hadError)
462 return ExprResult(true);
463
Chris Lattner5d661452007-08-26 03:42:43 +0000464 Expr *Res;
465
466 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000467 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000468 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000469 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000470 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000471 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000472 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000473 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000474
475 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
476
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000477 // isExact will be set by GetFloatValue().
478 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000479 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000480 Ty, Tok.getLocation());
481
Chris Lattner5d661452007-08-26 03:42:43 +0000482 } else if (!Literal.isIntegerLiteral()) {
483 return ExprResult(true);
484 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000485 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000486
Neil Boothb9449512007-08-29 22:00:19 +0000487 // long long is a C99 feature.
488 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000489 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000490 Diag(Tok.getLocation(), diag::ext_longlong);
491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000493 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494
495 if (Literal.GetIntegerValue(ResultVal)) {
496 // If this value didn't fit into uintmax_t, warn and force to ull.
497 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000498 Ty = Context.UnsignedLongLongTy;
499 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000500 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 } else {
502 // If this value fits into a ULL, try to figure out what else it fits into
503 // according to the rules of C99 6.4.4.1p5.
504
505 // Octal, Hexadecimal, and integers with a U suffix are allowed to
506 // be an unsigned int.
507 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
508
509 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000510 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000511 if (!Literal.isLong && !Literal.isLongLong) {
512 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000513 unsigned IntSize = Context.Target.getIntWidth();
514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 // Does it fit in a unsigned int?
516 if (ResultVal.isIntN(IntSize)) {
517 // Does it fit in a signed int?
518 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000519 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000521 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000522 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 }
525
526 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000527 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000528 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000529
530 // Does it fit in a unsigned long?
531 if (ResultVal.isIntN(LongSize)) {
532 // Does it fit in a signed long?
533 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000534 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000536 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000537 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 }
540
541 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000542 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000543 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000544
545 // Does it fit in a unsigned long long?
546 if (ResultVal.isIntN(LongLongSize)) {
547 // Does it fit in a signed long long?
548 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000549 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000551 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000552 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 }
554 }
555
556 // If we still couldn't decide a type, we probably have something that
557 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000558 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000560 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000561 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000563
564 if (ResultVal.getBitWidth() != Width)
565 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 }
567
Chris Lattnerf0467b32008-04-02 04:24:33 +0000568 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 }
Chris Lattner5d661452007-08-26 03:42:43 +0000570
571 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
572 if (Literal.isImaginary)
573 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
574
575 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000576}
577
Steve Narofff69936d2007-09-16 03:34:24 +0000578Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000580 Expr *E = (Expr *)Val;
581 assert((E != 0) && "ActOnParenExpr() missing expr");
582 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000583}
584
585/// The UsualUnaryConversions() function is *not* called by this routine.
586/// See C99 6.3.2.1p[2-4] for more details.
587QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000588 SourceLocation OpLoc,
589 const SourceRange &ExprRange,
590 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 // C99 6.5.3.4p1:
592 if (isa<FunctionType>(exprType) && isSizeof)
593 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000594 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000596 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
597 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 else if (exprType->isIncompleteType()) {
599 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
600 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000601 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 return QualType(); // error
603 }
604 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
605 return Context.getSizeType();
606}
607
608Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000609ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 SourceLocation LPLoc, TypeTy *Ty,
611 SourceLocation RPLoc) {
612 // If error parsing type, ignore.
613 if (Ty == 0) return true;
614
615 // Verify that this is a valid expression.
616 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
617
Chris Lattnerbb280a42008-07-25 21:45:37 +0000618 QualType resultType =
619 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000620
621 if (resultType.isNull())
622 return true;
623 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
624}
625
Chris Lattner5d794252007-08-24 21:41:10 +0000626QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000627 DefaultFunctionArrayConversion(V);
628
Chris Lattnercc26ed72007-08-26 05:39:26 +0000629 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000630 if (const ComplexType *CT = V->getType()->getAsComplexType())
631 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000632
633 // Otherwise they pass through real integer and floating point types here.
634 if (V->getType()->isArithmeticType())
635 return V->getType();
636
637 // Reject anything else.
638 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
639 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000640}
641
642
Reid Spencer5f016e22007-07-11 17:01:13 +0000643
Steve Narofff69936d2007-09-16 03:34:24 +0000644Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 tok::TokenKind Kind,
646 ExprTy *Input) {
647 UnaryOperator::Opcode Opc;
648 switch (Kind) {
649 default: assert(0 && "Unknown unary op!");
650 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
651 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
652 }
653 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
654 if (result.isNull())
655 return true;
656 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
657}
658
659Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000660ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000662 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000663
664 // Perform default conversions.
665 DefaultFunctionArrayConversion(LHSExp);
666 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000667
Chris Lattner12d9ff62007-07-16 00:14:47 +0000668 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000669
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000671 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 // in the subscript position. As a result, we need to derive the array base
673 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000674 Expr *BaseExpr, *IndexExpr;
675 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000676 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000677 BaseExpr = LHSExp;
678 IndexExpr = RHSExp;
679 // FIXME: need to deal with const...
680 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000681 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000682 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000683 BaseExpr = RHSExp;
684 IndexExpr = LHSExp;
685 // FIXME: need to deal with const...
686 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000687 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
688 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000689 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000690
691 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000692 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
693 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000694 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000695 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000696 // FIXME: need to deal with const...
697 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000699 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
700 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 }
702 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000703 if (!IndexExpr->getType()->isIntegerType())
704 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
705 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000706
Chris Lattner12d9ff62007-07-16 00:14:47 +0000707 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
708 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000709 // void (*)(int)) and pointers to incomplete types. Functions are not
710 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000711 if (!ResultType->isObjectType())
712 return Diag(BaseExpr->getLocStart(),
713 diag::err_typecheck_subscript_not_object,
714 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
715
716 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000717}
718
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000719QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000720CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000721 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000722 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000723
724 // This flag determines whether or not the component is to be treated as a
725 // special name, or a regular GLSL-style component access.
726 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000727
728 // The vector accessor can't exceed the number of elements.
729 const char *compStr = CompName.getName();
730 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000731 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000732 baseType.getAsString(), SourceRange(CompLoc));
733 return QualType();
734 }
Nate Begeman8a997642008-05-09 06:41:27 +0000735
736 // Check that we've found one of the special components, or that the component
737 // names must come from the same set.
738 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
739 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
740 SpecialComponent = true;
741 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000742 do
743 compStr++;
744 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
745 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
746 do
747 compStr++;
748 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
749 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
750 do
751 compStr++;
752 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
753 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000754
Nate Begeman8a997642008-05-09 06:41:27 +0000755 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000756 // We didn't get to the end of the string. This means the component names
757 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000758 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000759 std::string(compStr,compStr+1), SourceRange(CompLoc));
760 return QualType();
761 }
762 // Each component accessor can't exceed the vector type.
763 compStr = CompName.getName();
764 while (*compStr) {
765 if (vecType->isAccessorWithinNumElements(*compStr))
766 compStr++;
767 else
768 break;
769 }
Nate Begeman8a997642008-05-09 06:41:27 +0000770 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000771 // We didn't get to the end of the string. This means a component accessor
772 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000773 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000774 baseType.getAsString(), SourceRange(CompLoc));
775 return QualType();
776 }
Nate Begeman8a997642008-05-09 06:41:27 +0000777
778 // If we have a special component name, verify that the current vector length
779 // is an even number, since all special component names return exactly half
780 // the elements.
781 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
782 return QualType();
783 }
784
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000785 // The component accessor looks fine - now we need to compute the actual type.
786 // The vector type is implied by the component accessor. For example,
787 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000788 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
789 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
790 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000791 if (CompSize == 1)
792 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000793
Nate Begeman213541a2008-04-18 23:10:10 +0000794 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000795 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000796 // diagostics look bad. We want extended vector types to appear built-in.
797 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
798 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
799 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000800 }
801 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000802}
803
Reid Spencer5f016e22007-07-11 17:01:13 +0000804Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000805ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 tok::TokenKind OpKind, SourceLocation MemberLoc,
807 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000808 Expr *BaseExpr = static_cast<Expr *>(Base);
809 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000810
811 // Perform default conversions.
812 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000814 QualType BaseType = BaseExpr->getType();
815 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000816
Chris Lattner68a057b2008-07-21 04:36:39 +0000817 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
818 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000820 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000821 BaseType = PT->getPointeeType();
822 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000823 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
824 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000826
Chris Lattner68a057b2008-07-21 04:36:39 +0000827 // Handle field access to simple records. This also handles access to fields
828 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000829 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000830 RecordDecl *RDecl = RTy->getDecl();
831 if (RTy->isIncompleteType())
832 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
833 BaseExpr->getSourceRange());
834 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000835 FieldDecl *MemberDecl = RDecl->getMember(&Member);
836 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000837 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
838 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000839
840 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000841 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000842 QualType MemberType = MemberDecl->getType();
843 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000844 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000845 MemberType = MemberType.getQualifiedType(combinedQualifiers);
846
Chris Lattner68a057b2008-07-21 04:36:39 +0000847 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000848 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000849 }
850
Chris Lattnera38e6b12008-07-21 04:59:05 +0000851 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
852 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000853 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
854 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000855 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000856 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000857 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000858 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000859 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000860 }
861
Chris Lattnera38e6b12008-07-21 04:59:05 +0000862 // Handle Objective-C property access, which is "Obj.property" where Obj is a
863 // pointer to a (potentially qualified) interface type.
864 const PointerType *PTy;
865 const ObjCInterfaceType *IFTy;
866 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
867 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
868 ObjCInterfaceDecl *IFace = IFTy->getDecl();
869
Chris Lattner6562fda2008-07-21 06:44:27 +0000870 // FIXME: The logic for looking up nullary and unary selectors should be
871 // shared with the code in ActOnInstanceMessage.
872
Chris Lattnera38e6b12008-07-21 04:59:05 +0000873 // Before we look for explicit property declarations, we check for
874 // nullary methods (which allow '.' notation).
875 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Chris Lattnera38e6b12008-07-21 04:59:05 +0000876 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel))
877 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
878 MemberLoc, BaseExpr);
879
Chris Lattner6562fda2008-07-21 06:44:27 +0000880 // If this reference is in an @implementation, check for 'private' methods.
881 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
882 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
883 if (ObjCImplementationDecl *ImpDecl =
884 ObjCImplementations[ClassDecl->getIdentifier()])
885 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel))
886 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
887 MemberLoc, BaseExpr);
888 }
889
Chris Lattnera38e6b12008-07-21 04:59:05 +0000890 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
891 // @interface NSBundle : NSObject {}
892 // - (NSString *)bundlePath;
893 // - (void)setBundlePath:(NSString *)x;
894 // @end
895 // void someMethod() { frameworkBundle.bundlePath = 0; }
896 //
897 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
898 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
899
900 // Lastly, check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000901 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
902 E = IFTy->qual_end(); I != E; ++I)
903 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
904 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000905 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000906
907 // Handle 'field access' to vectors, such as 'V.xx'.
908 if (BaseType->isExtVectorType() && OpKind == tok::period) {
909 // Component access limited to variables (reject vec4.rg.g).
910 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
911 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +0000912 return Diag(MemberLoc, diag::err_ext_vector_component_access,
913 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000914 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
915 if (ret.isNull())
916 return true;
917 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
918 }
919
Chris Lattner2a01b722008-07-21 05:35:34 +0000920 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
921 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000922}
923
Steve Narofff69936d2007-09-16 03:34:24 +0000924/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000925/// This provides the location of the left/right parens and a list of comma
926/// locations.
927Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000928ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +0000929 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000931 Expr *Fn = static_cast<Expr *>(fn);
932 Expr **Args = reinterpret_cast<Expr**>(args);
933 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +0000934 FunctionDecl *FDecl = NULL;
Chris Lattner04421082008-04-08 04:40:51 +0000935
936 // Promote the function operand.
937 UsualUnaryConversions(Fn);
938
939 // If we're directly calling a function, get the declaration for
940 // that function.
941 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
942 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
943 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
944
Chris Lattner925e60d2007-12-28 05:29:59 +0000945 // Make the call expr early, before semantic checks. This guarantees cleanup
946 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +0000947 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +0000948 Context.BoolTy, RParenLoc));
949
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
951 // type pointer to function".
Chris Lattner925e60d2007-12-28 05:29:59 +0000952 const PointerType *PT = Fn->getType()->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 if (PT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +0000954 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
955 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +0000956 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
957 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +0000958 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
959 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +0000960
961 // We know the result type of the call, set it.
962 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000963
Chris Lattner925e60d2007-12-28 05:29:59 +0000964 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
966 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +0000967 unsigned NumArgsInProto = Proto->getNumArgs();
968 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000969
Chris Lattner04421082008-04-08 04:40:51 +0000970 // If too few arguments are available (and we don't have default
971 // arguments for the remaining parameters), don't make the call.
972 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +0000973 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +0000974 // Use default arguments for missing arguments
975 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +0000976 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +0000977 } else
978 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
979 Fn->getSourceRange());
980 }
981
Chris Lattner925e60d2007-12-28 05:29:59 +0000982 // If too many are passed and not variadic, error on the extras and drop
983 // them.
984 if (NumArgs > NumArgsInProto) {
985 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000986 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000987 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000988 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000989 Args[NumArgs-1]->getLocEnd()));
990 // This deletes the extra arguments.
991 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 }
993 NumArgsToCheck = NumArgsInProto;
994 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000995
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +0000997 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +0000998 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +0000999
1000 Expr *Arg;
1001 if (i < NumArgs)
1002 Arg = Args[i];
1003 else
1004 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001005 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001006
Chris Lattner925e60d2007-12-28 05:29:59 +00001007 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001008 AssignConvertType ConvTy =
1009 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001010 TheCall->setArg(i, Arg);
1011
Chris Lattner5cf216b2008-01-04 18:04:52 +00001012 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1013 ArgType, Arg, "passing"))
1014 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001016
1017 // If this is a variadic call, handle args passed through "...".
1018 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001019 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001020 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1021 Expr *Arg = Args[i];
1022 DefaultArgumentPromotion(Arg);
1023 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001024 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001025 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001026 } else {
1027 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1028
Steve Naroffb291ab62007-08-28 23:30:39 +00001029 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001030 for (unsigned i = 0; i != NumArgs; i++) {
1031 Expr *Arg = Args[i];
1032 DefaultArgumentPromotion(Arg);
1033 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001034 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001036
Chris Lattner59907c42007-08-10 20:18:51 +00001037 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001038 if (FDecl)
1039 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001040
Chris Lattner925e60d2007-12-28 05:29:59 +00001041 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001042}
1043
1044Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001045ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001046 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001047 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001048 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001049 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001050 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001051 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001052
Eli Friedman6223c222008-05-20 05:22:08 +00001053 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001054 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001055 return Diag(LParenLoc,
1056 diag::err_variable_object_no_init,
1057 SourceRange(LParenLoc,
1058 literalExpr->getSourceRange().getEnd()));
1059 } else if (literalType->isIncompleteType()) {
1060 return Diag(LParenLoc,
1061 diag::err_typecheck_decl_incomplete_type,
1062 literalType.getAsString(),
1063 SourceRange(LParenLoc,
1064 literalExpr->getSourceRange().getEnd()));
1065 }
1066
Steve Naroffd0091aa2008-01-10 22:15:12 +00001067 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001068 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001069
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001070 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001071 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001072 if (CheckForConstantInitializer(literalExpr, literalType))
1073 return true;
1074 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001075 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001076}
1077
1078Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001079ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001080 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001081 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001082
Steve Naroff08d92e42007-09-15 18:49:24 +00001083 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001084 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001085
Chris Lattnerf0467b32008-04-02 04:24:33 +00001086 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1087 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1088 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001089}
1090
Chris Lattnerfe23e212007-12-20 00:44:32 +00001091bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001092 assert(VectorTy->isVectorType() && "Not a vector type!");
1093
1094 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001095 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001096 return Diag(R.getBegin(),
1097 Ty->isVectorType() ?
1098 diag::err_invalid_conversion_between_vectors :
1099 diag::err_invalid_conversion_between_vector_and_integer,
1100 VectorTy.getAsString().c_str(),
1101 Ty.getAsString().c_str(), R);
1102 } else
1103 return Diag(R.getBegin(),
1104 diag::err_invalid_conversion_between_vector_and_scalar,
1105 VectorTy.getAsString().c_str(),
1106 Ty.getAsString().c_str(), R);
1107
1108 return false;
1109}
1110
Steve Naroff4aa88f82007-07-19 01:06:55 +00001111Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001112ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001114 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001115
1116 Expr *castExpr = static_cast<Expr*>(Op);
1117 QualType castType = QualType::getFromOpaquePtr(Ty);
1118
Steve Naroff711602b2007-08-31 00:32:44 +00001119 UsualUnaryConversions(castExpr);
1120
Chris Lattner75af4802007-07-18 16:00:06 +00001121 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1122 // type needs to be scalar.
Chris Lattner32b62b62008-07-25 22:06:10 +00001123 if (castType->isVoidType()) {
1124 // Cast to void allows any expr type.
1125 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1126 // GCC struct/union extension: allow cast to self.
1127 if (Context.getCanonicalType(castType) !=
1128 Context.getCanonicalType(castExpr->getType()) ||
1129 (!castType->isStructureType() && !castType->isUnionType())) {
1130 // Reject any other conversions to non-scalar types.
1131 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
1132 castType.getAsString(), castExpr->getSourceRange());
Steve Naroff63564b82008-06-03 12:56:35 +00001133 }
Chris Lattner32b62b62008-07-25 22:06:10 +00001134
1135 // accept this, but emit an ext-warn.
1136 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
1137 castType.getAsString(), castExpr->getSourceRange());
1138 } else if (!castExpr->getType()->isScalarType() &&
1139 !castExpr->getType()->isVectorType()) {
1140 return Diag(castExpr->getLocStart(),
1141 diag::err_typecheck_expect_scalar_operand,
1142 castExpr->getType().getAsString(),castExpr->getSourceRange());
1143 } else if (castExpr->getType()->isVectorType()) {
1144 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1145 castExpr->getType(), castType))
1146 return true;
1147 } else if (castType->isVectorType()) {
1148 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1149 castType, castExpr->getType()))
1150 return true;
Steve Naroff16beff82007-07-16 23:25:18 +00001151 }
1152 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001153}
1154
Chris Lattnera21ddb32007-11-26 01:40:58 +00001155/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1156/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001157inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001158 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001159 UsualUnaryConversions(cond);
1160 UsualUnaryConversions(lex);
1161 UsualUnaryConversions(rex);
1162 QualType condT = cond->getType();
1163 QualType lexT = lex->getType();
1164 QualType rexT = rex->getType();
1165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001167 if (!condT->isScalarType()) { // C99 6.5.15p2
1168 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1169 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 return QualType();
1171 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001172
1173 // Now check the two expressions.
1174
1175 // If both operands have arithmetic type, do the usual arithmetic conversions
1176 // to find a common type: C99 6.5.15p3,5.
1177 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001178 UsualArithmeticConversions(lex, rex);
1179 return lex->getType();
1180 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001181
1182 // If both operands are the same structure or union type, the result is that
1183 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001184 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001185 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001186 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001187 // "If both the operands have structure or union type, the result has
1188 // that type." This implies that CV qualifiers are dropped.
1189 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001191
1192 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001193 // The following || allows only one side to be void (a GCC-ism).
1194 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001195 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001196 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1197 rex->getSourceRange());
1198 if (!rexT->isVoidType())
1199 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001200 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001201 ImpCastExprToType(lex, Context.VoidTy);
1202 ImpCastExprToType(rex, Context.VoidTy);
1203 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001204 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001205 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1206 // the type of the other operand."
1207 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001208 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001209 return lexT;
1210 }
1211 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001212 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001213 return rexT;
1214 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001215 // Handle the case where both operands are pointers before we handle null
1216 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001217 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1218 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1219 // get the "pointed to" types
1220 QualType lhptee = LHSPT->getPointeeType();
1221 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001222
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001223 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1224 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001225 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001226 // Figure out necessary qualifiers (C99 6.5.15p6)
1227 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001228 QualType destType = Context.getPointerType(destPointee);
1229 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1230 ImpCastExprToType(rex, destType); // promote to void*
1231 return destType;
1232 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001233 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001234 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001235 QualType destType = Context.getPointerType(destPointee);
1236 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1237 ImpCastExprToType(rex, destType); // promote to void*
1238 return destType;
1239 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001240
Steve Naroffec0550f2007-10-15 20:41:53 +00001241 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1242 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001243 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001244 lexT.getAsString(), rexT.getAsString(),
1245 lex->getSourceRange(), rex->getSourceRange());
Eli Friedmanb1284ac2008-01-30 17:02:03 +00001246 // In this situation, we assume void* type. No especially good
1247 // reason, but this is what gcc does, and we do have to pick
1248 // to get a consistent AST.
1249 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1250 ImpCastExprToType(lex, voidPtrTy);
1251 ImpCastExprToType(rex, voidPtrTy);
1252 return voidPtrTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001253 }
1254 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001255 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1256 // differently qualified versions of compatible types, the result type is
1257 // a pointer to an appropriately qualified version of the *composite*
1258 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001259 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001260 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001261 QualType compositeType = lexT;
1262 ImpCastExprToType(lex, compositeType);
1263 ImpCastExprToType(rex, compositeType);
1264 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 }
1266 }
Steve Naroffaa73eec2008-05-31 22:33:45 +00001267 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1268 // evaluates to "struct objc_object *" (and is handled above when comparing
1269 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1270 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1271 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1272 return Context.getObjCIdType();
1273 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001274 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001276 lexT.getAsString(), rexT.getAsString(),
1277 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 return QualType();
1279}
1280
Steve Narofff69936d2007-09-16 03:34:24 +00001281/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001282/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001283Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 SourceLocation ColonLoc,
1285 ExprTy *Cond, ExprTy *LHS,
1286 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001287 Expr *CondExpr = (Expr *) Cond;
1288 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001289
1290 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1291 // was the condition.
1292 bool isLHSNull = LHSExpr == 0;
1293 if (isLHSNull)
1294 LHSExpr = CondExpr;
1295
Chris Lattner26824902007-07-16 21:39:03 +00001296 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1297 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 if (result.isNull())
1299 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001300 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1301 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302}
1303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304
1305// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1306// being closely modeled after the C99 spec:-). The odd characteristic of this
1307// routine is it effectively iqnores the qualifiers on the top level pointee.
1308// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1309// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001310Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001311Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1312 QualType lhptee, rhptee;
1313
1314 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001315 lhptee = lhsType->getAsPointerType()->getPointeeType();
1316 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001317
1318 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001319 lhptee = Context.getCanonicalType(lhptee);
1320 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001321
Chris Lattner5cf216b2008-01-04 18:04:52 +00001322 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001323
1324 // C99 6.5.16.1p1: This following citation is common to constraints
1325 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1326 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001327 // FIXME: Handle ASQualType
1328 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1329 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001330 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001331
1332 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1333 // incomplete type and the other is a pointer to a qualified or unqualified
1334 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001335 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001336 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001337 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001338
1339 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001340 assert(rhptee->isFunctionType());
1341 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001342 }
1343
1344 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001345 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001346 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001347
1348 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001349 assert(lhptee->isFunctionType());
1350 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001351 }
1352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1354 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001355 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1356 rhptee.getUnqualifiedType()))
1357 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001358 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359}
1360
1361/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1362/// has code to accommodate several GCC extensions when type checking
1363/// pointers. Here are some objectionable examples that GCC considers warnings:
1364///
1365/// int a, *pint;
1366/// short *pshort;
1367/// struct foo *pfoo;
1368///
1369/// pint = pshort; // warning: assignment from incompatible pointer type
1370/// a = pint; // warning: assignment makes integer from pointer without a cast
1371/// pint = a; // warning: assignment makes pointer from integer without a cast
1372/// pint = pfoo; // warning: assignment from incompatible pointer type
1373///
1374/// As a result, the code for dealing with pointers is more complex than the
1375/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001376///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001377Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001378Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001379 // Get canonical types. We're not formatting these types, just comparing
1380 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001381 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1382 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001383
1384 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001385 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001386
Anders Carlsson793680e2007-10-12 23:56:29 +00001387 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001388 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001389 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001390 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001391 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001392
Chris Lattnereca7be62008-04-07 05:30:13 +00001393 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1394 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001395 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001396 // Relax integer conversions like we do for pointers below.
1397 if (rhsType->isIntegerType())
1398 return IntToPointer;
1399 if (lhsType->isIntegerType())
1400 return PointerToInt;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001401 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001402 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001403
Nate Begemanbe2341d2008-07-14 18:02:46 +00001404 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001405 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001406 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1407 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001408 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001409
Nate Begemanbe2341d2008-07-14 18:02:46 +00001410 // If we are allowing lax vector conversions, and LHS and RHS are both
1411 // vectors, the total size only needs to be the same. This is a bitcast;
1412 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001413 if (getLangOptions().LaxVectorConversions &&
1414 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001415 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1416 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001417 }
1418 return Incompatible;
1419 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001420
Chris Lattnere8b3e962008-01-04 23:32:24 +00001421 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001423
Chris Lattner78eca282008-04-07 06:49:41 +00001424 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001426 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001427
Chris Lattner78eca282008-04-07 06:49:41 +00001428 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001430 return Incompatible;
1431 }
1432
Chris Lattner78eca282008-04-07 06:49:41 +00001433 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001435 if (lhsType == Context.BoolTy)
1436 return Compatible;
1437
1438 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001439 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001440
Chris Lattner78eca282008-04-07 06:49:41 +00001441 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001443 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001444 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001445
Chris Lattnerfc144e22008-01-04 23:18:45 +00001446 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001447 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 }
1450 return Incompatible;
1451}
1452
Chris Lattner5cf216b2008-01-04 18:04:52 +00001453Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001454Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001455 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1456 // a null pointer constant.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001457 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001458 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001459 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001460 return Compatible;
1461 }
Chris Lattner943140e2007-10-16 02:55:40 +00001462 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001463 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001464 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001465 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001466 //
1467 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1468 // are better understood.
1469 if (!lhsType->isReferenceType())
1470 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001471
Chris Lattner5cf216b2008-01-04 18:04:52 +00001472 Sema::AssignConvertType result =
1473 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001474
1475 // C99 6.5.16.1p2: The value of the right operand is converted to the
1476 // type of the assignment expression.
1477 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001478 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001479 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001480}
1481
Chris Lattner5cf216b2008-01-04 18:04:52 +00001482Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001483Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1484 return CheckAssignmentConstraints(lhsType, rhsType);
1485}
1486
Chris Lattnerca5eede2007-12-12 05:47:28 +00001487QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 Diag(loc, diag::err_typecheck_invalid_operands,
1489 lex->getType().getAsString(), rex->getType().getAsString(),
1490 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001491 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001492}
1493
Steve Naroff49b45262007-07-13 16:58:59 +00001494inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1495 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001496 // For conversion purposes, we ignore any qualifiers.
1497 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001498 QualType lhsType =
1499 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1500 QualType rhsType =
1501 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001502
Nate Begemanbe2341d2008-07-14 18:02:46 +00001503 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001504 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001506
Nate Begemanbe2341d2008-07-14 18:02:46 +00001507 // Handle the case of a vector & extvector type of the same size and element
1508 // type. It would be nice if we only had one vector type someday.
1509 if (getLangOptions().LaxVectorConversions)
1510 if (const VectorType *LV = lhsType->getAsVectorType())
1511 if (const VectorType *RV = rhsType->getAsVectorType())
1512 if (LV->getElementType() == RV->getElementType() &&
1513 LV->getNumElements() == RV->getNumElements())
1514 return lhsType->isExtVectorType() ? lhsType : rhsType;
1515
1516 // If the lhs is an extended vector and the rhs is a scalar of the same type
1517 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001518 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001519 QualType eltType = V->getElementType();
1520
1521 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1522 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1523 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001524 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001525 return lhsType;
1526 }
1527 }
1528
Nate Begemanbe2341d2008-07-14 18:02:46 +00001529 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001530 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001531 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001532 QualType eltType = V->getElementType();
1533
1534 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1535 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1536 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001537 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001538 return rhsType;
1539 }
1540 }
1541
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // You cannot convert between vector values of different size.
1543 Diag(loc, diag::err_typecheck_vector_not_convertable,
1544 lex->getType().getAsString(), rex->getType().getAsString(),
1545 lex->getSourceRange(), rex->getSourceRange());
1546 return QualType();
1547}
1548
1549inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001550 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001551{
Steve Naroff90045e82007-07-13 23:32:42 +00001552 QualType lhsType = lex->getType(), rhsType = rex->getType();
1553
1554 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001556
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001557 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001558
Steve Naroffa4332e22007-07-17 00:58:39 +00001559 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001560 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001561 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001562}
1563
1564inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001565 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001566{
Steve Naroff90045e82007-07-13 23:32:42 +00001567 QualType lhsType = lex->getType(), rhsType = rex->getType();
1568
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001569 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
Steve Naroffa4332e22007-07-17 00:58:39 +00001571 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001572 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001573 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574}
1575
1576inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001577 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001578{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001579 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001580 return CheckVectorOperands(loc, lex, rex);
1581
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001582 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001583
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001585 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001586 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001587
Eli Friedmand72d16e2008-05-18 18:08:51 +00001588 // Put any potential pointer into PExp
1589 Expr* PExp = lex, *IExp = rex;
1590 if (IExp->getType()->isPointerType())
1591 std::swap(PExp, IExp);
1592
1593 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1594 if (IExp->getType()->isIntegerType()) {
1595 // Check for arithmetic on pointers to incomplete types
1596 if (!PTy->getPointeeType()->isObjectType()) {
1597 if (PTy->getPointeeType()->isVoidType()) {
1598 Diag(loc, diag::ext_gnu_void_ptr,
1599 lex->getSourceRange(), rex->getSourceRange());
1600 } else {
1601 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1602 lex->getType().getAsString(), lex->getSourceRange());
1603 return QualType();
1604 }
1605 }
1606 return PExp->getType();
1607 }
1608 }
1609
Chris Lattnerca5eede2007-12-12 05:47:28 +00001610 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001611}
1612
Chris Lattnereca7be62008-04-07 05:30:13 +00001613// C99 6.5.6
1614QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1615 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001616 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001618
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001619 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001620
Chris Lattner6e4ab612007-12-09 21:53:25 +00001621 // Enforce type constraints: C99 6.5.6p3.
1622
1623 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001624 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001625 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001626
1627 // Either ptr - int or ptr - ptr.
1628 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001629 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001630
Chris Lattner6e4ab612007-12-09 21:53:25 +00001631 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001632 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001633 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001634 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001635 Diag(loc, diag::ext_gnu_void_ptr,
1636 lex->getSourceRange(), rex->getSourceRange());
1637 } else {
1638 Diag(loc, diag::err_typecheck_sub_ptr_object,
1639 lex->getType().getAsString(), lex->getSourceRange());
1640 return QualType();
1641 }
1642 }
1643
1644 // The result type of a pointer-int computation is the pointer type.
1645 if (rex->getType()->isIntegerType())
1646 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001647
Chris Lattner6e4ab612007-12-09 21:53:25 +00001648 // Handle pointer-pointer subtractions.
1649 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001650 QualType rpointee = RHSPTy->getPointeeType();
1651
Chris Lattner6e4ab612007-12-09 21:53:25 +00001652 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001653 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001654 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001655 if (rpointee->isVoidType()) {
1656 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001657 Diag(loc, diag::ext_gnu_void_ptr,
1658 lex->getSourceRange(), rex->getSourceRange());
1659 } else {
1660 Diag(loc, diag::err_typecheck_sub_ptr_object,
1661 rex->getType().getAsString(), rex->getSourceRange());
1662 return QualType();
1663 }
1664 }
1665
1666 // Pointee types must be compatible.
Steve Naroff2565eef2008-01-29 18:58:14 +00001667 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1668 rpointee.getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001669 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1670 lex->getType().getAsString(), rex->getType().getAsString(),
1671 lex->getSourceRange(), rex->getSourceRange());
1672 return QualType();
1673 }
1674
1675 return Context.getPointerDiffType();
1676 }
1677 }
1678
Chris Lattnerca5eede2007-12-12 05:47:28 +00001679 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680}
1681
Chris Lattnereca7be62008-04-07 05:30:13 +00001682// C99 6.5.7
1683QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1684 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00001685 // C99 6.5.7p2: Each of the operands shall have integer type.
1686 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1687 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001688
Chris Lattnerca5eede2007-12-12 05:47:28 +00001689 // Shifts don't perform usual arithmetic conversions, they just do integer
1690 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001691 if (!isCompAssign)
1692 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001693 UsualUnaryConversions(rex);
1694
1695 // "The type of the result is that of the promoted left operand."
1696 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001697}
1698
Chris Lattnereca7be62008-04-07 05:30:13 +00001699// C99 6.5.8
1700QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1701 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001702 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1703 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1704
Chris Lattnera5937dd2007-08-26 01:18:55 +00001705 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001706 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1707 UsualArithmeticConversions(lex, rex);
1708 else {
1709 UsualUnaryConversions(lex);
1710 UsualUnaryConversions(rex);
1711 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001712 QualType lType = lex->getType();
1713 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001714
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001715 // For non-floating point types, check for self-comparisons of the form
1716 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1717 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001718 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001719 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1720 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001721 if (DRL->getDecl() == DRR->getDecl())
1722 Diag(loc, diag::warn_selfcomparison);
1723 }
1724
Chris Lattnera5937dd2007-08-26 01:18:55 +00001725 if (isRelational) {
1726 if (lType->isRealType() && rType->isRealType())
1727 return Context.IntTy;
1728 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001729 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001730 if (lType->isFloatingType()) {
1731 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001732 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001733 }
1734
Chris Lattnera5937dd2007-08-26 01:18:55 +00001735 if (lType->isArithmeticType() && rType->isArithmeticType())
1736 return Context.IntTy;
1737 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001738
Chris Lattnerd28f8152007-08-26 01:10:14 +00001739 bool LHSIsNull = lex->isNullPointerConstant(Context);
1740 bool RHSIsNull = rex->isNullPointerConstant(Context);
1741
Chris Lattnera5937dd2007-08-26 01:18:55 +00001742 // All of the following pointer related warnings are GCC extensions, except
1743 // when handling null pointer constants. One day, we can consider making them
1744 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001745 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001746 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00001747 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00001748 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00001749 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00001750
Steve Naroff66296cb2007-11-13 14:57:38 +00001751 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001752 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1753 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1754 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001755 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1756 lType.getAsString(), rType.getAsString(),
1757 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00001759 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001760 return Context.IntTy;
1761 }
Steve Naroff20373222008-06-03 14:04:54 +00001762 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1763 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1764 ImpCastExprToType(rex, lType);
1765 return Context.IntTy;
1766 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001767 }
Steve Naroff20373222008-06-03 14:04:54 +00001768 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1769 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001770 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001771 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1772 lType.getAsString(), rType.getAsString(),
1773 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001774 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001775 return Context.IntTy;
1776 }
Steve Naroff20373222008-06-03 14:04:54 +00001777 if (lType->isIntegerType() &&
1778 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001779 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001780 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1781 lType.getAsString(), rType.getAsString(),
1782 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001783 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001784 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001786 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787}
1788
Nate Begemanbe2341d2008-07-14 18:02:46 +00001789/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1790/// operates on extended vector types. Instead of producing an IntTy result,
1791/// like a scalar comparison, a vector comparison produces a vector of integer
1792/// types.
1793QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1794 SourceLocation loc,
1795 bool isRelational) {
1796 // Check to make sure we're operating on vectors of the same type and width,
1797 // Allowing one side to be a scalar of element type.
1798 QualType vType = CheckVectorOperands(loc, lex, rex);
1799 if (vType.isNull())
1800 return vType;
1801
1802 QualType lType = lex->getType();
1803 QualType rType = rex->getType();
1804
1805 // For non-floating point types, check for self-comparisons of the form
1806 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1807 // often indicate logic errors in the program.
1808 if (!lType->isFloatingType()) {
1809 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1810 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1811 if (DRL->getDecl() == DRR->getDecl())
1812 Diag(loc, diag::warn_selfcomparison);
1813 }
1814
1815 // Check for comparisons of floating point operands using != and ==.
1816 if (!isRelational && lType->isFloatingType()) {
1817 assert (rType->isFloatingType());
1818 CheckFloatComparison(loc,lex,rex);
1819 }
1820
1821 // Return the type for the comparison, which is the same as vector type for
1822 // integer vectors, or an integer type of identical size and number of
1823 // elements for floating point vectors.
1824 if (lType->isIntegerType())
1825 return lType;
1826
1827 const VectorType *VTy = lType->getAsVectorType();
1828
1829 // FIXME: need to deal with non-32b int / non-64b long long
1830 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1831 if (TypeSize == 32) {
1832 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1833 }
1834 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1835 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1836}
1837
Reid Spencer5f016e22007-07-11 17:01:13 +00001838inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001839 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001840{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001841 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001843
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001844 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001845
Steve Naroffa4332e22007-07-17 00:58:39 +00001846 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001847 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001848 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001849}
1850
1851inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001852 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001853{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001854 UsualUnaryConversions(lex);
1855 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001856
Eli Friedman5773a6c2008-05-13 20:16:47 +00001857 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001859 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001860}
1861
1862inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001863 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001864{
1865 QualType lhsType = lex->getType();
1866 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00001867 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00001868
1869 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00001870 case Expr::MLV_Valid:
1871 break;
1872 case Expr::MLV_ConstQualified:
1873 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1874 return QualType();
1875 case Expr::MLV_ArrayType:
1876 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1877 lhsType.getAsString(), lex->getSourceRange());
1878 return QualType();
1879 case Expr::MLV_NotObjectType:
1880 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1881 lhsType.getAsString(), lex->getSourceRange());
1882 return QualType();
1883 case Expr::MLV_InvalidExpression:
1884 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1885 lex->getSourceRange());
1886 return QualType();
1887 case Expr::MLV_IncompleteType:
1888 case Expr::MLV_IncompleteVoidType:
1889 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1890 lhsType.getAsString(), lex->getSourceRange());
1891 return QualType();
1892 case Expr::MLV_DuplicateVectorComponents:
1893 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1894 lex->getSourceRange());
1895 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00001897
Chris Lattner5cf216b2008-01-04 18:04:52 +00001898 AssignConvertType ConvTy;
1899 if (compoundType.isNull())
1900 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1901 else
1902 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1903
1904 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1905 rex, "assigning"))
1906 return QualType();
1907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // C99 6.5.16p3: The type of an assignment expression is the type of the
1909 // left operand unless the left operand has qualified type, in which case
1910 // it is the unqualified version of the type of the left operand.
1911 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1912 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001913 // C++ 5.17p1: the type of the assignment expression is that of its left
1914 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001915 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001916}
1917
1918inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001919 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00001920
1921 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
1922 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001923 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001924}
1925
Steve Naroff49b45262007-07-13 16:58:59 +00001926/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1927/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001928QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001929 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 assert(!resType.isNull() && "no type for increment/decrement expression");
1931
Steve Naroff084f9ed2007-08-24 17:20:07 +00001932 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001933 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00001934 if (pt->getPointeeType()->isVoidType()) {
1935 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1936 } else if (!pt->getPointeeType()->isObjectType()) {
1937 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1939 resType.getAsString(), op->getSourceRange());
1940 return QualType();
1941 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001942 } else if (!resType->isRealType()) {
1943 if (resType->isComplexType())
1944 // C99 does not support ++/-- on complex types.
1945 Diag(OpLoc, diag::ext_integer_increment_complex,
1946 resType.getAsString(), op->getSourceRange());
1947 else {
1948 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1949 resType.getAsString(), op->getSourceRange());
1950 return QualType();
1951 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001953 // At this point, we know we have a real, complex or pointer type.
1954 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00001955 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 if (mlval != Expr::MLV_Valid) {
1957 // FIXME: emit a more precise diagnostic...
1958 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1959 op->getSourceRange());
1960 return QualType();
1961 }
1962 return resType;
1963}
1964
Anders Carlsson369dee42008-02-01 07:15:58 +00001965/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00001966/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00001967/// where the declaration is needed for type checking. We only need to
1968/// handle cases when the expression references a function designator
1969/// or is an lvalue. Here are some examples:
1970/// - &(x) => x
1971/// - &*****f => f for f a function designator.
1972/// - &s.xx => s
1973/// - &s.zz[1].yy -> s, if zz is an array
1974/// - *(x + 1) -> x, if x is an array
1975/// - &"123"[2] -> 0
1976/// - & __real__ x -> x
Chris Lattnerf0467b32008-04-02 04:24:33 +00001977static ValueDecl *getPrimaryDecl(Expr *E) {
1978 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00001980 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001982 // Fields cannot be declared with a 'register' storage class.
1983 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001984 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00001985 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00001986 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00001987 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00001988 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00001989
Chris Lattnerf0467b32008-04-02 04:24:33 +00001990 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlssonf2a4b842008-02-01 16:01:31 +00001991 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00001992 return 0;
1993 else
1994 return VD;
1995 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00001996 case Stmt::UnaryOperatorClass: {
1997 UnaryOperator *UO = cast<UnaryOperator>(E);
1998
1999 switch(UO->getOpcode()) {
2000 case UnaryOperator::Deref: {
2001 // *(X + 1) refers to X if X is not a pointer.
2002 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2003 if (!VD || VD->getType()->isPointerType())
2004 return 0;
2005 return VD;
2006 }
2007 case UnaryOperator::Real:
2008 case UnaryOperator::Imag:
2009 case UnaryOperator::Extension:
2010 return getPrimaryDecl(UO->getSubExpr());
2011 default:
2012 return 0;
2013 }
2014 }
2015 case Stmt::BinaryOperatorClass: {
2016 BinaryOperator *BO = cast<BinaryOperator>(E);
2017
2018 // Handle cases involving pointer arithmetic. The result of an
2019 // Assign or AddAssign is not an lvalue so they can be ignored.
2020
2021 // (x + n) or (n + x) => x
2022 if (BO->getOpcode() == BinaryOperator::Add) {
2023 if (BO->getLHS()->getType()->isPointerType()) {
2024 return getPrimaryDecl(BO->getLHS());
2025 } else if (BO->getRHS()->getType()->isPointerType()) {
2026 return getPrimaryDecl(BO->getRHS());
2027 }
2028 }
2029
2030 return 0;
2031 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002033 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002034 case Stmt::ImplicitCastExprClass:
2035 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002036 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 default:
2038 return 0;
2039 }
2040}
2041
2042/// CheckAddressOfOperand - The operand of & must be either a function
2043/// designator or an lvalue designating an object. If it is an lvalue, the
2044/// object cannot be declared with storage class register or be a bit field.
2045/// Note: The usual conversions are *not* applied to the operand of the &
2046/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2047QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002048 if (getLangOptions().C99) {
2049 // Implement C99-only parts of addressof rules.
2050 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2051 if (uOp->getOpcode() == UnaryOperator::Deref)
2052 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2053 // (assuming the deref expression is valid).
2054 return uOp->getSubExpr()->getType();
2055 }
2056 // Technically, there should be a check for array subscript
2057 // expressions here, but the result of one is always an lvalue anyway.
2058 }
Anders Carlsson369dee42008-02-01 07:15:58 +00002059 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002060 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002061
2062 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002063 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2064 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2066 op->getSourceRange());
2067 return QualType();
2068 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002069 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2070 if (MemExpr->getMemberDecl()->isBitField()) {
2071 Diag(OpLoc, diag::err_typecheck_address_of,
2072 std::string("bit-field"), op->getSourceRange());
2073 return QualType();
2074 }
2075 // Check for Apple extension for accessing vector components.
2076 } else if (isa<ArraySubscriptExpr>(op) &&
2077 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2078 Diag(OpLoc, diag::err_typecheck_address_of,
2079 std::string("vector"), op->getSourceRange());
2080 return QualType();
2081 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 // We have an lvalue with a decl. Make sure the decl is not declared
2083 // with the register storage-class specifier.
2084 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2085 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002086 Diag(OpLoc, diag::err_typecheck_address_of,
2087 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 return QualType();
2089 }
2090 } else
2091 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002093
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 // If the operand has type "type", the result has type "pointer to type".
2095 return Context.getPointerType(op->getType());
2096}
2097
2098QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002099 UsualUnaryConversions(op);
2100 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002101
Chris Lattnerbefee482007-07-31 16:53:04 +00002102 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002103 // Note that per both C89 and C99, this is always legal, even
2104 // if ptype is an incomplete type or void.
2105 // It would be possible to warn about dereferencing a
2106 // void pointer, but it's completely well-defined,
2107 // and such a warning is unlikely to catch any mistakes.
2108 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 }
2110 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2111 qType.getAsString(), op->getSourceRange());
2112 return QualType();
2113}
2114
2115static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2116 tok::TokenKind Kind) {
2117 BinaryOperator::Opcode Opc;
2118 switch (Kind) {
2119 default: assert(0 && "Unknown binop!");
2120 case tok::star: Opc = BinaryOperator::Mul; break;
2121 case tok::slash: Opc = BinaryOperator::Div; break;
2122 case tok::percent: Opc = BinaryOperator::Rem; break;
2123 case tok::plus: Opc = BinaryOperator::Add; break;
2124 case tok::minus: Opc = BinaryOperator::Sub; break;
2125 case tok::lessless: Opc = BinaryOperator::Shl; break;
2126 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2127 case tok::lessequal: Opc = BinaryOperator::LE; break;
2128 case tok::less: Opc = BinaryOperator::LT; break;
2129 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2130 case tok::greater: Opc = BinaryOperator::GT; break;
2131 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2132 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2133 case tok::amp: Opc = BinaryOperator::And; break;
2134 case tok::caret: Opc = BinaryOperator::Xor; break;
2135 case tok::pipe: Opc = BinaryOperator::Or; break;
2136 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2137 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2138 case tok::equal: Opc = BinaryOperator::Assign; break;
2139 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2140 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2141 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2142 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2143 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2144 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2145 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2146 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2147 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2148 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2149 case tok::comma: Opc = BinaryOperator::Comma; break;
2150 }
2151 return Opc;
2152}
2153
2154static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2155 tok::TokenKind Kind) {
2156 UnaryOperator::Opcode Opc;
2157 switch (Kind) {
2158 default: assert(0 && "Unknown unary op!");
2159 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2160 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2161 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2162 case tok::star: Opc = UnaryOperator::Deref; break;
2163 case tok::plus: Opc = UnaryOperator::Plus; break;
2164 case tok::minus: Opc = UnaryOperator::Minus; break;
2165 case tok::tilde: Opc = UnaryOperator::Not; break;
2166 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2167 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2168 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2169 case tok::kw___real: Opc = UnaryOperator::Real; break;
2170 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2171 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2172 }
2173 return Opc;
2174}
2175
2176// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002177Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 ExprTy *LHS, ExprTy *RHS) {
2179 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2180 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2181
Steve Narofff69936d2007-09-16 03:34:24 +00002182 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2183 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002184
2185 QualType ResultTy; // Result type of the binary operator.
2186 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2187
2188 switch (Opc) {
2189 default:
2190 assert(0 && "Unknown binary expr!");
2191 case BinaryOperator::Assign:
2192 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2193 break;
2194 case BinaryOperator::Mul:
2195 case BinaryOperator::Div:
2196 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2197 break;
2198 case BinaryOperator::Rem:
2199 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2200 break;
2201 case BinaryOperator::Add:
2202 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2203 break;
2204 case BinaryOperator::Sub:
2205 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2206 break;
2207 case BinaryOperator::Shl:
2208 case BinaryOperator::Shr:
2209 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2210 break;
2211 case BinaryOperator::LE:
2212 case BinaryOperator::LT:
2213 case BinaryOperator::GE:
2214 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002215 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 break;
2217 case BinaryOperator::EQ:
2218 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002219 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 break;
2221 case BinaryOperator::And:
2222 case BinaryOperator::Xor:
2223 case BinaryOperator::Or:
2224 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2225 break;
2226 case BinaryOperator::LAnd:
2227 case BinaryOperator::LOr:
2228 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2229 break;
2230 case BinaryOperator::MulAssign:
2231 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002232 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 if (!CompTy.isNull())
2234 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2235 break;
2236 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002237 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 if (!CompTy.isNull())
2239 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2240 break;
2241 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002242 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 if (!CompTy.isNull())
2244 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2245 break;
2246 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002247 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 if (!CompTy.isNull())
2249 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2250 break;
2251 case BinaryOperator::ShlAssign:
2252 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002253 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 if (!CompTy.isNull())
2255 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2256 break;
2257 case BinaryOperator::AndAssign:
2258 case BinaryOperator::XorAssign:
2259 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002260 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 if (!CompTy.isNull())
2262 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2263 break;
2264 case BinaryOperator::Comma:
2265 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2266 break;
2267 }
2268 if (ResultTy.isNull())
2269 return true;
2270 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002271 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002273 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002274}
2275
2276// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002277Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 ExprTy *input) {
2279 Expr *Input = (Expr*)input;
2280 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2281 QualType resultType;
2282 switch (Opc) {
2283 default:
2284 assert(0 && "Unimplemented unary expr!");
2285 case UnaryOperator::PreInc:
2286 case UnaryOperator::PreDec:
2287 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2288 break;
2289 case UnaryOperator::AddrOf:
2290 resultType = CheckAddressOfOperand(Input, OpLoc);
2291 break;
2292 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002293 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 resultType = CheckIndirectionOperand(Input, OpLoc);
2295 break;
2296 case UnaryOperator::Plus:
2297 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002298 UsualUnaryConversions(Input);
2299 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2301 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2302 resultType.getAsString());
2303 break;
2304 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002305 UsualUnaryConversions(Input);
2306 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002307 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2308 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2309 // C99 does not support '~' for complex conjugation.
2310 Diag(OpLoc, diag::ext_integer_complement_complex,
2311 resultType.getAsString(), Input->getSourceRange());
2312 else if (!resultType->isIntegerType())
2313 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2314 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 break;
2316 case UnaryOperator::LNot: // logical negation
2317 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002318 DefaultFunctionArrayConversion(Input);
2319 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2321 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2322 resultType.getAsString());
2323 // LNot always has type int. C99 6.5.3.3p5.
2324 resultType = Context.IntTy;
2325 break;
2326 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002327 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2328 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002329 break;
2330 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002331 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2332 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002334 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002335 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002336 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002337 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 resultType = Input->getType();
2340 break;
2341 }
2342 if (resultType.isNull())
2343 return true;
2344 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2345}
2346
Steve Naroff1b273c42007-09-16 14:56:35 +00002347/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2348Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 SourceLocation LabLoc,
2350 IdentifierInfo *LabelII) {
2351 // Look up the record for this label identifier.
2352 LabelStmt *&LabelDecl = LabelMap[LabelII];
2353
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002354 // If we haven't seen this label yet, create a forward reference. It
2355 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 if (LabelDecl == 0)
2357 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2358
2359 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002360 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2361 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002362}
2363
Steve Naroff1b273c42007-09-16 14:56:35 +00002364Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002365 SourceLocation RPLoc) { // "({..})"
2366 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2367 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2368 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2369
2370 // FIXME: there are a variety of strange constraints to enforce here, for
2371 // example, it is not possible to goto into a stmt expression apparently.
2372 // More semantic analysis is needed.
2373
2374 // FIXME: the last statement in the compount stmt has its value used. We
2375 // should not warn about it being unused.
2376
2377 // If there are sub stmts in the compound stmt, take the type of the last one
2378 // as the type of the stmtexpr.
2379 QualType Ty = Context.VoidTy;
2380
Chris Lattner611b2ec2008-07-26 19:51:01 +00002381 if (!Compound->body_empty()) {
2382 Stmt *LastStmt = Compound->body_back();
2383 // If LastStmt is a label, skip down through into the body.
2384 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2385 LastStmt = Label->getSubStmt();
2386
2387 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002388 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002389 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002390
2391 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2392}
Steve Naroffd34e9152007-08-01 22:05:33 +00002393
Steve Naroff1b273c42007-09-16 14:56:35 +00002394Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002395 SourceLocation TypeLoc,
2396 TypeTy *argty,
2397 OffsetOfComponent *CompPtr,
2398 unsigned NumComponents,
2399 SourceLocation RPLoc) {
2400 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2401 assert(!ArgTy.isNull() && "Missing type argument!");
2402
2403 // We must have at least one component that refers to the type, and the first
2404 // one is known to be a field designator. Verify that the ArgTy represents
2405 // a struct/union/class.
2406 if (!ArgTy->isRecordType())
2407 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2408
2409 // Otherwise, create a compound literal expression as the base, and
2410 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002411 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002412
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002413 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2414 // GCC extension, diagnose them.
2415 if (NumComponents != 1)
2416 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2417 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2418
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002419 for (unsigned i = 0; i != NumComponents; ++i) {
2420 const OffsetOfComponent &OC = CompPtr[i];
2421 if (OC.isBrackets) {
2422 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002423 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002424 if (!AT) {
2425 delete Res;
2426 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2427 Res->getType().getAsString());
2428 }
2429
Chris Lattner704fe352007-08-30 17:59:59 +00002430 // FIXME: C++: Verify that operator[] isn't overloaded.
2431
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002432 // C99 6.5.2.1p1
2433 Expr *Idx = static_cast<Expr*>(OC.U.E);
2434 if (!Idx->getType()->isIntegerType())
2435 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2436 Idx->getSourceRange());
2437
2438 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2439 continue;
2440 }
2441
2442 const RecordType *RC = Res->getType()->getAsRecordType();
2443 if (!RC) {
2444 delete Res;
2445 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2446 Res->getType().getAsString());
2447 }
2448
2449 // Get the decl corresponding to this.
2450 RecordDecl *RD = RC->getDecl();
2451 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2452 if (!MemberDecl)
2453 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2454 OC.U.IdentInfo->getName(),
2455 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002456
2457 // FIXME: C++: Verify that MemberDecl isn't a static field.
2458 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002459 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2460 // matter here.
2461 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002462 }
2463
2464 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2465 BuiltinLoc);
2466}
2467
2468
Steve Naroff1b273c42007-09-16 14:56:35 +00002469Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002470 TypeTy *arg1, TypeTy *arg2,
2471 SourceLocation RPLoc) {
2472 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2473 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2474
2475 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2476
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002477 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002478}
2479
Steve Naroff1b273c42007-09-16 14:56:35 +00002480Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002481 ExprTy *expr1, ExprTy *expr2,
2482 SourceLocation RPLoc) {
2483 Expr *CondExpr = static_cast<Expr*>(cond);
2484 Expr *LHSExpr = static_cast<Expr*>(expr1);
2485 Expr *RHSExpr = static_cast<Expr*>(expr2);
2486
2487 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2488
2489 // The conditional expression is required to be a constant expression.
2490 llvm::APSInt condEval(32);
2491 SourceLocation ExpLoc;
2492 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2493 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2494 CondExpr->getSourceRange());
2495
2496 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2497 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2498 RHSExpr->getType();
2499 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2500}
2501
Nate Begeman67295d02008-01-30 20:50:20 +00002502/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00002503/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00002504/// The number of arguments has already been validated to match the number of
2505/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002506static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2507 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00002508 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00002509 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002510 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2511 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00002512
2513 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00002514 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00002515 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002516 return true;
2517}
2518
2519Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2520 SourceLocation *CommaLocs,
2521 SourceLocation BuiltinLoc,
2522 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002523 // __builtin_overload requires at least 2 arguments
2524 if (NumArgs < 2)
2525 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2526 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00002527
Nate Begemane2ce1d92008-01-17 17:46:27 +00002528 // The first argument is required to be a constant expression. It tells us
2529 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002530 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00002531 Expr *NParamsExpr = Args[0];
2532 llvm::APSInt constEval(32);
2533 SourceLocation ExpLoc;
2534 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2535 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2536 NParamsExpr->getSourceRange());
2537
2538 // Verify that the number of parameters is > 0
2539 unsigned NumParams = constEval.getZExtValue();
2540 if (NumParams == 0)
2541 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2542 NParamsExpr->getSourceRange());
2543 // Verify that we have at least 1 + NumParams arguments to the builtin.
2544 if ((NumParams + 1) > NumArgs)
2545 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2546 SourceRange(BuiltinLoc, RParenLoc));
2547
2548 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00002549 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002550 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002551 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2552 // UsualUnaryConversions will convert the function DeclRefExpr into a
2553 // pointer to function.
2554 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00002555 const FunctionTypeProto *FnType = 0;
2556 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2557 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00002558
2559 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2560 // parameters, and the number of parameters must match the value passed to
2561 // the builtin.
2562 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00002563 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2564 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00002565
2566 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00002567 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00002568 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002569 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002570 if (OE)
2571 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2572 OE->getFn()->getSourceRange());
2573 // Remember our match, and continue processing the remaining arguments
2574 // to catch any errors.
2575 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2576 BuiltinLoc, RParenLoc);
2577 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002578 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00002579 // Return the newly created OverloadExpr node, if we succeded in matching
2580 // exactly one of the candidate functions.
2581 if (OE)
2582 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002583
2584 // If we didn't find a matching function Expr in the __builtin_overload list
2585 // the return an error.
2586 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00002587 for (unsigned i = 0; i != NumParams; ++i) {
2588 if (i != 0) typeNames += ", ";
2589 typeNames += Args[i+1]->getType().getAsString();
2590 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002591
2592 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2593 SourceRange(BuiltinLoc, RParenLoc));
2594}
2595
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002596Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2597 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002598 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002599 Expr *E = static_cast<Expr*>(expr);
2600 QualType T = QualType::getFromOpaquePtr(type);
2601
2602 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00002603
2604 // Get the va_list type
2605 QualType VaListType = Context.getBuiltinVaListType();
2606 // Deal with implicit array decay; for example, on x86-64,
2607 // va_list is an array, but it's supposed to decay to
2608 // a pointer for va_arg.
2609 if (VaListType->isArrayType())
2610 VaListType = Context.getArrayDecayedType(VaListType);
2611
2612 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002613 return Diag(E->getLocStart(),
2614 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2615 E->getType().getAsString(),
2616 E->getSourceRange());
2617
2618 // FIXME: Warn if a non-POD type is passed in.
2619
2620 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2621}
2622
Chris Lattner5cf216b2008-01-04 18:04:52 +00002623bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2624 SourceLocation Loc,
2625 QualType DstType, QualType SrcType,
2626 Expr *SrcExpr, const char *Flavor) {
2627 // Decode the result (notice that AST's are still created for extensions).
2628 bool isInvalid = false;
2629 unsigned DiagKind;
2630 switch (ConvTy) {
2631 default: assert(0 && "Unknown conversion type");
2632 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002633 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00002634 DiagKind = diag::ext_typecheck_convert_pointer_int;
2635 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002636 case IntToPointer:
2637 DiagKind = diag::ext_typecheck_convert_int_pointer;
2638 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002639 case IncompatiblePointer:
2640 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2641 break;
2642 case FunctionVoidPointer:
2643 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2644 break;
2645 case CompatiblePointerDiscardsQualifiers:
2646 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2647 break;
2648 case Incompatible:
2649 DiagKind = diag::err_typecheck_convert_incompatible;
2650 isInvalid = true;
2651 break;
2652 }
2653
2654 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2655 SrcExpr->getSourceRange());
2656 return isInvalid;
2657}