blob: cdba6ec6ea6c91c76635a70ba964c816e791a263 [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"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Chris Lattnere7a2e912008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattnere7a2e912008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39 Ty = E->getType();
40 }
41 if (Ty->isFunctionType())
42 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000043 else if (Ty->isArrayType()) {
44 // In C90 mode, arrays only promote to pointers if the array expression is
45 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46 // type 'array of type' is converted to an expression that has type 'pointer
47 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
48 // that has type 'array of type' ...". The relevant change is "an lvalue"
49 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000050 //
51 // C++ 4.2p1:
52 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
53 // T" can be converted to an rvalue of type "pointer to T".
54 //
55 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
56 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000057 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000059}
60
61/// UsualUnaryConversions - Performs various conversions that are common to most
62/// operators (C99 6.3). The conversions of array and function types are
63/// sometimes surpressed. For example, the array->pointer conversion doesn't
64/// apply if the array is an argument to the sizeof or address (&) operators.
65/// In these instances, this routine should *not* be called.
66Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
67 QualType Ty = Expr->getType();
68 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
69
70 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
71 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
72 Ty = Expr->getType();
73 }
74 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
75 ImpCastExprToType(Expr, Context.IntTy);
76 else
77 DefaultFunctionArrayConversion(Expr);
78
79 return Expr;
80}
81
Chris Lattner05faf172008-07-25 22:25:12 +000082/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
83/// do not have a prototype. Arguments that have type float are promoted to
84/// double. All other argument types are converted by UsualUnaryConversions().
85void Sema::DefaultArgumentPromotion(Expr *&Expr) {
86 QualType Ty = Expr->getType();
87 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
88
89 // If this is a 'float' (CVR qualified or typedef) promote to double.
90 if (const BuiltinType *BT = Ty->getAsBuiltinType())
91 if (BT->getKind() == BuiltinType::Float)
92 return ImpCastExprToType(Expr, Context.DoubleTy);
93
94 UsualUnaryConversions(Expr);
95}
96
Chris Lattnere7a2e912008-07-25 21:10:04 +000097/// UsualArithmeticConversions - Performs various conversions that are common to
98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
99/// routine returns the first non-arithmetic type found. The client is
100/// responsible for emitting appropriate error diagnostics.
101/// FIXME: verify the conversion rules for "complex int" are consistent with
102/// GCC.
103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
104 bool isCompAssign) {
105 if (!isCompAssign) {
106 UsualUnaryConversions(lhsExpr);
107 UsualUnaryConversions(rhsExpr);
108 }
109 // For conversion purposes, we ignore any qualifiers.
110 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000111 QualType lhs =
112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113 QualType rhs =
114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000115
116 // If both types are identical, no conversion is needed.
117 if (lhs == rhs)
118 return lhs;
119
120 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
121 // The caller can deal with this (e.g. pointer + int).
122 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
123 return lhs;
124
125 // At this point, we have two different arithmetic types.
126
127 // Handle complex types first (C99 6.3.1.8p1).
128 if (lhs->isComplexType() || rhs->isComplexType()) {
129 // if we have an integer operand, the result is the complex type.
130 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
131 // convert the rhs to the lhs complex type.
132 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
133 return lhs;
134 }
135 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
136 // convert the lhs to the rhs complex type.
137 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
138 return rhs;
139 }
140 // This handles complex/complex, complex/float, or float/complex.
141 // When both operands are complex, the shorter operand is converted to the
142 // type of the longer, and that is the type of the result. This corresponds
143 // to what is done when combining two real floating-point operands.
144 // The fun begins when size promotion occur across type domains.
145 // From H&S 6.3.4: When one operand is complex and the other is a real
146 // floating-point type, the less precise type is converted, within it's
147 // real or complex domain, to the precision of the other type. For example,
148 // when combining a "long double" with a "double _Complex", the
149 // "double _Complex" is promoted to "long double _Complex".
150 int result = Context.getFloatingTypeOrder(lhs, rhs);
151
152 if (result > 0) { // The left side is bigger, convert rhs.
153 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
154 if (!isCompAssign)
155 ImpCastExprToType(rhsExpr, rhs);
156 } else if (result < 0) { // The right side is bigger, convert lhs.
157 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
158 if (!isCompAssign)
159 ImpCastExprToType(lhsExpr, lhs);
160 }
161 // At this point, lhs and rhs have the same rank/size. Now, make sure the
162 // domains match. This is a requirement for our implementation, C99
163 // does not require this promotion.
164 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
165 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
166 if (!isCompAssign)
167 ImpCastExprToType(lhsExpr, rhs);
168 return rhs;
169 } else { // handle "_Complex double, double".
170 if (!isCompAssign)
171 ImpCastExprToType(rhsExpr, lhs);
172 return lhs;
173 }
174 }
175 return lhs; // The domain/size match exactly.
176 }
177 // Now handle "real" floating types (i.e. float, double, long double).
178 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
179 // if we have an integer operand, the result is the real floating type.
180 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
181 // convert rhs to the lhs floating point type.
182 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
183 return lhs;
184 }
185 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
186 // convert lhs to the rhs floating point type.
187 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
188 return rhs;
189 }
190 // We have two real floating types, float/complex combos were handled above.
191 // Convert the smaller operand to the bigger result.
192 int result = Context.getFloatingTypeOrder(lhs, rhs);
193
194 if (result > 0) { // convert the rhs
195 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
196 return lhs;
197 }
198 if (result < 0) { // convert the lhs
199 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
200 return rhs;
201 }
202 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
203 }
204 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
205 // Handle GCC complex int extension.
206 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
207 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
208
209 if (lhsComplexInt && rhsComplexInt) {
210 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
211 rhsComplexInt->getElementType()) >= 0) {
212 // convert the rhs
213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214 return lhs;
215 }
216 if (!isCompAssign)
217 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
218 return rhs;
219 } else if (lhsComplexInt && rhs->isIntegerType()) {
220 // convert the rhs to the lhs complex type.
221 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
222 return lhs;
223 } else if (rhsComplexInt && lhs->isIntegerType()) {
224 // convert the lhs to the rhs complex type.
225 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
226 return rhs;
227 }
228 }
229 // Finally, we have two differing integer types.
230 // The rules for this case are in C99 6.3.1.8
231 int compare = Context.getIntegerTypeOrder(lhs, rhs);
232 bool lhsSigned = lhs->isSignedIntegerType(),
233 rhsSigned = rhs->isSignedIntegerType();
234 QualType destType;
235 if (lhsSigned == rhsSigned) {
236 // Same signedness; use the higher-ranked type
237 destType = compare >= 0 ? lhs : rhs;
238 } else if (compare != (lhsSigned ? 1 : -1)) {
239 // The unsigned type has greater than or equal rank to the
240 // signed type, so use the unsigned type
241 destType = lhsSigned ? rhs : lhs;
242 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
243 // The two types are different widths; if we are here, that
244 // means the signed type is larger than the unsigned type, so
245 // use the signed type.
246 destType = lhsSigned ? lhs : rhs;
247 } else {
248 // The signed type is higher-ranked than the unsigned type,
249 // but isn't actually any bigger (like unsigned int and long
250 // on most 32-bit systems). Use the unsigned type corresponding
251 // to the signed type.
252 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
253 }
254 if (!isCompAssign) {
255 ImpCastExprToType(lhsExpr, destType);
256 ImpCastExprToType(rhsExpr, destType);
257 }
258 return destType;
259}
260
261//===----------------------------------------------------------------------===//
262// Semantic Analysis for various Expression Types
263//===----------------------------------------------------------------------===//
264
265
Steve Narofff69936d2007-09-16 03:34:24 +0000266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000267/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
269/// multiple tokens. However, the common case is that StringToks points to one
270/// string.
271///
272Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 assert(NumStringToks && "Must have at least one string!");
275
276 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
277 if (Literal.hadError)
278 return ExprResult(true);
279
280 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
281 for (unsigned i = 0; i != NumStringToks; ++i)
282 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000283
284 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000285 if (Literal.Pascal && Literal.GetStringLength() > 256)
286 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
287 SourceRange(StringToks[0].getLocation(),
288 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000289
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000290 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000291 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000293
294 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
295 if (getLangOptions().CPlusPlus)
296 StrTy.addConst();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000297
298 // Get an array type for the string, according to C99 6.4.5. This includes
299 // the nul terminator character as well as the string length for pascal
300 // strings.
301 StrTy = Context.getConstantArrayType(StrTy,
302 llvm::APInt(32, Literal.GetStringLength()+1),
303 ArrayType::Normal, 0);
304
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000307 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000308 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 StringToks[NumStringToks-1].getLocation());
310}
311
Steve Naroffdd972f22008-09-05 22:11:13 +0000312/// DeclDefinedWithinScope - Return true if the specified decl is defined at or
313/// within the 'Within' scope. The current Scope is CurScope.
314///
Steve Naroffaa5caa12008-09-28 21:07:52 +0000315/// FIXME: This method is extremely inefficient (linear scan), this should not
316/// be used in common cases. Replace with the more modern DeclContext. We need
317/// to make sure both assignments below produce an error.
318///
319/// int main(int argc) {
320/// int xx;
321/// ^(int X) {
322/// xx = 4; // error (variable is not assignable)
323/// argc = 3; // no error.
324/// };
325/// }
Steve Naroffdd972f22008-09-05 22:11:13 +0000326///
327static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within,
328 Scope *CurScope) {
329 while (1) {
330 assert(CurScope && "CurScope not nested within 'Within'?");
331
332 // Check this scope for the decl.
333 if (CurScope->isDeclScope(D)) return true;
334
335 if (CurScope == Within) return false;
336 CurScope = CurScope->getParent();
337 }
338}
Reid Spencer5f016e22007-07-11 17:01:13 +0000339
Steve Naroff08d92e42007-09-15 18:49:24 +0000340/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000341/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000342/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000343Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 IdentifierInfo &II,
345 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000346 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000347 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000348
349 // If this reference is in an Objective-C method, then ivar lookup happens as
350 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000351 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000352 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000353 // There are two cases to handle here. 1) scoped lookup could have failed,
354 // in which case we should look for an ivar. 2) scoped lookup could have
355 // found a decl, but that decl is outside the current method (i.e. a global
356 // variable). In these two cases, we do a lookup for an ivar with this
357 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000358 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000359 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000360 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000361 // FIXME: This should use a new expr for a direct reference, don't turn
362 // this into Self->ivar, just return a BareIVarExpr or something.
363 IdentifierInfo &II = Context.Idents.get("self");
364 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
365 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
366 static_cast<Expr*>(SelfExpr.Val), true, true);
367 }
368 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000369 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000370 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000371 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000372 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000373 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000374 }
Chris Lattner8a934232008-03-31 00:36:02 +0000375 }
Steve Naroff1f3b0d52008-09-10 18:33:00 +0000376 // If we are parsing a block, check the block parameter list.
377 if (CurBlock) {
Steve Naroff538afe32008-09-28 00:13:36 +0000378 BlockSemaInfo *BLK = CurBlock;
379 do {
380 for (unsigned i = 0, e = BLK->Params.size(); i != e && D == 0; ++i)
381 if (BLK->Params[i]->getIdentifier() == &II)
382 D = BLK->Params[i];
383 if (D)
384 break; // Found!
385 } while ((BLK = BLK->PrevBlockInfo)); // Look through any enclosing blocks.
Steve Naroff1f3b0d52008-09-10 18:33:00 +0000386 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 if (D == 0) {
388 // Otherwise, this could be an implicitly declared function reference (legal
389 // in C90, extension in C99).
390 if (HasTrailingLParen &&
Chris Lattner8a934232008-03-31 00:36:02 +0000391 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 D = ImplicitlyDefineFunction(Loc, II, S);
393 else {
394 // If this name wasn't predeclared and if this is not a function call,
395 // diagnose the problem.
396 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
397 }
398 }
Chris Lattner8a934232008-03-31 00:36:02 +0000399
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000400 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
401 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
402 if (MD->isStatic())
403 // "invalid use of member 'x' in static member function"
404 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
405 FD->getName());
406 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
407 // "invalid use of nonstatic data member 'x'"
408 return Diag(Loc, diag::err_invalid_non_static_member_use,
409 FD->getName());
410
411 if (FD->isInvalidDecl())
412 return true;
413
414 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
415 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
416 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
417 true, FD, Loc, FD->getType());
418 }
419
420 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
421 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 if (isa<TypedefDecl>(D))
423 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000424 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000425 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000426 if (isa<NamespaceDecl>(D))
427 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000428
Steve Naroffdd972f22008-09-05 22:11:13 +0000429 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
430 ValueDecl *VD = cast<ValueDecl>(D);
431
432 // check if referencing an identifier with __attribute__((deprecated)).
433 if (VD->getAttr<DeprecatedAttr>())
434 Diag(Loc, diag::warn_deprecated, VD->getName());
435
436 // Only create DeclRefExpr's for valid Decl's.
437 if (VD->isInvalidDecl())
438 return true;
439
440 // If this reference is not in a block or if the referenced variable is
441 // within the block, create a normal DeclRefExpr.
442 //
443 // FIXME: This will create BlockDeclRefExprs for global variables,
Chris Lattnerf7037b12008-09-28 05:30:26 +0000444 // function references, etc which is suboptimal :) and breaks
Steve Naroffdd972f22008-09-05 22:11:13 +0000445 // things like "integer constant expression" tests.
446 //
Chris Lattnerf7037b12008-09-28 05:30:26 +0000447 if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S) ||
Steve Naroffae530cf2008-09-28 14:02:55 +0000448 isa<EnumConstantDecl>(VD) || isa<ParmVarDecl>(VD))
Steve Naroffdd972f22008-09-05 22:11:13 +0000449 return new DeclRefExpr(VD, VD->getType(), Loc);
450
451 // If we are in a block and the variable is outside the current block,
452 // bind the variable reference with a BlockDeclRefExpr.
453
Steve Naroff33ae3af2008-09-22 15:31:56 +0000454 // The BlocksAttr indicates the variable is bound by-reference.
455 if (VD->getAttr<BlocksAttr>())
456 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
Steve Naroffdd972f22008-09-05 22:11:13 +0000457
Steve Naroff33ae3af2008-09-22 15:31:56 +0000458 // Variable will be bound by-copy, make it const within the closure.
459 VD->getType().addConst();
Steve Naroffdd972f22008-09-05 22:11:13 +0000460 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461}
462
Chris Lattnerd9f69102008-08-10 01:53:14 +0000463Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000464 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000465 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000468 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000469 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
470 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
471 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000473
474 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000475 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000476 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000477
Chris Lattnerfa28b302008-01-12 08:14:25 +0000478 // Pre-defined identifiers are of type char[x], where x is the length of the
479 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000480 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000481 if (getCurFunctionDecl())
482 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000483 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000484 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000485
Chris Lattner8f978d52008-01-12 19:32:28 +0000486 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000487 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000488 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000489 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490}
491
Steve Narofff69936d2007-09-16 03:34:24 +0000492Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 llvm::SmallString<16> CharBuffer;
494 CharBuffer.resize(Tok.getLength());
495 const char *ThisTokBegin = &CharBuffer[0];
496 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
497
498 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
499 Tok.getLocation(), PP);
500 if (Literal.hadError())
501 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000502
503 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
504
Chris Lattnerc250aae2008-06-07 22:35:38 +0000505 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
506 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000507}
508
Steve Narofff69936d2007-09-16 03:34:24 +0000509Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // fast path for a single digit (which is quite common). A single digit
511 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
512 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000513 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000514
Chris Lattner98be4942008-03-05 18:54:05 +0000515 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000516 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 Context.IntTy,
518 Tok.getLocation()));
519 }
520 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000521 // Add padding so that NumericLiteralParser can overread by one character.
522 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 const char *ThisTokBegin = &IntegerBuffer[0];
524
525 // Get the spelling of the token, which eliminates trigraphs, etc.
526 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000527
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
529 Tok.getLocation(), PP);
530 if (Literal.hadError)
531 return ExprResult(true);
532
Chris Lattner5d661452007-08-26 03:42:43 +0000533 Expr *Res;
534
535 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000536 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000537 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000538 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000539 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000540 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000541 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000542 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000543
544 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
545
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000546 // isExact will be set by GetFloatValue().
547 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000548 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000549 Ty, Tok.getLocation());
550
Chris Lattner5d661452007-08-26 03:42:43 +0000551 } else if (!Literal.isIntegerLiteral()) {
552 return ExprResult(true);
553 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000554 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000555
Neil Boothb9449512007-08-29 22:00:19 +0000556 // long long is a C99 feature.
557 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000558 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000559 Diag(Tok.getLocation(), diag::ext_longlong);
560
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000562 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
564 if (Literal.GetIntegerValue(ResultVal)) {
565 // If this value didn't fit into uintmax_t, warn and force to ull.
566 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000567 Ty = Context.UnsignedLongLongTy;
568 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000569 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 } else {
571 // If this value fits into a ULL, try to figure out what else it fits into
572 // according to the rules of C99 6.4.4.1p5.
573
574 // Octal, Hexadecimal, and integers with a U suffix are allowed to
575 // be an unsigned int.
576 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
577
578 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000579 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000580 if (!Literal.isLong && !Literal.isLongLong) {
581 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000582 unsigned IntSize = Context.Target.getIntWidth();
583
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 // Does it fit in a unsigned int?
585 if (ResultVal.isIntN(IntSize)) {
586 // Does it fit in a signed int?
587 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000588 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000590 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000591 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 }
594
595 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000596 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000597 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000598
599 // Does it fit in a unsigned long?
600 if (ResultVal.isIntN(LongSize)) {
601 // Does it fit in a signed long?
602 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000603 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000605 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000606 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 }
609
610 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000611 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000612 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000613
614 // Does it fit in a unsigned long long?
615 if (ResultVal.isIntN(LongLongSize)) {
616 // Does it fit in a signed long long?
617 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000618 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000620 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000621 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 }
623 }
624
625 // If we still couldn't decide a type, we probably have something that
626 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000627 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000629 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000630 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000632
633 if (ResultVal.getBitWidth() != Width)
634 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 }
636
Chris Lattnerf0467b32008-04-02 04:24:33 +0000637 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 }
Chris Lattner5d661452007-08-26 03:42:43 +0000639
640 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
641 if (Literal.isImaginary)
642 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
643
644 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000645}
646
Steve Narofff69936d2007-09-16 03:34:24 +0000647Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000649 Expr *E = (Expr *)Val;
650 assert((E != 0) && "ActOnParenExpr() missing expr");
651 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000652}
653
654/// The UsualUnaryConversions() function is *not* called by this routine.
655/// See C99 6.3.2.1p[2-4] for more details.
656QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000657 SourceLocation OpLoc,
658 const SourceRange &ExprRange,
659 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 // C99 6.5.3.4p1:
661 if (isa<FunctionType>(exprType) && isSizeof)
662 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000663 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000665 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
666 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 else if (exprType->isIncompleteType()) {
668 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
669 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000670 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 return QualType(); // error
672 }
673 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
674 return Context.getSizeType();
675}
676
677Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000678ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 SourceLocation LPLoc, TypeTy *Ty,
680 SourceLocation RPLoc) {
681 // If error parsing type, ignore.
682 if (Ty == 0) return true;
683
684 // Verify that this is a valid expression.
685 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
686
Chris Lattnerbb280a42008-07-25 21:45:37 +0000687 QualType resultType =
688 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000689
690 if (resultType.isNull())
691 return true;
692 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
693}
694
Chris Lattner5d794252007-08-24 21:41:10 +0000695QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000696 DefaultFunctionArrayConversion(V);
697
Chris Lattnercc26ed72007-08-26 05:39:26 +0000698 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000699 if (const ComplexType *CT = V->getType()->getAsComplexType())
700 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000701
702 // Otherwise they pass through real integer and floating point types here.
703 if (V->getType()->isArithmeticType())
704 return V->getType();
705
706 // Reject anything else.
707 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
708 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000709}
710
711
Reid Spencer5f016e22007-07-11 17:01:13 +0000712
Steve Narofff69936d2007-09-16 03:34:24 +0000713Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 tok::TokenKind Kind,
715 ExprTy *Input) {
716 UnaryOperator::Opcode Opc;
717 switch (Kind) {
718 default: assert(0 && "Unknown unary op!");
719 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
720 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
721 }
722 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
723 if (result.isNull())
724 return true;
725 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
726}
727
728Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000729ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000731 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000732
733 // Perform default conversions.
734 DefaultFunctionArrayConversion(LHSExp);
735 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000736
Chris Lattner12d9ff62007-07-16 00:14:47 +0000737 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000738
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000740 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 // in the subscript position. As a result, we need to derive the array base
742 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000743 Expr *BaseExpr, *IndexExpr;
744 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000745 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000746 BaseExpr = LHSExp;
747 IndexExpr = RHSExp;
748 // FIXME: need to deal with const...
749 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000750 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000751 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000752 BaseExpr = RHSExp;
753 IndexExpr = LHSExp;
754 // FIXME: need to deal with const...
755 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000756 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
757 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000758 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000759
760 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000761 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
762 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000763 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000764 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000765 // FIXME: need to deal with const...
766 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000768 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
769 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 }
771 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000772 if (!IndexExpr->getType()->isIntegerType())
773 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
774 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000775
Chris Lattner12d9ff62007-07-16 00:14:47 +0000776 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
777 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000778 // void (*)(int)) and pointers to incomplete types. Functions are not
779 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000780 if (!ResultType->isObjectType())
781 return Diag(BaseExpr->getLocStart(),
782 diag::err_typecheck_subscript_not_object,
783 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
784
785 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000786}
787
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000788QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000789CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000790 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000791 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000792
793 // This flag determines whether or not the component is to be treated as a
794 // special name, or a regular GLSL-style component access.
795 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000796
797 // The vector accessor can't exceed the number of elements.
798 const char *compStr = CompName.getName();
799 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000800 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000801 baseType.getAsString(), SourceRange(CompLoc));
802 return QualType();
803 }
Nate Begeman8a997642008-05-09 06:41:27 +0000804
805 // Check that we've found one of the special components, or that the component
806 // names must come from the same set.
807 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
808 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
809 SpecialComponent = true;
810 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000811 do
812 compStr++;
813 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
814 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
815 do
816 compStr++;
817 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
818 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
819 do
820 compStr++;
821 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
822 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000823
Nate Begeman8a997642008-05-09 06:41:27 +0000824 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000825 // We didn't get to the end of the string. This means the component names
826 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000827 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000828 std::string(compStr,compStr+1), SourceRange(CompLoc));
829 return QualType();
830 }
831 // Each component accessor can't exceed the vector type.
832 compStr = CompName.getName();
833 while (*compStr) {
834 if (vecType->isAccessorWithinNumElements(*compStr))
835 compStr++;
836 else
837 break;
838 }
Nate Begeman8a997642008-05-09 06:41:27 +0000839 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000840 // We didn't get to the end of the string. This means a component accessor
841 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000842 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000843 baseType.getAsString(), SourceRange(CompLoc));
844 return QualType();
845 }
Nate Begeman8a997642008-05-09 06:41:27 +0000846
847 // If we have a special component name, verify that the current vector length
848 // is an even number, since all special component names return exactly half
849 // the elements.
850 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbarabee2d72008-09-30 17:22:47 +0000851 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
852 baseType.getAsString(), SourceRange(CompLoc));
Nate Begeman8a997642008-05-09 06:41:27 +0000853 return QualType();
854 }
855
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000856 // The component accessor looks fine - now we need to compute the actual type.
857 // The vector type is implied by the component accessor. For example,
858 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000859 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
860 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
861 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000862 if (CompSize == 1)
863 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000864
Nate Begeman213541a2008-04-18 23:10:10 +0000865 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000866 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000867 // diagostics look bad. We want extended vector types to appear built-in.
868 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
869 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
870 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000871 }
872 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000873}
874
Daniel Dunbar2307d312008-09-03 01:05:41 +0000875/// constructSetterName - Return the setter name for the given
876/// identifier, i.e. "set" + Name where the initial character of Name
877/// has been capitalized.
878// FIXME: Merge with same routine in Parser. But where should this
879// live?
880static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
881 const IdentifierInfo *Name) {
882 unsigned N = Name->getLength();
883 char *SelectorName = new char[3 + N];
884 memcpy(SelectorName, "set", 3);
885 memcpy(&SelectorName[3], Name->getName(), N);
886 SelectorName[3] = toupper(SelectorName[3]);
887
888 IdentifierInfo *Setter =
889 &Idents.get(SelectorName, &SelectorName[3 + N]);
890 delete[] SelectorName;
891 return Setter;
892}
893
Reid Spencer5f016e22007-07-11 17:01:13 +0000894Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000895ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 tok::TokenKind OpKind, SourceLocation MemberLoc,
897 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000898 Expr *BaseExpr = static_cast<Expr *>(Base);
899 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000900
901 // Perform default conversions.
902 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000904 QualType BaseType = BaseExpr->getType();
905 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000906
Chris Lattner68a057b2008-07-21 04:36:39 +0000907 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
908 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000910 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000911 BaseType = PT->getPointeeType();
912 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000913 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
914 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000916
Chris Lattner68a057b2008-07-21 04:36:39 +0000917 // Handle field access to simple records. This also handles access to fields
918 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000919 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000920 RecordDecl *RDecl = RTy->getDecl();
921 if (RTy->isIncompleteType())
922 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
923 BaseExpr->getSourceRange());
924 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000925 FieldDecl *MemberDecl = RDecl->getMember(&Member);
926 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000927 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
928 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000929
930 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000931 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000932 QualType MemberType = MemberDecl->getType();
933 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000934 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000935 MemberType = MemberType.getQualifiedType(combinedQualifiers);
936
Chris Lattner68a057b2008-07-21 04:36:39 +0000937 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000938 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000939 }
940
Chris Lattnera38e6b12008-07-21 04:59:05 +0000941 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
942 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000943 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
944 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000945 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000946 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000947 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000948 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000949 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000950 }
951
Chris Lattnera38e6b12008-07-21 04:59:05 +0000952 // Handle Objective-C property access, which is "Obj.property" where Obj is a
953 // pointer to a (potentially qualified) interface type.
954 const PointerType *PTy;
955 const ObjCInterfaceType *IFTy;
956 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
957 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
958 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000959
Daniel Dunbar2307d312008-09-03 01:05:41 +0000960 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000961 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
962 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
963
Daniel Dunbar2307d312008-09-03 01:05:41 +0000964 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000965 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
966 E = IFTy->qual_end(); I != E; ++I)
967 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
968 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000969
970 // If that failed, look for an "implicit" property by seeing if the nullary
971 // selector is implemented.
972
973 // FIXME: The logic for looking up nullary and unary selectors should be
974 // shared with the code in ActOnInstanceMessage.
975
976 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
977 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
978
979 // If this reference is in an @implementation, check for 'private' methods.
980 if (!Getter)
981 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
982 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
983 if (ObjCImplementationDecl *ImpDecl =
984 ObjCImplementations[ClassDecl->getIdentifier()])
985 Getter = ImpDecl->getInstanceMethod(Sel);
986
987 if (Getter) {
988 // If we found a getter then this may be a valid dot-reference, we
989 // need to also look for the matching setter.
990 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
991 &Member);
992 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
993 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
994
995 if (!Setter) {
996 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
997 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
998 if (ObjCImplementationDecl *ImpDecl =
999 ObjCImplementations[ClassDecl->getIdentifier()])
1000 Setter = ImpDecl->getInstanceMethod(SetterSel);
1001 }
1002
1003 // FIXME: There are some issues here. First, we are not
1004 // diagnosing accesses to read-only properties because we do not
1005 // know if this is a getter or setter yet. Second, we are
1006 // checking that the type of the setter matches the type we
1007 // expect.
1008 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1009 MemberLoc, BaseExpr);
1010 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001011 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001012
1013 // Handle 'field access' to vectors, such as 'V.xx'.
1014 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1015 // Component access limited to variables (reject vec4.rg.g).
1016 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1017 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +00001018 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1019 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001020 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1021 if (ret.isNull())
1022 return true;
1023 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1024 }
1025
Chris Lattner2a01b722008-07-21 05:35:34 +00001026 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1027 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001028}
1029
Steve Narofff69936d2007-09-16 03:34:24 +00001030/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001031/// This provides the location of the left/right parens and a list of comma
1032/// locations.
1033Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001034ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001035 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001037 Expr *Fn = static_cast<Expr *>(fn);
1038 Expr **Args = reinterpret_cast<Expr**>(args);
1039 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001040 FunctionDecl *FDecl = NULL;
Chris Lattner04421082008-04-08 04:40:51 +00001041
1042 // Promote the function operand.
1043 UsualUnaryConversions(Fn);
1044
1045 // If we're directly calling a function, get the declaration for
1046 // that function.
1047 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1048 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1049 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1050
Chris Lattner925e60d2007-12-28 05:29:59 +00001051 // Make the call expr early, before semantic checks. This guarantees cleanup
1052 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001053 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001054 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001055 const FunctionType *FuncT;
1056 if (!Fn->getType()->isBlockPointerType()) {
1057 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1058 // have type pointer to function".
1059 const PointerType *PT = Fn->getType()->getAsPointerType();
1060 if (PT == 0)
1061 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1062 Fn->getSourceRange());
1063 FuncT = PT->getPointeeType()->getAsFunctionType();
1064 } else { // This is a block call.
1065 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1066 getAsFunctionType();
1067 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001068 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001069 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1070 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001071
1072 // We know the result type of the call, set it.
1073 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001074
Chris Lattner925e60d2007-12-28 05:29:59 +00001075 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1077 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001078 unsigned NumArgsInProto = Proto->getNumArgs();
1079 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001080
Chris Lattner04421082008-04-08 04:40:51 +00001081 // If too few arguments are available (and we don't have default
1082 // arguments for the remaining parameters), don't make the call.
1083 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001084 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001085 // Use default arguments for missing arguments
1086 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001087 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001088 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001089 return Diag(RParenLoc,
1090 !Fn->getType()->isBlockPointerType()
1091 ? diag::err_typecheck_call_too_few_args
1092 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001093 Fn->getSourceRange());
1094 }
1095
Chris Lattner925e60d2007-12-28 05:29:59 +00001096 // If too many are passed and not variadic, error on the extras and drop
1097 // them.
1098 if (NumArgs > NumArgsInProto) {
1099 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001100 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001101 !Fn->getType()->isBlockPointerType()
1102 ? diag::err_typecheck_call_too_many_args
1103 : diag::err_typecheck_block_too_many_args,
1104 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001105 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001106 Args[NumArgs-1]->getLocEnd()));
1107 // This deletes the extra arguments.
1108 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 }
1110 NumArgsToCheck = NumArgsInProto;
1111 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001112
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001114 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001115 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001116
1117 Expr *Arg;
1118 if (i < NumArgs)
1119 Arg = Args[i];
1120 else
1121 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001122 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001123
Chris Lattner925e60d2007-12-28 05:29:59 +00001124 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001125 AssignConvertType ConvTy =
1126 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001127 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001128
Chris Lattner5cf216b2008-01-04 18:04:52 +00001129 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1130 ArgType, Arg, "passing"))
1131 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001133
1134 // If this is a variadic call, handle args passed through "...".
1135 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001136 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001137 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1138 Expr *Arg = Args[i];
1139 DefaultArgumentPromotion(Arg);
1140 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001141 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001142 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001143 } else {
1144 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1145
Steve Naroffb291ab62007-08-28 23:30:39 +00001146 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001147 for (unsigned i = 0; i != NumArgs; i++) {
1148 Expr *Arg = Args[i];
1149 DefaultArgumentPromotion(Arg);
1150 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001151 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001153
Chris Lattner59907c42007-08-10 20:18:51 +00001154 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001155 if (FDecl)
1156 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001157
Chris Lattner925e60d2007-12-28 05:29:59 +00001158 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001159}
1160
1161Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001162ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001163 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001164 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001165 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001166 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001167 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001168 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001169
Eli Friedman6223c222008-05-20 05:22:08 +00001170 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001171 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001172 return Diag(LParenLoc,
1173 diag::err_variable_object_no_init,
1174 SourceRange(LParenLoc,
1175 literalExpr->getSourceRange().getEnd()));
1176 } else if (literalType->isIncompleteType()) {
1177 return Diag(LParenLoc,
1178 diag::err_typecheck_decl_incomplete_type,
1179 literalType.getAsString(),
1180 SourceRange(LParenLoc,
1181 literalExpr->getSourceRange().getEnd()));
1182 }
1183
Steve Naroffd0091aa2008-01-10 22:15:12 +00001184 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001185 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001186
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001187 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001188 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001189 if (CheckForConstantInitializer(literalExpr, literalType))
1190 return true;
1191 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001192 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001193}
1194
1195Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001196ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001197 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001198 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001199
Steve Naroff08d92e42007-09-15 18:49:24 +00001200 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001201 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001202
Chris Lattnerf0467b32008-04-02 04:24:33 +00001203 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1204 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1205 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001206}
1207
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001208/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001209bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001210 UsualUnaryConversions(castExpr);
1211
1212 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1213 // type needs to be scalar.
1214 if (castType->isVoidType()) {
1215 // Cast to void allows any expr type.
1216 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1217 // GCC struct/union extension: allow cast to self.
1218 if (Context.getCanonicalType(castType) !=
1219 Context.getCanonicalType(castExpr->getType()) ||
1220 (!castType->isStructureType() && !castType->isUnionType())) {
1221 // Reject any other conversions to non-scalar types.
1222 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1223 castType.getAsString(), castExpr->getSourceRange());
1224 }
1225
1226 // accept this, but emit an ext-warn.
1227 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1228 castType.getAsString(), castExpr->getSourceRange());
1229 } else if (!castExpr->getType()->isScalarType() &&
1230 !castExpr->getType()->isVectorType()) {
1231 return Diag(castExpr->getLocStart(),
1232 diag::err_typecheck_expect_scalar_operand,
1233 castExpr->getType().getAsString(),castExpr->getSourceRange());
1234 } else if (castExpr->getType()->isVectorType()) {
1235 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1236 return true;
1237 } else if (castType->isVectorType()) {
1238 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1239 return true;
1240 }
1241 return false;
1242}
1243
Chris Lattnerfe23e212007-12-20 00:44:32 +00001244bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001245 assert(VectorTy->isVectorType() && "Not a vector type!");
1246
1247 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001248 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001249 return Diag(R.getBegin(),
1250 Ty->isVectorType() ?
1251 diag::err_invalid_conversion_between_vectors :
1252 diag::err_invalid_conversion_between_vector_and_integer,
1253 VectorTy.getAsString().c_str(),
1254 Ty.getAsString().c_str(), R);
1255 } else
1256 return Diag(R.getBegin(),
1257 diag::err_invalid_conversion_between_vector_and_scalar,
1258 VectorTy.getAsString().c_str(),
1259 Ty.getAsString().c_str(), R);
1260
1261 return false;
1262}
1263
Steve Naroff4aa88f82007-07-19 01:06:55 +00001264Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001265ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001267 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001268
1269 Expr *castExpr = static_cast<Expr*>(Op);
1270 QualType castType = QualType::getFromOpaquePtr(Ty);
1271
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001272 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1273 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001274 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001275}
1276
Chris Lattnera21ddb32007-11-26 01:40:58 +00001277/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1278/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001279inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001280 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001281 UsualUnaryConversions(cond);
1282 UsualUnaryConversions(lex);
1283 UsualUnaryConversions(rex);
1284 QualType condT = cond->getType();
1285 QualType lexT = lex->getType();
1286 QualType rexT = rex->getType();
1287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001289 if (!condT->isScalarType()) { // C99 6.5.15p2
1290 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1291 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 return QualType();
1293 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001294
1295 // Now check the two expressions.
1296
1297 // If both operands have arithmetic type, do the usual arithmetic conversions
1298 // to find a common type: C99 6.5.15p3,5.
1299 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001300 UsualArithmeticConversions(lex, rex);
1301 return lex->getType();
1302 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001303
1304 // If both operands are the same structure or union type, the result is that
1305 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001306 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001307 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001308 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001309 // "If both the operands have structure or union type, the result has
1310 // that type." This implies that CV qualifiers are dropped.
1311 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001313
1314 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001315 // The following || allows only one side to be void (a GCC-ism).
1316 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001317 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001318 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1319 rex->getSourceRange());
1320 if (!rexT->isVoidType())
1321 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001322 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001323 ImpCastExprToType(lex, Context.VoidTy);
1324 ImpCastExprToType(rex, Context.VoidTy);
1325 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001326 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001327 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1328 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001329 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1330 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001331 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001332 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001333 return lexT;
1334 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001335 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1336 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001337 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001338 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001339 return rexT;
1340 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001341 // Handle the case where both operands are pointers before we handle null
1342 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001343 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1344 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1345 // get the "pointed to" types
1346 QualType lhptee = LHSPT->getPointeeType();
1347 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001348
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001349 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1350 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001351 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001352 // Figure out necessary qualifiers (C99 6.5.15p6)
1353 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001354 QualType destType = Context.getPointerType(destPointee);
1355 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1356 ImpCastExprToType(rex, destType); // promote to void*
1357 return destType;
1358 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001359 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001360 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001361 QualType destType = Context.getPointerType(destPointee);
1362 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1363 ImpCastExprToType(rex, destType); // promote to void*
1364 return destType;
1365 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001366
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001367 QualType compositeType = lexT;
1368
1369 // If either type is an Objective-C object type then check
1370 // compatibility according to Objective-C.
1371 if (Context.isObjCObjectPointerType(lexT) ||
1372 Context.isObjCObjectPointerType(rexT)) {
1373 // If both operands are interfaces and either operand can be
1374 // assigned to the other, use that type as the composite
1375 // type. This allows
1376 // xxx ? (A*) a : (B*) b
1377 // where B is a subclass of A.
1378 //
1379 // Additionally, as for assignment, if either type is 'id'
1380 // allow silent coercion. Finally, if the types are
1381 // incompatible then make sure to use 'id' as the composite
1382 // type so the result is acceptable for sending messages to.
1383
1384 // FIXME: This code should not be localized to here. Also this
1385 // should use a compatible check instead of abusing the
1386 // canAssignObjCInterfaces code.
1387 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1388 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1389 if (LHSIface && RHSIface &&
1390 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1391 compositeType = lexT;
1392 } else if (LHSIface && RHSIface &&
1393 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1394 compositeType = rexT;
1395 } else if (Context.isObjCIdType(lhptee) ||
1396 Context.isObjCIdType(rhptee)) {
1397 // FIXME: This code looks wrong, because isObjCIdType checks
1398 // the struct but getObjCIdType returns the pointer to
1399 // struct. This is horrible and should be fixed.
1400 compositeType = Context.getObjCIdType();
1401 } else {
1402 QualType incompatTy = Context.getObjCIdType();
1403 ImpCastExprToType(lex, incompatTy);
1404 ImpCastExprToType(rex, incompatTy);
1405 return incompatTy;
1406 }
1407 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1408 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001409 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001410 lexT.getAsString(), rexT.getAsString(),
1411 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001412 // In this situation, we assume void* type. No especially good
1413 // reason, but this is what gcc does, and we do have to pick
1414 // to get a consistent AST.
1415 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001416 ImpCastExprToType(lex, incompatTy);
1417 ImpCastExprToType(rex, incompatTy);
1418 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001419 }
1420 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001421 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1422 // differently qualified versions of compatible types, the result type is
1423 // a pointer to an appropriately qualified version of the *composite*
1424 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001425 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001426 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001427 ImpCastExprToType(lex, compositeType);
1428 ImpCastExprToType(rex, compositeType);
1429 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 }
1431 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001432 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1433 // evaluates to "struct objc_object *" (and is handled above when comparing
1434 // id with statically typed objects).
1435 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1436 // GCC allows qualified id and any Objective-C type to devolve to
1437 // id. Currently localizing to here until clear this should be
1438 // part of ObjCQualifiedIdTypesAreCompatible.
1439 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1440 (lexT->isObjCQualifiedIdType() &&
1441 Context.isObjCObjectPointerType(rexT)) ||
1442 (rexT->isObjCQualifiedIdType() &&
1443 Context.isObjCObjectPointerType(lexT))) {
1444 // FIXME: This is not the correct composite type. This only
1445 // happens to work because id can more or less be used anywhere,
1446 // however this may change the type of method sends.
1447 // FIXME: gcc adds some type-checking of the arguments and emits
1448 // (confusing) incompatible comparison warnings in some
1449 // cases. Investigate.
1450 QualType compositeType = Context.getObjCIdType();
1451 ImpCastExprToType(lex, compositeType);
1452 ImpCastExprToType(rex, compositeType);
1453 return compositeType;
1454 }
1455 }
1456
Steve Naroff61f40a22008-09-10 19:17:48 +00001457 // Selection between block pointer types is ok as long as they are the same.
1458 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1459 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1460 return lexT;
1461
Chris Lattner70d67a92008-01-06 22:42:25 +00001462 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001464 lexT.getAsString(), rexT.getAsString(),
1465 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 return QualType();
1467}
1468
Steve Narofff69936d2007-09-16 03:34:24 +00001469/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001470/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001471Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 SourceLocation ColonLoc,
1473 ExprTy *Cond, ExprTy *LHS,
1474 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001475 Expr *CondExpr = (Expr *) Cond;
1476 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001477
1478 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1479 // was the condition.
1480 bool isLHSNull = LHSExpr == 0;
1481 if (isLHSNull)
1482 LHSExpr = CondExpr;
1483
Chris Lattner26824902007-07-16 21:39:03 +00001484 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1485 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 if (result.isNull())
1487 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001488 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1489 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001490}
1491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492
1493// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1494// being closely modeled after the C99 spec:-). The odd characteristic of this
1495// routine is it effectively iqnores the qualifiers on the top level pointee.
1496// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1497// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001498Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001499Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1500 QualType lhptee, rhptee;
1501
1502 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001503 lhptee = lhsType->getAsPointerType()->getPointeeType();
1504 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001505
1506 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001507 lhptee = Context.getCanonicalType(lhptee);
1508 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001509
Chris Lattner5cf216b2008-01-04 18:04:52 +00001510 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001511
1512 // C99 6.5.16.1p1: This following citation is common to constraints
1513 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1514 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001515 // FIXME: Handle ASQualType
1516 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1517 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001518 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001519
1520 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1521 // incomplete type and the other is a pointer to a qualified or unqualified
1522 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001523 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001524 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001525 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001526
1527 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001528 assert(rhptee->isFunctionType());
1529 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001530 }
1531
1532 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001533 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001534 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001535
1536 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001537 assert(lhptee->isFunctionType());
1538 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001539 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001540
1541 // Check for ObjC interfaces
1542 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1543 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1544 if (LHSIface && RHSIface &&
1545 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1546 return ConvTy;
1547
1548 // ID acts sort of like void* for ObjC interfaces
1549 if (LHSIface && Context.isObjCIdType(rhptee))
1550 return ConvTy;
1551 if (RHSIface && Context.isObjCIdType(lhptee))
1552 return ConvTy;
1553
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1555 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001556 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1557 rhptee.getUnqualifiedType()))
1558 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001559 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001560}
1561
Steve Naroff1c7d0672008-09-04 15:10:53 +00001562/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1563/// block pointer types are compatible or whether a block and normal pointer
1564/// are compatible. It is more restrict than comparing two function pointer
1565// types.
1566Sema::AssignConvertType
1567Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1568 QualType rhsType) {
1569 QualType lhptee, rhptee;
1570
1571 // get the "pointed to" type (ignoring qualifiers at the top level)
1572 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1573 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1574
1575 // make sure we operate on the canonical type
1576 lhptee = Context.getCanonicalType(lhptee);
1577 rhptee = Context.getCanonicalType(rhptee);
1578
1579 AssignConvertType ConvTy = Compatible;
1580
1581 // For blocks we enforce that qualifiers are identical.
1582 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1583 ConvTy = CompatiblePointerDiscardsQualifiers;
1584
1585 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1586 return IncompatibleBlockPointer;
1587 return ConvTy;
1588}
1589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1591/// has code to accommodate several GCC extensions when type checking
1592/// pointers. Here are some objectionable examples that GCC considers warnings:
1593///
1594/// int a, *pint;
1595/// short *pshort;
1596/// struct foo *pfoo;
1597///
1598/// pint = pshort; // warning: assignment from incompatible pointer type
1599/// a = pint; // warning: assignment makes integer from pointer without a cast
1600/// pint = a; // warning: assignment makes pointer from integer without a cast
1601/// pint = pfoo; // warning: assignment from incompatible pointer type
1602///
1603/// As a result, the code for dealing with pointers is more complex than the
1604/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001605///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001606Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001607Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001608 // Get canonical types. We're not formatting these types, just comparing
1609 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001610 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1611 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001612
1613 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001614 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001615
Anders Carlsson793680e2007-10-12 23:56:29 +00001616 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001617 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001618 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001619 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001620 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001621
Chris Lattnereca7be62008-04-07 05:30:13 +00001622 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1623 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001624 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001625 // Relax integer conversions like we do for pointers below.
1626 if (rhsType->isIntegerType())
1627 return IntToPointer;
1628 if (lhsType->isIntegerType())
1629 return PointerToInt;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001630 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001631 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001632
Nate Begemanbe2341d2008-07-14 18:02:46 +00001633 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001634 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001635 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1636 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001637 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001638
Nate Begemanbe2341d2008-07-14 18:02:46 +00001639 // If we are allowing lax vector conversions, and LHS and RHS are both
1640 // vectors, the total size only needs to be the same. This is a bitcast;
1641 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001642 if (getLangOptions().LaxVectorConversions &&
1643 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001644 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1645 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001646 }
1647 return Incompatible;
1648 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001649
Chris Lattnere8b3e962008-01-04 23:32:24 +00001650 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001652
Chris Lattner78eca282008-04-07 06:49:41 +00001653 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001655 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001656
Chris Lattner78eca282008-04-07 06:49:41 +00001657 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001659
Steve Naroffb4406862008-09-29 18:10:17 +00001660 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001661 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001662 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001663
1664 // Treat block pointers as objects.
1665 if (getLangOptions().ObjC1 &&
1666 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1667 return Compatible;
1668 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001669 return Incompatible;
1670 }
1671
1672 if (isa<BlockPointerType>(lhsType)) {
1673 if (rhsType->isIntegerType())
1674 return IntToPointer;
1675
Steve Naroffb4406862008-09-29 18:10:17 +00001676 // Treat block pointers as objects.
1677 if (getLangOptions().ObjC1 &&
1678 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1679 return Compatible;
1680
Steve Naroff1c7d0672008-09-04 15:10:53 +00001681 if (rhsType->isBlockPointerType())
1682 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1683
1684 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1685 if (RHSPT->getPointeeType()->isVoidType())
1686 return BlockVoidPointer;
1687 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001688 return Incompatible;
1689 }
1690
Chris Lattner78eca282008-04-07 06:49:41 +00001691 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001693 if (lhsType == Context.BoolTy)
1694 return Compatible;
1695
1696 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001697 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001698
Chris Lattner78eca282008-04-07 06:49:41 +00001699 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001701
1702 if (isa<BlockPointerType>(lhsType) &&
1703 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1704 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001705 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001706 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001707
Chris Lattnerfc144e22008-01-04 23:18:45 +00001708 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001709 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
1712 return Incompatible;
1713}
1714
Chris Lattner5cf216b2008-01-04 18:04:52 +00001715Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001716Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001717 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1718 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001719 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1720 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001721 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001722 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001723 return Compatible;
1724 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001725
1726 // We don't allow conversion of non-null-pointer constants to integers.
1727 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1728 return IntToBlockPointer;
1729
Chris Lattner943140e2007-10-16 02:55:40 +00001730 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001731 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001732 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001733 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001734 //
1735 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1736 // are better understood.
1737 if (!lhsType->isReferenceType())
1738 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001739
Chris Lattner5cf216b2008-01-04 18:04:52 +00001740 Sema::AssignConvertType result =
1741 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001742
1743 // C99 6.5.16.1p2: The value of the right operand is converted to the
1744 // type of the assignment expression.
1745 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001746 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001747 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001748}
1749
Chris Lattner5cf216b2008-01-04 18:04:52 +00001750Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001751Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1752 return CheckAssignmentConstraints(lhsType, rhsType);
1753}
1754
Chris Lattnerca5eede2007-12-12 05:47:28 +00001755QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 Diag(loc, diag::err_typecheck_invalid_operands,
1757 lex->getType().getAsString(), rex->getType().getAsString(),
1758 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001759 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001760}
1761
Steve Naroff49b45262007-07-13 16:58:59 +00001762inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1763 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001764 // For conversion purposes, we ignore any qualifiers.
1765 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001766 QualType lhsType =
1767 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1768 QualType rhsType =
1769 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001770
Nate Begemanbe2341d2008-07-14 18:02:46 +00001771 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001772 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001774
Nate Begemanbe2341d2008-07-14 18:02:46 +00001775 // Handle the case of a vector & extvector type of the same size and element
1776 // type. It would be nice if we only had one vector type someday.
1777 if (getLangOptions().LaxVectorConversions)
1778 if (const VectorType *LV = lhsType->getAsVectorType())
1779 if (const VectorType *RV = rhsType->getAsVectorType())
1780 if (LV->getElementType() == RV->getElementType() &&
1781 LV->getNumElements() == RV->getNumElements())
1782 return lhsType->isExtVectorType() ? lhsType : rhsType;
1783
1784 // If the lhs is an extended vector and the rhs is a scalar of the same type
1785 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001786 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001787 QualType eltType = V->getElementType();
1788
1789 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1790 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1791 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001792 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001793 return lhsType;
1794 }
1795 }
1796
Nate Begemanbe2341d2008-07-14 18:02:46 +00001797 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001798 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001799 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001800 QualType eltType = V->getElementType();
1801
1802 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1803 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1804 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001805 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001806 return rhsType;
1807 }
1808 }
1809
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 // You cannot convert between vector values of different size.
1811 Diag(loc, diag::err_typecheck_vector_not_convertable,
1812 lex->getType().getAsString(), rex->getType().getAsString(),
1813 lex->getSourceRange(), rex->getSourceRange());
1814 return QualType();
1815}
1816
1817inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001818 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001819{
Steve Naroff90045e82007-07-13 23:32:42 +00001820 QualType lhsType = lex->getType(), rhsType = rex->getType();
1821
1822 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001824
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001825 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001826
Steve Naroffa4332e22007-07-17 00:58:39 +00001827 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001828 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001829 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001830}
1831
1832inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001833 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001834{
Steve Naroff90045e82007-07-13 23:32:42 +00001835 QualType lhsType = lex->getType(), rhsType = rex->getType();
1836
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001837 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001838
Steve Naroffa4332e22007-07-17 00:58:39 +00001839 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001840 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001841 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001842}
1843
1844inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001845 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001846{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001847 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001848 return CheckVectorOperands(loc, lex, rex);
1849
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001850 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001851
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001853 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001854 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001855
Eli Friedmand72d16e2008-05-18 18:08:51 +00001856 // Put any potential pointer into PExp
1857 Expr* PExp = lex, *IExp = rex;
1858 if (IExp->getType()->isPointerType())
1859 std::swap(PExp, IExp);
1860
1861 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1862 if (IExp->getType()->isIntegerType()) {
1863 // Check for arithmetic on pointers to incomplete types
1864 if (!PTy->getPointeeType()->isObjectType()) {
1865 if (PTy->getPointeeType()->isVoidType()) {
1866 Diag(loc, diag::ext_gnu_void_ptr,
1867 lex->getSourceRange(), rex->getSourceRange());
1868 } else {
1869 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1870 lex->getType().getAsString(), lex->getSourceRange());
1871 return QualType();
1872 }
1873 }
1874 return PExp->getType();
1875 }
1876 }
1877
Chris Lattnerca5eede2007-12-12 05:47:28 +00001878 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001879}
1880
Chris Lattnereca7be62008-04-07 05:30:13 +00001881// C99 6.5.6
1882QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1883 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001884 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001886
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001887 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001888
Chris Lattner6e4ab612007-12-09 21:53:25 +00001889 // Enforce type constraints: C99 6.5.6p3.
1890
1891 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001892 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001893 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001894
1895 // Either ptr - int or ptr - ptr.
1896 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001897 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001898
Chris Lattner6e4ab612007-12-09 21:53:25 +00001899 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001900 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001901 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001902 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001903 Diag(loc, diag::ext_gnu_void_ptr,
1904 lex->getSourceRange(), rex->getSourceRange());
1905 } else {
1906 Diag(loc, diag::err_typecheck_sub_ptr_object,
1907 lex->getType().getAsString(), lex->getSourceRange());
1908 return QualType();
1909 }
1910 }
1911
1912 // The result type of a pointer-int computation is the pointer type.
1913 if (rex->getType()->isIntegerType())
1914 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001915
Chris Lattner6e4ab612007-12-09 21:53:25 +00001916 // Handle pointer-pointer subtractions.
1917 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001918 QualType rpointee = RHSPTy->getPointeeType();
1919
Chris Lattner6e4ab612007-12-09 21:53:25 +00001920 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001921 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001922 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001923 if (rpointee->isVoidType()) {
1924 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001925 Diag(loc, diag::ext_gnu_void_ptr,
1926 lex->getSourceRange(), rex->getSourceRange());
1927 } else {
1928 Diag(loc, diag::err_typecheck_sub_ptr_object,
1929 rex->getType().getAsString(), rex->getSourceRange());
1930 return QualType();
1931 }
1932 }
1933
1934 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001935 if (!Context.typesAreCompatible(
1936 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1937 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001938 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1939 lex->getType().getAsString(), rex->getType().getAsString(),
1940 lex->getSourceRange(), rex->getSourceRange());
1941 return QualType();
1942 }
1943
1944 return Context.getPointerDiffType();
1945 }
1946 }
1947
Chris Lattnerca5eede2007-12-12 05:47:28 +00001948 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001949}
1950
Chris Lattnereca7be62008-04-07 05:30:13 +00001951// C99 6.5.7
1952QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1953 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00001954 // C99 6.5.7p2: Each of the operands shall have integer type.
1955 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1956 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001957
Chris Lattnerca5eede2007-12-12 05:47:28 +00001958 // Shifts don't perform usual arithmetic conversions, they just do integer
1959 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001960 if (!isCompAssign)
1961 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001962 UsualUnaryConversions(rex);
1963
1964 // "The type of the result is that of the promoted left operand."
1965 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001966}
1967
Eli Friedman3d815e72008-08-22 00:56:42 +00001968static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1969 ASTContext& Context) {
1970 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1971 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1972 // ID acts sort of like void* for ObjC interfaces
1973 if (LHSIface && Context.isObjCIdType(RHS))
1974 return true;
1975 if (RHSIface && Context.isObjCIdType(LHS))
1976 return true;
1977 if (!LHSIface || !RHSIface)
1978 return false;
1979 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1980 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1981}
1982
Chris Lattnereca7be62008-04-07 05:30:13 +00001983// C99 6.5.8
1984QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1985 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001986 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1987 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1988
Chris Lattnera5937dd2007-08-26 01:18:55 +00001989 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001990 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1991 UsualArithmeticConversions(lex, rex);
1992 else {
1993 UsualUnaryConversions(lex);
1994 UsualUnaryConversions(rex);
1995 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001996 QualType lType = lex->getType();
1997 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001998
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001999 // For non-floating point types, check for self-comparisons of the form
2000 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2001 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002002 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002003 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2004 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002005 if (DRL->getDecl() == DRR->getDecl())
2006 Diag(loc, diag::warn_selfcomparison);
2007 }
2008
Chris Lattnera5937dd2007-08-26 01:18:55 +00002009 if (isRelational) {
2010 if (lType->isRealType() && rType->isRealType())
2011 return Context.IntTy;
2012 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002013 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002014 if (lType->isFloatingType()) {
2015 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002016 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002017 }
2018
Chris Lattnera5937dd2007-08-26 01:18:55 +00002019 if (lType->isArithmeticType() && rType->isArithmeticType())
2020 return Context.IntTy;
2021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002022
Chris Lattnerd28f8152007-08-26 01:10:14 +00002023 bool LHSIsNull = lex->isNullPointerConstant(Context);
2024 bool RHSIsNull = rex->isNullPointerConstant(Context);
2025
Chris Lattnera5937dd2007-08-26 01:18:55 +00002026 // All of the following pointer related warnings are GCC extensions, except
2027 // when handling null pointer constants. One day, we can consider making them
2028 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002029 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002030 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002031 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002032 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002033 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002034
Steve Naroff66296cb2007-11-13 14:57:38 +00002035 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002036 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2037 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002038 RCanPointeeTy.getUnqualifiedType()) &&
2039 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002040 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2041 lType.getAsString(), rType.getAsString(),
2042 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002044 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002045 return Context.IntTy;
2046 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002047 // Handle block pointer types.
2048 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2049 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2050 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2051
2052 if (!LHSIsNull && !RHSIsNull &&
2053 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2054 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2055 lType.getAsString(), rType.getAsString(),
2056 lex->getSourceRange(), rex->getSourceRange());
2057 }
2058 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2059 return Context.IntTy;
2060 }
Steve Naroff59f53942008-09-28 01:11:11 +00002061 // Allow block pointers to be compared with null pointer constants.
2062 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2063 (lType->isPointerType() && rType->isBlockPointerType())) {
2064 if (!LHSIsNull && !RHSIsNull) {
2065 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2066 lType.getAsString(), rType.getAsString(),
2067 lex->getSourceRange(), rex->getSourceRange());
2068 }
2069 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2070 return Context.IntTy;
2071 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002072
Steve Naroff20373222008-06-03 14:04:54 +00002073 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2074 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2075 ImpCastExprToType(rex, lType);
2076 return Context.IntTy;
2077 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002078 }
Steve Naroff20373222008-06-03 14:04:54 +00002079 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2080 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002081 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002082 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2083 lType.getAsString(), rType.getAsString(),
2084 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002085 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002086 return Context.IntTy;
2087 }
Steve Naroff20373222008-06-03 14:04:54 +00002088 if (lType->isIntegerType() &&
2089 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002090 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002091 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2092 lType.getAsString(), rType.getAsString(),
2093 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002094 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002095 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 }
Steve Naroff39218df2008-09-04 16:56:14 +00002097 // Handle block pointers.
2098 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2099 if (!RHSIsNull)
2100 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2101 lType.getAsString(), rType.getAsString(),
2102 lex->getSourceRange(), rex->getSourceRange());
2103 ImpCastExprToType(rex, lType); // promote the integer to pointer
2104 return Context.IntTy;
2105 }
2106 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2107 if (!LHSIsNull)
2108 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2109 lType.getAsString(), rType.getAsString(),
2110 lex->getSourceRange(), rex->getSourceRange());
2111 ImpCastExprToType(lex, rType); // promote the integer to pointer
2112 return Context.IntTy;
2113 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002114 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002115}
2116
Nate Begemanbe2341d2008-07-14 18:02:46 +00002117/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2118/// operates on extended vector types. Instead of producing an IntTy result,
2119/// like a scalar comparison, a vector comparison produces a vector of integer
2120/// types.
2121QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2122 SourceLocation loc,
2123 bool isRelational) {
2124 // Check to make sure we're operating on vectors of the same type and width,
2125 // Allowing one side to be a scalar of element type.
2126 QualType vType = CheckVectorOperands(loc, lex, rex);
2127 if (vType.isNull())
2128 return vType;
2129
2130 QualType lType = lex->getType();
2131 QualType rType = rex->getType();
2132
2133 // For non-floating point types, check for self-comparisons of the form
2134 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2135 // often indicate logic errors in the program.
2136 if (!lType->isFloatingType()) {
2137 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2138 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2139 if (DRL->getDecl() == DRR->getDecl())
2140 Diag(loc, diag::warn_selfcomparison);
2141 }
2142
2143 // Check for comparisons of floating point operands using != and ==.
2144 if (!isRelational && lType->isFloatingType()) {
2145 assert (rType->isFloatingType());
2146 CheckFloatComparison(loc,lex,rex);
2147 }
2148
2149 // Return the type for the comparison, which is the same as vector type for
2150 // integer vectors, or an integer type of identical size and number of
2151 // elements for floating point vectors.
2152 if (lType->isIntegerType())
2153 return lType;
2154
2155 const VectorType *VTy = lType->getAsVectorType();
2156
2157 // FIXME: need to deal with non-32b int / non-64b long long
2158 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2159 if (TypeSize == 32) {
2160 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2161 }
2162 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2163 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2164}
2165
Reid Spencer5f016e22007-07-11 17:01:13 +00002166inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002167 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002168{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002169 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002171
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002172 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002173
Steve Naroffa4332e22007-07-17 00:58:39 +00002174 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002175 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002176 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002177}
2178
2179inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002180 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002181{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002182 UsualUnaryConversions(lex);
2183 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002184
Eli Friedman5773a6c2008-05-13 20:16:47 +00002185 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002187 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002188}
2189
2190inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002191 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002192{
2193 QualType lhsType = lex->getType();
2194 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002195 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002196
2197 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002198 case Expr::MLV_Valid:
2199 break;
2200 case Expr::MLV_ConstQualified:
2201 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2202 return QualType();
2203 case Expr::MLV_ArrayType:
2204 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2205 lhsType.getAsString(), lex->getSourceRange());
2206 return QualType();
2207 case Expr::MLV_NotObjectType:
2208 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2209 lhsType.getAsString(), lex->getSourceRange());
2210 return QualType();
2211 case Expr::MLV_InvalidExpression:
2212 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2213 lex->getSourceRange());
2214 return QualType();
2215 case Expr::MLV_IncompleteType:
2216 case Expr::MLV_IncompleteVoidType:
2217 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2218 lhsType.getAsString(), lex->getSourceRange());
2219 return QualType();
2220 case Expr::MLV_DuplicateVectorComponents:
2221 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2222 lex->getSourceRange());
2223 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002224 case Expr::MLV_NotBlockQualified:
2225 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2226 lex->getSourceRange());
2227 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002229
Chris Lattner5cf216b2008-01-04 18:04:52 +00002230 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002231 if (compoundType.isNull()) {
2232 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002233 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002234
2235 // If the RHS is a unary plus or minus, check to see if they = and + are
2236 // right next to each other. If so, the user may have typo'd "x =+ 4"
2237 // instead of "x += 4".
2238 Expr *RHSCheck = rex;
2239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2240 RHSCheck = ICE->getSubExpr();
2241 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2242 if ((UO->getOpcode() == UnaryOperator::Plus ||
2243 UO->getOpcode() == UnaryOperator::Minus) &&
2244 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2245 // Only if the two operators are exactly adjacent.
2246 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2247 Diag(loc, diag::warn_not_compound_assign,
2248 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2249 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2250 }
2251 } else {
2252 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002253 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002254 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002255
2256 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2257 rex, "assigning"))
2258 return QualType();
2259
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 // C99 6.5.16p3: The type of an assignment expression is the type of the
2261 // left operand unless the left operand has qualified type, in which case
2262 // it is the unqualified version of the type of the left operand.
2263 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2264 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002265 // C++ 5.17p1: the type of the assignment expression is that of its left
2266 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002267 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002268}
2269
2270inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002271 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002272
2273 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2274 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002275 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002276}
2277
Steve Naroff49b45262007-07-13 16:58:59 +00002278/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2279/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002280QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002281 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 assert(!resType.isNull() && "no type for increment/decrement expression");
2283
Steve Naroff084f9ed2007-08-24 17:20:07 +00002284 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002285 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002286 if (pt->getPointeeType()->isVoidType()) {
2287 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2288 } else if (!pt->getPointeeType()->isObjectType()) {
2289 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2291 resType.getAsString(), op->getSourceRange());
2292 return QualType();
2293 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002294 } else if (!resType->isRealType()) {
2295 if (resType->isComplexType())
2296 // C99 does not support ++/-- on complex types.
2297 Diag(OpLoc, diag::ext_integer_increment_complex,
2298 resType.getAsString(), op->getSourceRange());
2299 else {
2300 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2301 resType.getAsString(), op->getSourceRange());
2302 return QualType();
2303 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002305 // At this point, we know we have a real, complex or pointer type.
2306 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002307 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002308 if (mlval != Expr::MLV_Valid) {
2309 // FIXME: emit a more precise diagnostic...
2310 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2311 op->getSourceRange());
2312 return QualType();
2313 }
2314 return resType;
2315}
2316
Anders Carlsson369dee42008-02-01 07:15:58 +00002317/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002318/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002319/// where the declaration is needed for type checking. We only need to
2320/// handle cases when the expression references a function designator
2321/// or is an lvalue. Here are some examples:
2322/// - &(x) => x
2323/// - &*****f => f for f a function designator.
2324/// - &s.xx => s
2325/// - &s.zz[1].yy -> s, if zz is an array
2326/// - *(x + 1) -> x, if x is an array
2327/// - &"123"[2] -> 0
2328/// - & __real__ x -> x
Chris Lattnerf0467b32008-04-02 04:24:33 +00002329static ValueDecl *getPrimaryDecl(Expr *E) {
2330 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002332 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002334 // Fields cannot be declared with a 'register' storage class.
2335 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002336 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002337 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002338 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002339 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002340 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002341
Chris Lattnerf0467b32008-04-02 04:24:33 +00002342 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002343 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002344 return 0;
2345 else
2346 return VD;
2347 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002348 case Stmt::UnaryOperatorClass: {
2349 UnaryOperator *UO = cast<UnaryOperator>(E);
2350
2351 switch(UO->getOpcode()) {
2352 case UnaryOperator::Deref: {
2353 // *(X + 1) refers to X if X is not a pointer.
2354 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2355 if (!VD || VD->getType()->isPointerType())
2356 return 0;
2357 return VD;
2358 }
2359 case UnaryOperator::Real:
2360 case UnaryOperator::Imag:
2361 case UnaryOperator::Extension:
2362 return getPrimaryDecl(UO->getSubExpr());
2363 default:
2364 return 0;
2365 }
2366 }
2367 case Stmt::BinaryOperatorClass: {
2368 BinaryOperator *BO = cast<BinaryOperator>(E);
2369
2370 // Handle cases involving pointer arithmetic. The result of an
2371 // Assign or AddAssign is not an lvalue so they can be ignored.
2372
2373 // (x + n) or (n + x) => x
2374 if (BO->getOpcode() == BinaryOperator::Add) {
2375 if (BO->getLHS()->getType()->isPointerType()) {
2376 return getPrimaryDecl(BO->getLHS());
2377 } else if (BO->getRHS()->getType()->isPointerType()) {
2378 return getPrimaryDecl(BO->getRHS());
2379 }
2380 }
2381
2382 return 0;
2383 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002384 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002385 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002386 case Stmt::ImplicitCastExprClass:
2387 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002388 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 default:
2390 return 0;
2391 }
2392}
2393
2394/// CheckAddressOfOperand - The operand of & must be either a function
2395/// designator or an lvalue designating an object. If it is an lvalue, the
2396/// object cannot be declared with storage class register or be a bit field.
2397/// Note: The usual conversions are *not* applied to the operand of the &
2398/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2399QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002400 if (getLangOptions().C99) {
2401 // Implement C99-only parts of addressof rules.
2402 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2403 if (uOp->getOpcode() == UnaryOperator::Deref)
2404 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2405 // (assuming the deref expression is valid).
2406 return uOp->getSubExpr()->getType();
2407 }
2408 // Technically, there should be a check for array subscript
2409 // expressions here, but the result of one is always an lvalue anyway.
2410 }
Anders Carlsson369dee42008-02-01 07:15:58 +00002411 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002412 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002413
2414 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002415 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2416 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002417 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2418 op->getSourceRange());
2419 return QualType();
2420 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002421 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2422 if (MemExpr->getMemberDecl()->isBitField()) {
2423 Diag(OpLoc, diag::err_typecheck_address_of,
2424 std::string("bit-field"), op->getSourceRange());
2425 return QualType();
2426 }
2427 // Check for Apple extension for accessing vector components.
2428 } else if (isa<ArraySubscriptExpr>(op) &&
2429 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2430 Diag(OpLoc, diag::err_typecheck_address_of,
2431 std::string("vector"), op->getSourceRange());
2432 return QualType();
2433 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002434 // We have an lvalue with a decl. Make sure the decl is not declared
2435 // with the register storage-class specifier.
2436 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2437 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002438 Diag(OpLoc, diag::err_typecheck_address_of,
2439 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002440 return QualType();
2441 }
2442 } else
2443 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002445
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 // If the operand has type "type", the result has type "pointer to type".
2447 return Context.getPointerType(op->getType());
2448}
2449
2450QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002451 UsualUnaryConversions(op);
2452 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002453
Chris Lattnerbefee482007-07-31 16:53:04 +00002454 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002455 // Note that per both C89 and C99, this is always legal, even
2456 // if ptype is an incomplete type or void.
2457 // It would be possible to warn about dereferencing a
2458 // void pointer, but it's completely well-defined,
2459 // and such a warning is unlikely to catch any mistakes.
2460 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002461 }
2462 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2463 qType.getAsString(), op->getSourceRange());
2464 return QualType();
2465}
2466
2467static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2468 tok::TokenKind Kind) {
2469 BinaryOperator::Opcode Opc;
2470 switch (Kind) {
2471 default: assert(0 && "Unknown binop!");
2472 case tok::star: Opc = BinaryOperator::Mul; break;
2473 case tok::slash: Opc = BinaryOperator::Div; break;
2474 case tok::percent: Opc = BinaryOperator::Rem; break;
2475 case tok::plus: Opc = BinaryOperator::Add; break;
2476 case tok::minus: Opc = BinaryOperator::Sub; break;
2477 case tok::lessless: Opc = BinaryOperator::Shl; break;
2478 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2479 case tok::lessequal: Opc = BinaryOperator::LE; break;
2480 case tok::less: Opc = BinaryOperator::LT; break;
2481 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2482 case tok::greater: Opc = BinaryOperator::GT; break;
2483 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2484 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2485 case tok::amp: Opc = BinaryOperator::And; break;
2486 case tok::caret: Opc = BinaryOperator::Xor; break;
2487 case tok::pipe: Opc = BinaryOperator::Or; break;
2488 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2489 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2490 case tok::equal: Opc = BinaryOperator::Assign; break;
2491 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2492 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2493 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2494 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2495 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2496 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2497 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2498 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2499 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2500 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2501 case tok::comma: Opc = BinaryOperator::Comma; break;
2502 }
2503 return Opc;
2504}
2505
2506static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2507 tok::TokenKind Kind) {
2508 UnaryOperator::Opcode Opc;
2509 switch (Kind) {
2510 default: assert(0 && "Unknown unary op!");
2511 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2512 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2513 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2514 case tok::star: Opc = UnaryOperator::Deref; break;
2515 case tok::plus: Opc = UnaryOperator::Plus; break;
2516 case tok::minus: Opc = UnaryOperator::Minus; break;
2517 case tok::tilde: Opc = UnaryOperator::Not; break;
2518 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2519 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2520 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2521 case tok::kw___real: Opc = UnaryOperator::Real; break;
2522 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2523 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2524 }
2525 return Opc;
2526}
2527
2528// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002529Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 ExprTy *LHS, ExprTy *RHS) {
2531 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2532 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2533
Steve Narofff69936d2007-09-16 03:34:24 +00002534 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2535 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002536
2537 QualType ResultTy; // Result type of the binary operator.
2538 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2539
2540 switch (Opc) {
2541 default:
2542 assert(0 && "Unknown binary expr!");
2543 case BinaryOperator::Assign:
2544 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2545 break;
2546 case BinaryOperator::Mul:
2547 case BinaryOperator::Div:
2548 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2549 break;
2550 case BinaryOperator::Rem:
2551 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2552 break;
2553 case BinaryOperator::Add:
2554 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2555 break;
2556 case BinaryOperator::Sub:
2557 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2558 break;
2559 case BinaryOperator::Shl:
2560 case BinaryOperator::Shr:
2561 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2562 break;
2563 case BinaryOperator::LE:
2564 case BinaryOperator::LT:
2565 case BinaryOperator::GE:
2566 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002567 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 break;
2569 case BinaryOperator::EQ:
2570 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002571 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 break;
2573 case BinaryOperator::And:
2574 case BinaryOperator::Xor:
2575 case BinaryOperator::Or:
2576 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2577 break;
2578 case BinaryOperator::LAnd:
2579 case BinaryOperator::LOr:
2580 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2581 break;
2582 case BinaryOperator::MulAssign:
2583 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002584 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 if (!CompTy.isNull())
2586 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2587 break;
2588 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002589 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 if (!CompTy.isNull())
2591 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2592 break;
2593 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002594 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 if (!CompTy.isNull())
2596 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2597 break;
2598 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002599 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 if (!CompTy.isNull())
2601 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2602 break;
2603 case BinaryOperator::ShlAssign:
2604 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002605 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 if (!CompTy.isNull())
2607 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2608 break;
2609 case BinaryOperator::AndAssign:
2610 case BinaryOperator::XorAssign:
2611 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002612 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 if (!CompTy.isNull())
2614 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2615 break;
2616 case BinaryOperator::Comma:
2617 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2618 break;
2619 }
2620 if (ResultTy.isNull())
2621 return true;
2622 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002623 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002625 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002626}
2627
2628// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002629Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 ExprTy *input) {
2631 Expr *Input = (Expr*)input;
2632 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2633 QualType resultType;
2634 switch (Opc) {
2635 default:
2636 assert(0 && "Unimplemented unary expr!");
2637 case UnaryOperator::PreInc:
2638 case UnaryOperator::PreDec:
2639 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2640 break;
2641 case UnaryOperator::AddrOf:
2642 resultType = CheckAddressOfOperand(Input, OpLoc);
2643 break;
2644 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002645 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 resultType = CheckIndirectionOperand(Input, OpLoc);
2647 break;
2648 case UnaryOperator::Plus:
2649 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002650 UsualUnaryConversions(Input);
2651 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2653 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2654 resultType.getAsString());
2655 break;
2656 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002657 UsualUnaryConversions(Input);
2658 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002659 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2660 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2661 // C99 does not support '~' for complex conjugation.
2662 Diag(OpLoc, diag::ext_integer_complement_complex,
2663 resultType.getAsString(), Input->getSourceRange());
2664 else if (!resultType->isIntegerType())
2665 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2666 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 break;
2668 case UnaryOperator::LNot: // logical negation
2669 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002670 DefaultFunctionArrayConversion(Input);
2671 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2673 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2674 resultType.getAsString());
2675 // LNot always has type int. C99 6.5.3.3p5.
2676 resultType = Context.IntTy;
2677 break;
2678 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002679 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2680 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 break;
2682 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002683 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2684 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002686 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002687 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002688 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002689 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 resultType = Input->getType();
2692 break;
2693 }
2694 if (resultType.isNull())
2695 return true;
2696 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2697}
2698
Steve Naroff1b273c42007-09-16 14:56:35 +00002699/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2700Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 SourceLocation LabLoc,
2702 IdentifierInfo *LabelII) {
2703 // Look up the record for this label identifier.
2704 LabelStmt *&LabelDecl = LabelMap[LabelII];
2705
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002706 // If we haven't seen this label yet, create a forward reference. It
2707 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 if (LabelDecl == 0)
2709 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2710
2711 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002712 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2713 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002714}
2715
Steve Naroff1b273c42007-09-16 14:56:35 +00002716Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002717 SourceLocation RPLoc) { // "({..})"
2718 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2719 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2720 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2721
2722 // FIXME: there are a variety of strange constraints to enforce here, for
2723 // example, it is not possible to goto into a stmt expression apparently.
2724 // More semantic analysis is needed.
2725
2726 // FIXME: the last statement in the compount stmt has its value used. We
2727 // should not warn about it being unused.
2728
2729 // If there are sub stmts in the compound stmt, take the type of the last one
2730 // as the type of the stmtexpr.
2731 QualType Ty = Context.VoidTy;
2732
Chris Lattner611b2ec2008-07-26 19:51:01 +00002733 if (!Compound->body_empty()) {
2734 Stmt *LastStmt = Compound->body_back();
2735 // If LastStmt is a label, skip down through into the body.
2736 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2737 LastStmt = Label->getSubStmt();
2738
2739 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002740 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002741 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002742
2743 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2744}
Steve Naroffd34e9152007-08-01 22:05:33 +00002745
Steve Naroff1b273c42007-09-16 14:56:35 +00002746Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002747 SourceLocation TypeLoc,
2748 TypeTy *argty,
2749 OffsetOfComponent *CompPtr,
2750 unsigned NumComponents,
2751 SourceLocation RPLoc) {
2752 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2753 assert(!ArgTy.isNull() && "Missing type argument!");
2754
2755 // We must have at least one component that refers to the type, and the first
2756 // one is known to be a field designator. Verify that the ArgTy represents
2757 // a struct/union/class.
2758 if (!ArgTy->isRecordType())
2759 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2760
2761 // Otherwise, create a compound literal expression as the base, and
2762 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002763 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002764
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002765 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2766 // GCC extension, diagnose them.
2767 if (NumComponents != 1)
2768 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2769 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2770
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002771 for (unsigned i = 0; i != NumComponents; ++i) {
2772 const OffsetOfComponent &OC = CompPtr[i];
2773 if (OC.isBrackets) {
2774 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002775 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002776 if (!AT) {
2777 delete Res;
2778 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2779 Res->getType().getAsString());
2780 }
2781
Chris Lattner704fe352007-08-30 17:59:59 +00002782 // FIXME: C++: Verify that operator[] isn't overloaded.
2783
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002784 // C99 6.5.2.1p1
2785 Expr *Idx = static_cast<Expr*>(OC.U.E);
2786 if (!Idx->getType()->isIntegerType())
2787 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2788 Idx->getSourceRange());
2789
2790 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2791 continue;
2792 }
2793
2794 const RecordType *RC = Res->getType()->getAsRecordType();
2795 if (!RC) {
2796 delete Res;
2797 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2798 Res->getType().getAsString());
2799 }
2800
2801 // Get the decl corresponding to this.
2802 RecordDecl *RD = RC->getDecl();
2803 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2804 if (!MemberDecl)
2805 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2806 OC.U.IdentInfo->getName(),
2807 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002808
2809 // FIXME: C++: Verify that MemberDecl isn't a static field.
2810 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002811 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2812 // matter here.
2813 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002814 }
2815
2816 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2817 BuiltinLoc);
2818}
2819
2820
Steve Naroff1b273c42007-09-16 14:56:35 +00002821Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002822 TypeTy *arg1, TypeTy *arg2,
2823 SourceLocation RPLoc) {
2824 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2825 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2826
2827 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2828
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002829 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002830}
2831
Steve Naroff1b273c42007-09-16 14:56:35 +00002832Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002833 ExprTy *expr1, ExprTy *expr2,
2834 SourceLocation RPLoc) {
2835 Expr *CondExpr = static_cast<Expr*>(cond);
2836 Expr *LHSExpr = static_cast<Expr*>(expr1);
2837 Expr *RHSExpr = static_cast<Expr*>(expr2);
2838
2839 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2840
2841 // The conditional expression is required to be a constant expression.
2842 llvm::APSInt condEval(32);
2843 SourceLocation ExpLoc;
2844 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2845 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2846 CondExpr->getSourceRange());
2847
2848 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2849 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2850 RHSExpr->getType();
2851 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2852}
2853
Steve Naroff4eb206b2008-09-03 18:15:37 +00002854//===----------------------------------------------------------------------===//
2855// Clang Extensions.
2856//===----------------------------------------------------------------------===//
2857
2858/// ActOnBlockStart - This callback is invoked when a block literal is started.
2859void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2860 Declarator &ParamInfo) {
2861 // Analyze block parameters.
2862 BlockSemaInfo *BSI = new BlockSemaInfo();
2863
2864 // Add BSI to CurBlock.
2865 BSI->PrevBlockInfo = CurBlock;
2866 CurBlock = BSI;
2867
2868 BSI->ReturnType = 0;
2869 BSI->TheScope = BlockScope;
2870
2871 // Analyze arguments to block.
2872 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2873 "Not a function declarator!");
2874 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2875
2876 BSI->hasPrototype = FTI.hasPrototype;
2877 BSI->isVariadic = true;
2878
2879 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2880 // no arguments, not a function that takes a single void argument.
2881 if (FTI.hasPrototype &&
2882 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2883 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2884 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2885 // empty arg list, don't push any params.
2886 BSI->isVariadic = false;
2887 } else if (FTI.hasPrototype) {
2888 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2889 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2890 BSI->isVariadic = FTI.isVariadic;
2891 }
Steve Naroff1c90bfc2008-10-08 18:44:00 +00002892 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc,
2893 &BSI->Params[0], BSI->Params.size());
Steve Naroff4eb206b2008-09-03 18:15:37 +00002894}
2895
2896/// ActOnBlockError - If there is an error parsing a block, this callback
2897/// is invoked to pop the information about the block from the action impl.
2898void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2899 // Ensure that CurBlock is deleted.
2900 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2901
2902 // Pop off CurBlock, handle nested blocks.
2903 CurBlock = CurBlock->PrevBlockInfo;
2904
2905 // FIXME: Delete the ParmVarDecl objects as well???
2906
2907}
2908
2909/// ActOnBlockStmtExpr - This is called when the body of a block statement
2910/// literal was successfully completed. ^(int x){...}
2911Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2912 Scope *CurScope) {
2913 // Ensure that CurBlock is deleted.
2914 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2915 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2916
2917 // Pop off CurBlock, handle nested blocks.
2918 CurBlock = CurBlock->PrevBlockInfo;
2919
2920 QualType RetTy = Context.VoidTy;
2921 if (BSI->ReturnType)
2922 RetTy = QualType(BSI->ReturnType, 0);
2923
2924 llvm::SmallVector<QualType, 8> ArgTypes;
2925 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2926 ArgTypes.push_back(BSI->Params[i]->getType());
2927
2928 QualType BlockTy;
2929 if (!BSI->hasPrototype)
2930 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2931 else
2932 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2933 BSI->isVariadic);
2934
2935 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00002936
Steve Naroff1c90bfc2008-10-08 18:44:00 +00002937 BSI->TheDecl->setBody(Body.take());
2938 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002939}
2940
Nate Begeman67295d02008-01-30 20:50:20 +00002941/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00002942/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00002943/// The number of arguments has already been validated to match the number of
2944/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002945static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2946 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00002947 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00002948 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002949 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2950 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00002951
2952 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00002953 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00002954 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002955 return true;
2956}
2957
2958Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2959 SourceLocation *CommaLocs,
2960 SourceLocation BuiltinLoc,
2961 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002962 // __builtin_overload requires at least 2 arguments
2963 if (NumArgs < 2)
2964 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2965 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00002966
Nate Begemane2ce1d92008-01-17 17:46:27 +00002967 // The first argument is required to be a constant expression. It tells us
2968 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002969 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00002970 Expr *NParamsExpr = Args[0];
2971 llvm::APSInt constEval(32);
2972 SourceLocation ExpLoc;
2973 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2974 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2975 NParamsExpr->getSourceRange());
2976
2977 // Verify that the number of parameters is > 0
2978 unsigned NumParams = constEval.getZExtValue();
2979 if (NumParams == 0)
2980 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2981 NParamsExpr->getSourceRange());
2982 // Verify that we have at least 1 + NumParams arguments to the builtin.
2983 if ((NumParams + 1) > NumArgs)
2984 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2985 SourceRange(BuiltinLoc, RParenLoc));
2986
2987 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00002988 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002989 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002990 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2991 // UsualUnaryConversions will convert the function DeclRefExpr into a
2992 // pointer to function.
2993 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00002994 const FunctionTypeProto *FnType = 0;
2995 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2996 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00002997
2998 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2999 // parameters, and the number of parameters must match the value passed to
3000 // the builtin.
3001 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00003002 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3003 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00003004
3005 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003006 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003007 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003008 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003009 if (OE)
3010 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3011 OE->getFn()->getSourceRange());
3012 // Remember our match, and continue processing the remaining arguments
3013 // to catch any errors.
3014 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3015 BuiltinLoc, RParenLoc);
3016 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003017 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003018 // Return the newly created OverloadExpr node, if we succeded in matching
3019 // exactly one of the candidate functions.
3020 if (OE)
3021 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003022
3023 // If we didn't find a matching function Expr in the __builtin_overload list
3024 // the return an error.
3025 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003026 for (unsigned i = 0; i != NumParams; ++i) {
3027 if (i != 0) typeNames += ", ";
3028 typeNames += Args[i+1]->getType().getAsString();
3029 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003030
3031 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3032 SourceRange(BuiltinLoc, RParenLoc));
3033}
3034
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003035Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3036 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003037 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003038 Expr *E = static_cast<Expr*>(expr);
3039 QualType T = QualType::getFromOpaquePtr(type);
3040
3041 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003042
3043 // Get the va_list type
3044 QualType VaListType = Context.getBuiltinVaListType();
3045 // Deal with implicit array decay; for example, on x86-64,
3046 // va_list is an array, but it's supposed to decay to
3047 // a pointer for va_arg.
3048 if (VaListType->isArrayType())
3049 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003050 // Make sure the input expression also decays appropriately.
3051 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003052
3053 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003054 return Diag(E->getLocStart(),
3055 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3056 E->getType().getAsString(),
3057 E->getSourceRange());
3058
3059 // FIXME: Warn if a non-POD type is passed in.
3060
3061 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3062}
3063
Chris Lattner5cf216b2008-01-04 18:04:52 +00003064bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3065 SourceLocation Loc,
3066 QualType DstType, QualType SrcType,
3067 Expr *SrcExpr, const char *Flavor) {
3068 // Decode the result (notice that AST's are still created for extensions).
3069 bool isInvalid = false;
3070 unsigned DiagKind;
3071 switch (ConvTy) {
3072 default: assert(0 && "Unknown conversion type");
3073 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003074 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003075 DiagKind = diag::ext_typecheck_convert_pointer_int;
3076 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003077 case IntToPointer:
3078 DiagKind = diag::ext_typecheck_convert_int_pointer;
3079 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003080 case IncompatiblePointer:
3081 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3082 break;
3083 case FunctionVoidPointer:
3084 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3085 break;
3086 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003087 // If the qualifiers lost were because we were applying the
3088 // (deprecated) C++ conversion from a string literal to a char*
3089 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3090 // Ideally, this check would be performed in
3091 // CheckPointerTypesForAssignment. However, that would require a
3092 // bit of refactoring (so that the second argument is an
3093 // expression, rather than a type), which should be done as part
3094 // of a larger effort to fix CheckPointerTypesForAssignment for
3095 // C++ semantics.
3096 if (getLangOptions().CPlusPlus &&
3097 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3098 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003099 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3100 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003101 case IntToBlockPointer:
3102 DiagKind = diag::err_int_to_block_pointer;
3103 break;
3104 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003105 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003106 break;
3107 case BlockVoidPointer:
3108 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3109 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003110 case Incompatible:
3111 DiagKind = diag::err_typecheck_convert_incompatible;
3112 isInvalid = true;
3113 break;
3114 }
3115
3116 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3117 SrcExpr->getSourceRange());
3118 return isInvalid;
3119}