blob: 070db2b5b9f81ec1d97c1e30a955b2e5be205b34 [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
Chris Lattner639e2d32008-10-20 05:16:36 +0000312/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
313/// CurBlock to VD should cause it to be snapshotted (as we do for auto
314/// variables defined outside the block) or false if this is not needed (e.g.
315/// for values inside the block or for globals).
316///
317/// FIXME: This will create BlockDeclRefExprs for global variables,
318/// function references, etc which is suboptimal :) and breaks
319/// things like "integer constant expression" tests.
320static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
321 ValueDecl *VD) {
322 // If the value is defined inside the block, we couldn't snapshot it even if
323 // we wanted to.
324 if (CurBlock->TheDecl == VD->getDeclContext())
325 return false;
326
327 // If this is an enum constant or function, it is constant, don't snapshot.
328 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
329 return false;
330
331 // If this is a reference to an extern, static, or global variable, no need to
332 // snapshot it.
333 // FIXME: What about 'const' variables in C++?
334 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
335 return Var->hasLocalStorage();
336
337 return true;
338}
339
340
341
Steve Naroff08d92e42007-09-15 18:49:24 +0000342/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000343/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000344/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000345Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 IdentifierInfo &II,
347 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000348 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000349 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000350
351 // If this reference is in an Objective-C method, then ivar lookup happens as
352 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000353 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000354 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000355 // There are two cases to handle here. 1) scoped lookup could have failed,
356 // in which case we should look for an ivar. 2) scoped lookup could have
357 // found a decl, but that decl is outside the current method (i.e. a global
358 // variable). In these two cases, we do a lookup for an ivar with this
359 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000360 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000361 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000362 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000363 // FIXME: This should use a new expr for a direct reference, don't turn
364 // this into Self->ivar, just return a BareIVarExpr or something.
365 IdentifierInfo &II = Context.Idents.get("self");
366 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
367 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
368 static_cast<Expr*>(SelfExpr.Val), true, true);
369 }
370 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000371 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000372 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000373 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000374 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000375 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000376 }
Chris Lattner8a934232008-03-31 00:36:02 +0000377 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 if (D == 0) {
379 // Otherwise, this could be an implicitly declared function reference (legal
380 // in C90, extension in C99).
381 if (HasTrailingLParen &&
Chris Lattner8a934232008-03-31 00:36:02 +0000382 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 D = ImplicitlyDefineFunction(Loc, II, S);
384 else {
385 // If this name wasn't predeclared and if this is not a function call,
386 // diagnose the problem.
387 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
388 }
389 }
Chris Lattner8a934232008-03-31 00:36:02 +0000390
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000391 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
392 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
393 if (MD->isStatic())
394 // "invalid use of member 'x' in static member function"
395 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
396 FD->getName());
397 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
398 // "invalid use of nonstatic data member 'x'"
399 return Diag(Loc, diag::err_invalid_non_static_member_use,
400 FD->getName());
401
402 if (FD->isInvalidDecl())
403 return true;
404
Argyrios Kyrtzidis90b7bc62008-10-22 21:00:29 +0000405 return new DeclRefExpr(FD, FD->getType(), Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000406 }
407
408 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
409 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 if (isa<TypedefDecl>(D))
411 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000412 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000413 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000414 if (isa<NamespaceDecl>(D))
415 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000416
Steve Naroffdd972f22008-09-05 22:11:13 +0000417 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000418 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
419 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
420
Steve Naroffdd972f22008-09-05 22:11:13 +0000421 ValueDecl *VD = cast<ValueDecl>(D);
422
423 // check if referencing an identifier with __attribute__((deprecated)).
424 if (VD->getAttr<DeprecatedAttr>())
425 Diag(Loc, diag::warn_deprecated, VD->getName());
426
427 // Only create DeclRefExpr's for valid Decl's.
428 if (VD->isInvalidDecl())
429 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000430
431 // If the identifier reference is inside a block, and it refers to a value
432 // that is outside the block, create a BlockDeclRefExpr instead of a
433 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
434 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000435 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000436 // We do not do this for things like enum constants, global variables, etc,
437 // as they do not get snapshotted.
438 //
439 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000440 // The BlocksAttr indicates the variable is bound by-reference.
441 if (VD->getAttr<BlocksAttr>())
442 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
443
444 // Variable will be bound by-copy, make it const within the closure.
445 VD->getType().addConst();
446 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
447 }
448 // If this reference is not in a block or if the referenced variable is
449 // within the block, create a normal DeclRefExpr.
Douglas Gregore0a5d5f2008-10-22 04:14:44 +0000450 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000451}
452
Chris Lattnerd9f69102008-08-10 01:53:14 +0000453Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000454 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000455 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000458 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000459 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
460 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
461 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000463
464 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000465 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000466 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000467
Chris Lattnerfa28b302008-01-12 08:14:25 +0000468 // Pre-defined identifiers are of type char[x], where x is the length of the
469 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000470 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000471 if (getCurFunctionDecl())
472 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000473 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000474 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000475
Chris Lattner8f978d52008-01-12 19:32:28 +0000476 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000477 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000478 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000479 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480}
481
Steve Narofff69936d2007-09-16 03:34:24 +0000482Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 llvm::SmallString<16> CharBuffer;
484 CharBuffer.resize(Tok.getLength());
485 const char *ThisTokBegin = &CharBuffer[0];
486 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
487
488 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
489 Tok.getLocation(), PP);
490 if (Literal.hadError())
491 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000492
493 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
494
Chris Lattnerc250aae2008-06-07 22:35:38 +0000495 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
496 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000497}
498
Steve Narofff69936d2007-09-16 03:34:24 +0000499Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 // fast path for a single digit (which is quite common). A single digit
501 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
502 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000503 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000504
Chris Lattner98be4942008-03-05 18:54:05 +0000505 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000506 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 Context.IntTy,
508 Tok.getLocation()));
509 }
510 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000511 // Add padding so that NumericLiteralParser can overread by one character.
512 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 const char *ThisTokBegin = &IntegerBuffer[0];
514
515 // Get the spelling of the token, which eliminates trigraphs, etc.
516 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000517
Reid Spencer5f016e22007-07-11 17:01:13 +0000518 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
519 Tok.getLocation(), PP);
520 if (Literal.hadError)
521 return ExprResult(true);
522
Chris Lattner5d661452007-08-26 03:42:43 +0000523 Expr *Res;
524
525 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000526 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000528 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000529 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000530 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000531 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000532 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000533
534 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
535
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000536 // isExact will be set by GetFloatValue().
537 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000538 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000539 Ty, Tok.getLocation());
540
Chris Lattner5d661452007-08-26 03:42:43 +0000541 } else if (!Literal.isIntegerLiteral()) {
542 return ExprResult(true);
543 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000544 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000545
Neil Boothb9449512007-08-29 22:00:19 +0000546 // long long is a C99 feature.
547 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000548 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000549 Diag(Tok.getLocation(), diag::ext_longlong);
550
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000552 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000553
554 if (Literal.GetIntegerValue(ResultVal)) {
555 // If this value didn't fit into uintmax_t, warn and force to ull.
556 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000557 Ty = Context.UnsignedLongLongTy;
558 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000559 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 } else {
561 // If this value fits into a ULL, try to figure out what else it fits into
562 // according to the rules of C99 6.4.4.1p5.
563
564 // Octal, Hexadecimal, and integers with a U suffix are allowed to
565 // be an unsigned int.
566 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
567
568 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000569 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000570 if (!Literal.isLong && !Literal.isLongLong) {
571 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000572 unsigned IntSize = Context.Target.getIntWidth();
573
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 // Does it fit in a unsigned int?
575 if (ResultVal.isIntN(IntSize)) {
576 // Does it fit in a signed int?
577 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000578 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000580 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000581 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 }
584
585 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000586 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000587 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000588
589 // Does it fit in a unsigned long?
590 if (ResultVal.isIntN(LongSize)) {
591 // Does it fit in a signed long?
592 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000593 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000595 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000596 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 }
599
600 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000601 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000602 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000603
604 // Does it fit in a unsigned long long?
605 if (ResultVal.isIntN(LongLongSize)) {
606 // Does it fit in a signed long long?
607 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000608 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000610 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000611 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 }
613 }
614
615 // If we still couldn't decide a type, we probably have something that
616 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000617 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000619 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000620 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000622
623 if (ResultVal.getBitWidth() != Width)
624 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
626
Chris Lattnerf0467b32008-04-02 04:24:33 +0000627 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 }
Chris Lattner5d661452007-08-26 03:42:43 +0000629
630 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
631 if (Literal.isImaginary)
632 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
633
634 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000635}
636
Steve Narofff69936d2007-09-16 03:34:24 +0000637Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000639 Expr *E = (Expr *)Val;
640 assert((E != 0) && "ActOnParenExpr() missing expr");
641 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000642}
643
644/// The UsualUnaryConversions() function is *not* called by this routine.
645/// See C99 6.3.2.1p[2-4] for more details.
646QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000647 SourceLocation OpLoc,
648 const SourceRange &ExprRange,
649 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 // C99 6.5.3.4p1:
651 if (isa<FunctionType>(exprType) && isSizeof)
652 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000653 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000655 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
656 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 else if (exprType->isIncompleteType()) {
658 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
659 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000660 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 return QualType(); // error
662 }
663 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
664 return Context.getSizeType();
665}
666
667Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000668ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 SourceLocation LPLoc, TypeTy *Ty,
670 SourceLocation RPLoc) {
671 // If error parsing type, ignore.
672 if (Ty == 0) return true;
673
674 // Verify that this is a valid expression.
675 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
676
Chris Lattnerbb280a42008-07-25 21:45:37 +0000677 QualType resultType =
678 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000679
680 if (resultType.isNull())
681 return true;
682 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
683}
684
Chris Lattner5d794252007-08-24 21:41:10 +0000685QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000686 DefaultFunctionArrayConversion(V);
687
Chris Lattnercc26ed72007-08-26 05:39:26 +0000688 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000689 if (const ComplexType *CT = V->getType()->getAsComplexType())
690 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000691
692 // Otherwise they pass through real integer and floating point types here.
693 if (V->getType()->isArithmeticType())
694 return V->getType();
695
696 // Reject anything else.
697 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
698 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000699}
700
701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702
Steve Narofff69936d2007-09-16 03:34:24 +0000703Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 tok::TokenKind Kind,
705 ExprTy *Input) {
706 UnaryOperator::Opcode Opc;
707 switch (Kind) {
708 default: assert(0 && "Unknown unary op!");
709 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
710 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
711 }
712 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
713 if (result.isNull())
714 return true;
715 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
716}
717
718Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000719ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000721 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000722
723 // Perform default conversions.
724 DefaultFunctionArrayConversion(LHSExp);
725 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000726
Chris Lattner12d9ff62007-07-16 00:14:47 +0000727 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000728
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000730 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // in the subscript position. As a result, we need to derive the array base
732 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000733 Expr *BaseExpr, *IndexExpr;
734 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000735 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000736 BaseExpr = LHSExp;
737 IndexExpr = RHSExp;
738 // FIXME: need to deal with const...
739 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000740 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000741 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000742 BaseExpr = RHSExp;
743 IndexExpr = LHSExp;
744 // FIXME: need to deal with const...
745 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000746 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
747 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000748 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000749
750 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000751 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
752 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000753 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000754 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000755 // FIXME: need to deal with const...
756 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000758 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
759 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 }
761 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000762 if (!IndexExpr->getType()->isIntegerType())
763 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
764 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000765
Chris Lattner12d9ff62007-07-16 00:14:47 +0000766 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
767 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000768 // void (*)(int)) and pointers to incomplete types. Functions are not
769 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000770 if (!ResultType->isObjectType())
771 return Diag(BaseExpr->getLocStart(),
772 diag::err_typecheck_subscript_not_object,
773 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
774
775 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000776}
777
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000778QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000779CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000780 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000781 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000782
783 // This flag determines whether or not the component is to be treated as a
784 // special name, or a regular GLSL-style component access.
785 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000786
787 // The vector accessor can't exceed the number of elements.
788 const char *compStr = CompName.getName();
789 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000790 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000791 baseType.getAsString(), SourceRange(CompLoc));
792 return QualType();
793 }
Nate Begeman8a997642008-05-09 06:41:27 +0000794
795 // Check that we've found one of the special components, or that the component
796 // names must come from the same set.
797 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
798 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
799 SpecialComponent = true;
800 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000801 do
802 compStr++;
803 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
804 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
805 do
806 compStr++;
807 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
808 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
809 do
810 compStr++;
811 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
812 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000813
Nate Begeman8a997642008-05-09 06:41:27 +0000814 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000815 // We didn't get to the end of the string. This means the component names
816 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000817 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000818 std::string(compStr,compStr+1), SourceRange(CompLoc));
819 return QualType();
820 }
821 // Each component accessor can't exceed the vector type.
822 compStr = CompName.getName();
823 while (*compStr) {
824 if (vecType->isAccessorWithinNumElements(*compStr))
825 compStr++;
826 else
827 break;
828 }
Nate Begeman8a997642008-05-09 06:41:27 +0000829 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000830 // We didn't get to the end of the string. This means a component accessor
831 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000832 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000833 baseType.getAsString(), SourceRange(CompLoc));
834 return QualType();
835 }
Nate Begeman8a997642008-05-09 06:41:27 +0000836
837 // If we have a special component name, verify that the current vector length
838 // is an even number, since all special component names return exactly half
839 // the elements.
840 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbarabee2d72008-09-30 17:22:47 +0000841 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
842 baseType.getAsString(), SourceRange(CompLoc));
Nate Begeman8a997642008-05-09 06:41:27 +0000843 return QualType();
844 }
845
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000846 // The component accessor looks fine - now we need to compute the actual type.
847 // The vector type is implied by the component accessor. For example,
848 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000849 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
850 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
851 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000852 if (CompSize == 1)
853 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000854
Nate Begeman213541a2008-04-18 23:10:10 +0000855 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000856 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000857 // diagostics look bad. We want extended vector types to appear built-in.
858 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
859 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
860 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000861 }
862 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000863}
864
Daniel Dunbar2307d312008-09-03 01:05:41 +0000865/// constructSetterName - Return the setter name for the given
866/// identifier, i.e. "set" + Name where the initial character of Name
867/// has been capitalized.
868// FIXME: Merge with same routine in Parser. But where should this
869// live?
870static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
871 const IdentifierInfo *Name) {
872 unsigned N = Name->getLength();
873 char *SelectorName = new char[3 + N];
874 memcpy(SelectorName, "set", 3);
875 memcpy(&SelectorName[3], Name->getName(), N);
876 SelectorName[3] = toupper(SelectorName[3]);
877
878 IdentifierInfo *Setter =
879 &Idents.get(SelectorName, &SelectorName[3 + N]);
880 delete[] SelectorName;
881 return Setter;
882}
883
Reid Spencer5f016e22007-07-11 17:01:13 +0000884Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000885ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 tok::TokenKind OpKind, SourceLocation MemberLoc,
887 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000888 Expr *BaseExpr = static_cast<Expr *>(Base);
889 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000890
891 // Perform default conversions.
892 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000893
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000894 QualType BaseType = BaseExpr->getType();
895 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000896
Chris Lattner68a057b2008-07-21 04:36:39 +0000897 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
898 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000900 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000901 BaseType = PT->getPointeeType();
902 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000903 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
904 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000906
Chris Lattner68a057b2008-07-21 04:36:39 +0000907 // Handle field access to simple records. This also handles access to fields
908 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000909 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000910 RecordDecl *RDecl = RTy->getDecl();
911 if (RTy->isIncompleteType())
912 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
913 BaseExpr->getSourceRange());
914 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000915 FieldDecl *MemberDecl = RDecl->getMember(&Member);
916 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000917 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
918 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000919
920 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000921 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000922 QualType MemberType = MemberDecl->getType();
923 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000924 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000925 MemberType = MemberType.getQualifiedType(combinedQualifiers);
926
Chris Lattner68a057b2008-07-21 04:36:39 +0000927 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000928 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000929 }
930
Chris Lattnera38e6b12008-07-21 04:59:05 +0000931 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
932 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000933 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
934 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000935 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000936 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000937 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000938 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000939 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000940 }
941
Chris Lattnera38e6b12008-07-21 04:59:05 +0000942 // Handle Objective-C property access, which is "Obj.property" where Obj is a
943 // pointer to a (potentially qualified) interface type.
944 const PointerType *PTy;
945 const ObjCInterfaceType *IFTy;
946 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
947 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
948 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000949
Daniel Dunbar2307d312008-09-03 01:05:41 +0000950 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000951 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
952 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
953
Daniel Dunbar2307d312008-09-03 01:05:41 +0000954 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000955 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
956 E = IFTy->qual_end(); I != E; ++I)
957 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
958 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000959
960 // If that failed, look for an "implicit" property by seeing if the nullary
961 // selector is implemented.
962
963 // FIXME: The logic for looking up nullary and unary selectors should be
964 // shared with the code in ActOnInstanceMessage.
965
966 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
967 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
968
969 // If this reference is in an @implementation, check for 'private' methods.
970 if (!Getter)
971 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
972 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
973 if (ObjCImplementationDecl *ImpDecl =
974 ObjCImplementations[ClassDecl->getIdentifier()])
975 Getter = ImpDecl->getInstanceMethod(Sel);
976
Steve Naroff7692ed62008-10-22 19:16:27 +0000977 // Look through local category implementations associated with the class.
978 if (!Getter) {
979 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
980 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
981 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
982 }
983 }
Daniel Dunbar2307d312008-09-03 01:05:41 +0000984 if (Getter) {
985 // If we found a getter then this may be a valid dot-reference, we
986 // need to also look for the matching setter.
987 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
988 &Member);
989 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
990 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
991
992 if (!Setter) {
993 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
994 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
995 if (ObjCImplementationDecl *ImpDecl =
996 ObjCImplementations[ClassDecl->getIdentifier()])
997 Setter = ImpDecl->getInstanceMethod(SetterSel);
998 }
999
1000 // FIXME: There are some issues here. First, we are not
1001 // diagnosing accesses to read-only properties because we do not
1002 // know if this is a getter or setter yet. Second, we are
1003 // checking that the type of the setter matches the type we
1004 // expect.
1005 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1006 MemberLoc, BaseExpr);
1007 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001008 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001009 // Handle properties on qualified "id" protocols.
1010 const ObjCQualifiedIdType *QIdTy;
1011 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1012 // Check protocols on qualified interfaces.
1013 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1014 E = QIdTy->qual_end(); I != E; ++I)
1015 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1016 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1017 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001018 // Handle 'field access' to vectors, such as 'V.xx'.
1019 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1020 // Component access limited to variables (reject vec4.rg.g).
1021 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1022 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +00001023 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1024 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001025 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1026 if (ret.isNull())
1027 return true;
1028 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1029 }
1030
Chris Lattner2a01b722008-07-21 05:35:34 +00001031 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1032 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001033}
1034
Steve Narofff69936d2007-09-16 03:34:24 +00001035/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001036/// This provides the location of the left/right parens and a list of comma
1037/// locations.
1038Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001039ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001040 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001041 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001042 Expr *Fn = static_cast<Expr *>(fn);
1043 Expr **Args = reinterpret_cast<Expr**>(args);
1044 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001045 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001046 OverloadedFunctionDecl *Ovl = NULL;
1047
1048 // If we're directly calling a function or a set of overloaded
1049 // functions, get the appropriate declaration.
1050 {
1051 DeclRefExpr *DRExpr = NULL;
1052 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1053 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1054 else
1055 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1056
1057 if (DRExpr) {
1058 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1059 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1060 }
1061 }
1062
1063 // If we have a set of overloaded functions, perform overload
1064 // resolution to pick the function.
1065 if (Ovl) {
1066 OverloadCandidateSet CandidateSet;
1067 OverloadCandidateSet::iterator Best;
1068 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1069 switch (BestViableFunction(CandidateSet, Best)) {
1070 case OR_Success:
1071 {
1072 // Success! Let the remainder of this function build a call to
1073 // the function selected by overload resolution.
1074 FDecl = Best->Function;
1075 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1076 Fn->getSourceRange().getBegin());
1077 delete Fn;
1078 Fn = NewFn;
1079 }
1080 break;
1081
1082 case OR_No_Viable_Function:
1083 if (CandidateSet.empty())
1084 Diag(Fn->getSourceRange().getBegin(),
1085 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1086 Fn->getSourceRange());
1087 else {
1088 Diag(Fn->getSourceRange().getBegin(),
1089 diag::err_ovl_no_viable_function_in_call_with_cands,
1090 Ovl->getName(), Fn->getSourceRange());
1091 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1092 }
1093 return true;
1094
1095 case OR_Ambiguous:
1096 Diag(Fn->getSourceRange().getBegin(),
1097 diag::err_ovl_ambiguous_call, Ovl->getName(),
1098 Fn->getSourceRange());
1099 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1100 return true;
1101 }
1102 }
Chris Lattner04421082008-04-08 04:40:51 +00001103
1104 // Promote the function operand.
1105 UsualUnaryConversions(Fn);
1106
Chris Lattner925e60d2007-12-28 05:29:59 +00001107 // Make the call expr early, before semantic checks. This guarantees cleanup
1108 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001109 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001110 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001111 const FunctionType *FuncT;
1112 if (!Fn->getType()->isBlockPointerType()) {
1113 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1114 // have type pointer to function".
1115 const PointerType *PT = Fn->getType()->getAsPointerType();
1116 if (PT == 0)
1117 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1118 Fn->getSourceRange());
1119 FuncT = PT->getPointeeType()->getAsFunctionType();
1120 } else { // This is a block call.
1121 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1122 getAsFunctionType();
1123 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001124 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001125 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1126 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001127
1128 // We know the result type of the call, set it.
1129 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001130
Chris Lattner925e60d2007-12-28 05:29:59 +00001131 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1133 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001134 unsigned NumArgsInProto = Proto->getNumArgs();
1135 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001136
Chris Lattner04421082008-04-08 04:40:51 +00001137 // If too few arguments are available (and we don't have default
1138 // arguments for the remaining parameters), don't make the call.
1139 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001140 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001141 // Use default arguments for missing arguments
1142 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001143 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001144 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001145 return Diag(RParenLoc,
1146 !Fn->getType()->isBlockPointerType()
1147 ? diag::err_typecheck_call_too_few_args
1148 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001149 Fn->getSourceRange());
1150 }
1151
Chris Lattner925e60d2007-12-28 05:29:59 +00001152 // If too many are passed and not variadic, error on the extras and drop
1153 // them.
1154 if (NumArgs > NumArgsInProto) {
1155 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001156 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001157 !Fn->getType()->isBlockPointerType()
1158 ? diag::err_typecheck_call_too_many_args
1159 : diag::err_typecheck_block_too_many_args,
1160 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001161 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001162 Args[NumArgs-1]->getLocEnd()));
1163 // This deletes the extra arguments.
1164 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 }
1166 NumArgsToCheck = NumArgsInProto;
1167 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001168
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001170 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001171 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001172
1173 Expr *Arg;
1174 if (i < NumArgs)
1175 Arg = Args[i];
1176 else
1177 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001178 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001179
Chris Lattner925e60d2007-12-28 05:29:59 +00001180 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001181 AssignConvertType ConvTy =
1182 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001183 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001184
Chris Lattner5cf216b2008-01-04 18:04:52 +00001185 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1186 ArgType, Arg, "passing"))
1187 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001189
1190 // If this is a variadic call, handle args passed through "...".
1191 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001192 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001193 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1194 Expr *Arg = Args[i];
1195 DefaultArgumentPromotion(Arg);
1196 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001197 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001198 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001199 } else {
1200 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1201
Steve Naroffb291ab62007-08-28 23:30:39 +00001202 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001203 for (unsigned i = 0; i != NumArgs; i++) {
1204 Expr *Arg = Args[i];
1205 DefaultArgumentPromotion(Arg);
1206 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001207 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001209
Chris Lattner59907c42007-08-10 20:18:51 +00001210 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001211 if (FDecl)
1212 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001213
Chris Lattner925e60d2007-12-28 05:29:59 +00001214 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001215}
1216
1217Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001218ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001219 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001220 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001221 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001222 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001223 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001224 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001225
Eli Friedman6223c222008-05-20 05:22:08 +00001226 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001227 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001228 return Diag(LParenLoc,
1229 diag::err_variable_object_no_init,
1230 SourceRange(LParenLoc,
1231 literalExpr->getSourceRange().getEnd()));
1232 } else if (literalType->isIncompleteType()) {
1233 return Diag(LParenLoc,
1234 diag::err_typecheck_decl_incomplete_type,
1235 literalType.getAsString(),
1236 SourceRange(LParenLoc,
1237 literalExpr->getSourceRange().getEnd()));
1238 }
1239
Steve Naroffd0091aa2008-01-10 22:15:12 +00001240 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001241 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001242
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001243 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001244 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001245 if (CheckForConstantInitializer(literalExpr, literalType))
1246 return true;
1247 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001248 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001249}
1250
1251Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001252ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001253 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001254 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001255
Steve Naroff08d92e42007-09-15 18:49:24 +00001256 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001257 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001258
Chris Lattnerf0467b32008-04-02 04:24:33 +00001259 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1260 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1261 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001262}
1263
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001264/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001265bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001266 UsualUnaryConversions(castExpr);
1267
1268 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1269 // type needs to be scalar.
1270 if (castType->isVoidType()) {
1271 // Cast to void allows any expr type.
1272 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1273 // GCC struct/union extension: allow cast to self.
1274 if (Context.getCanonicalType(castType) !=
1275 Context.getCanonicalType(castExpr->getType()) ||
1276 (!castType->isStructureType() && !castType->isUnionType())) {
1277 // Reject any other conversions to non-scalar types.
1278 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1279 castType.getAsString(), castExpr->getSourceRange());
1280 }
1281
1282 // accept this, but emit an ext-warn.
1283 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1284 castType.getAsString(), castExpr->getSourceRange());
1285 } else if (!castExpr->getType()->isScalarType() &&
1286 !castExpr->getType()->isVectorType()) {
1287 return Diag(castExpr->getLocStart(),
1288 diag::err_typecheck_expect_scalar_operand,
1289 castExpr->getType().getAsString(),castExpr->getSourceRange());
1290 } else if (castExpr->getType()->isVectorType()) {
1291 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1292 return true;
1293 } else if (castType->isVectorType()) {
1294 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1295 return true;
1296 }
1297 return false;
1298}
1299
Chris Lattnerfe23e212007-12-20 00:44:32 +00001300bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001301 assert(VectorTy->isVectorType() && "Not a vector type!");
1302
1303 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001304 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001305 return Diag(R.getBegin(),
1306 Ty->isVectorType() ?
1307 diag::err_invalid_conversion_between_vectors :
1308 diag::err_invalid_conversion_between_vector_and_integer,
1309 VectorTy.getAsString().c_str(),
1310 Ty.getAsString().c_str(), R);
1311 } else
1312 return Diag(R.getBegin(),
1313 diag::err_invalid_conversion_between_vector_and_scalar,
1314 VectorTy.getAsString().c_str(),
1315 Ty.getAsString().c_str(), R);
1316
1317 return false;
1318}
1319
Steve Naroff4aa88f82007-07-19 01:06:55 +00001320Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001321ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001323 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001324
1325 Expr *castExpr = static_cast<Expr*>(Op);
1326 QualType castType = QualType::getFromOpaquePtr(Ty);
1327
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001328 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1329 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001330 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001331}
1332
Chris Lattnera21ddb32007-11-26 01:40:58 +00001333/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1334/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001335inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001336 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001337 UsualUnaryConversions(cond);
1338 UsualUnaryConversions(lex);
1339 UsualUnaryConversions(rex);
1340 QualType condT = cond->getType();
1341 QualType lexT = lex->getType();
1342 QualType rexT = rex->getType();
1343
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001345 if (!condT->isScalarType()) { // C99 6.5.15p2
1346 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1347 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 return QualType();
1349 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001350
1351 // Now check the two expressions.
1352
1353 // If both operands have arithmetic type, do the usual arithmetic conversions
1354 // to find a common type: C99 6.5.15p3,5.
1355 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001356 UsualArithmeticConversions(lex, rex);
1357 return lex->getType();
1358 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001359
1360 // If both operands are the same structure or union type, the result is that
1361 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001362 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001363 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001364 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001365 // "If both the operands have structure or union type, the result has
1366 // that type." This implies that CV qualifiers are dropped.
1367 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001369
1370 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001371 // The following || allows only one side to be void (a GCC-ism).
1372 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001373 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001374 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1375 rex->getSourceRange());
1376 if (!rexT->isVoidType())
1377 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001378 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001379 ImpCastExprToType(lex, Context.VoidTy);
1380 ImpCastExprToType(rex, Context.VoidTy);
1381 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001382 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001383 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1384 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001385 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1386 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001387 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001388 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001389 return lexT;
1390 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001391 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1392 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001393 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001394 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001395 return rexT;
1396 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001397 // Handle the case where both operands are pointers before we handle null
1398 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001399 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1400 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1401 // get the "pointed to" types
1402 QualType lhptee = LHSPT->getPointeeType();
1403 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001404
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001405 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1406 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001407 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001408 // Figure out necessary qualifiers (C99 6.5.15p6)
1409 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001410 QualType destType = Context.getPointerType(destPointee);
1411 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1412 ImpCastExprToType(rex, destType); // promote to void*
1413 return destType;
1414 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001415 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001416 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001417 QualType destType = Context.getPointerType(destPointee);
1418 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1419 ImpCastExprToType(rex, destType); // promote to void*
1420 return destType;
1421 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001422
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001423 QualType compositeType = lexT;
1424
1425 // If either type is an Objective-C object type then check
1426 // compatibility according to Objective-C.
1427 if (Context.isObjCObjectPointerType(lexT) ||
1428 Context.isObjCObjectPointerType(rexT)) {
1429 // If both operands are interfaces and either operand can be
1430 // assigned to the other, use that type as the composite
1431 // type. This allows
1432 // xxx ? (A*) a : (B*) b
1433 // where B is a subclass of A.
1434 //
1435 // Additionally, as for assignment, if either type is 'id'
1436 // allow silent coercion. Finally, if the types are
1437 // incompatible then make sure to use 'id' as the composite
1438 // type so the result is acceptable for sending messages to.
1439
1440 // FIXME: This code should not be localized to here. Also this
1441 // should use a compatible check instead of abusing the
1442 // canAssignObjCInterfaces code.
1443 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1444 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1445 if (LHSIface && RHSIface &&
1446 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1447 compositeType = lexT;
1448 } else if (LHSIface && RHSIface &&
1449 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1450 compositeType = rexT;
1451 } else if (Context.isObjCIdType(lhptee) ||
1452 Context.isObjCIdType(rhptee)) {
1453 // FIXME: This code looks wrong, because isObjCIdType checks
1454 // the struct but getObjCIdType returns the pointer to
1455 // struct. This is horrible and should be fixed.
1456 compositeType = Context.getObjCIdType();
1457 } else {
1458 QualType incompatTy = Context.getObjCIdType();
1459 ImpCastExprToType(lex, incompatTy);
1460 ImpCastExprToType(rex, incompatTy);
1461 return incompatTy;
1462 }
1463 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1464 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001465 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001466 lexT.getAsString(), rexT.getAsString(),
1467 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001468 // In this situation, we assume void* type. No especially good
1469 // reason, but this is what gcc does, and we do have to pick
1470 // to get a consistent AST.
1471 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001472 ImpCastExprToType(lex, incompatTy);
1473 ImpCastExprToType(rex, incompatTy);
1474 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001475 }
1476 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001477 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1478 // differently qualified versions of compatible types, the result type is
1479 // a pointer to an appropriately qualified version of the *composite*
1480 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001481 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001482 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001483 ImpCastExprToType(lex, compositeType);
1484 ImpCastExprToType(rex, compositeType);
1485 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 }
1487 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001488 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1489 // evaluates to "struct objc_object *" (and is handled above when comparing
1490 // id with statically typed objects).
1491 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1492 // GCC allows qualified id and any Objective-C type to devolve to
1493 // id. Currently localizing to here until clear this should be
1494 // part of ObjCQualifiedIdTypesAreCompatible.
1495 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1496 (lexT->isObjCQualifiedIdType() &&
1497 Context.isObjCObjectPointerType(rexT)) ||
1498 (rexT->isObjCQualifiedIdType() &&
1499 Context.isObjCObjectPointerType(lexT))) {
1500 // FIXME: This is not the correct composite type. This only
1501 // happens to work because id can more or less be used anywhere,
1502 // however this may change the type of method sends.
1503 // FIXME: gcc adds some type-checking of the arguments and emits
1504 // (confusing) incompatible comparison warnings in some
1505 // cases. Investigate.
1506 QualType compositeType = Context.getObjCIdType();
1507 ImpCastExprToType(lex, compositeType);
1508 ImpCastExprToType(rex, compositeType);
1509 return compositeType;
1510 }
1511 }
1512
Steve Naroff61f40a22008-09-10 19:17:48 +00001513 // Selection between block pointer types is ok as long as they are the same.
1514 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1515 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1516 return lexT;
1517
Chris Lattner70d67a92008-01-06 22:42:25 +00001518 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001520 lexT.getAsString(), rexT.getAsString(),
1521 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 return QualType();
1523}
1524
Steve Narofff69936d2007-09-16 03:34:24 +00001525/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001526/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001527Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 SourceLocation ColonLoc,
1529 ExprTy *Cond, ExprTy *LHS,
1530 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001531 Expr *CondExpr = (Expr *) Cond;
1532 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001533
1534 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1535 // was the condition.
1536 bool isLHSNull = LHSExpr == 0;
1537 if (isLHSNull)
1538 LHSExpr = CondExpr;
1539
Chris Lattner26824902007-07-16 21:39:03 +00001540 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1541 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 if (result.isNull())
1543 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001544 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1545 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001546}
1547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548
1549// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1550// being closely modeled after the C99 spec:-). The odd characteristic of this
1551// routine is it effectively iqnores the qualifiers on the top level pointee.
1552// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1553// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001554Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001555Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1556 QualType lhptee, rhptee;
1557
1558 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001559 lhptee = lhsType->getAsPointerType()->getPointeeType();
1560 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001561
1562 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001563 lhptee = Context.getCanonicalType(lhptee);
1564 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001565
Chris Lattner5cf216b2008-01-04 18:04:52 +00001566 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567
1568 // C99 6.5.16.1p1: This following citation is common to constraints
1569 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1570 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001571 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001572 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001573 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001574
1575 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1576 // incomplete type and the other is a pointer to a qualified or unqualified
1577 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001578 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001579 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001580 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001581
1582 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001583 assert(rhptee->isFunctionType());
1584 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001585 }
1586
1587 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001588 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001589 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001590
1591 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001592 assert(lhptee->isFunctionType());
1593 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001594 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001595
1596 // Check for ObjC interfaces
1597 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1598 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1599 if (LHSIface && RHSIface &&
1600 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1601 return ConvTy;
1602
1603 // ID acts sort of like void* for ObjC interfaces
1604 if (LHSIface && Context.isObjCIdType(rhptee))
1605 return ConvTy;
1606 if (RHSIface && Context.isObjCIdType(lhptee))
1607 return ConvTy;
1608
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1610 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001611 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1612 rhptee.getUnqualifiedType()))
1613 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001614 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001615}
1616
Steve Naroff1c7d0672008-09-04 15:10:53 +00001617/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1618/// block pointer types are compatible or whether a block and normal pointer
1619/// are compatible. It is more restrict than comparing two function pointer
1620// types.
1621Sema::AssignConvertType
1622Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1623 QualType rhsType) {
1624 QualType lhptee, rhptee;
1625
1626 // get the "pointed to" type (ignoring qualifiers at the top level)
1627 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1628 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1629
1630 // make sure we operate on the canonical type
1631 lhptee = Context.getCanonicalType(lhptee);
1632 rhptee = Context.getCanonicalType(rhptee);
1633
1634 AssignConvertType ConvTy = Compatible;
1635
1636 // For blocks we enforce that qualifiers are identical.
1637 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1638 ConvTy = CompatiblePointerDiscardsQualifiers;
1639
1640 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1641 return IncompatibleBlockPointer;
1642 return ConvTy;
1643}
1644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1646/// has code to accommodate several GCC extensions when type checking
1647/// pointers. Here are some objectionable examples that GCC considers warnings:
1648///
1649/// int a, *pint;
1650/// short *pshort;
1651/// struct foo *pfoo;
1652///
1653/// pint = pshort; // warning: assignment from incompatible pointer type
1654/// a = pint; // warning: assignment makes integer from pointer without a cast
1655/// pint = a; // warning: assignment makes pointer from integer without a cast
1656/// pint = pfoo; // warning: assignment from incompatible pointer type
1657///
1658/// As a result, the code for dealing with pointers is more complex than the
1659/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001660///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001661Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001662Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001663 // Get canonical types. We're not formatting these types, just comparing
1664 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001665 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1666 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001667
1668 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001669 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001670
Anders Carlsson793680e2007-10-12 23:56:29 +00001671 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001672 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001673 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001674 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001675 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001676
Chris Lattnereca7be62008-04-07 05:30:13 +00001677 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1678 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001679 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001680 // Relax integer conversions like we do for pointers below.
1681 if (rhsType->isIntegerType())
1682 return IntToPointer;
1683 if (lhsType->isIntegerType())
1684 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001685 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001686 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001687
Nate Begemanbe2341d2008-07-14 18:02:46 +00001688 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001689 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001690 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1691 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001692 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001693
Nate Begemanbe2341d2008-07-14 18:02:46 +00001694 // If we are allowing lax vector conversions, and LHS and RHS are both
1695 // vectors, the total size only needs to be the same. This is a bitcast;
1696 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001697 if (getLangOptions().LaxVectorConversions &&
1698 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001699 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1700 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001701 }
1702 return Incompatible;
1703 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001704
Chris Lattnere8b3e962008-01-04 23:32:24 +00001705 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001707
Chris Lattner78eca282008-04-07 06:49:41 +00001708 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001710 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001711
Chris Lattner78eca282008-04-07 06:49:41 +00001712 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001714
Steve Naroffb4406862008-09-29 18:10:17 +00001715 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001716 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001717 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001718
1719 // Treat block pointers as objects.
1720 if (getLangOptions().ObjC1 &&
1721 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1722 return Compatible;
1723 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001724 return Incompatible;
1725 }
1726
1727 if (isa<BlockPointerType>(lhsType)) {
1728 if (rhsType->isIntegerType())
1729 return IntToPointer;
1730
Steve Naroffb4406862008-09-29 18:10:17 +00001731 // Treat block pointers as objects.
1732 if (getLangOptions().ObjC1 &&
1733 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1734 return Compatible;
1735
Steve Naroff1c7d0672008-09-04 15:10:53 +00001736 if (rhsType->isBlockPointerType())
1737 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1738
1739 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1740 if (RHSPT->getPointeeType()->isVoidType())
1741 return BlockVoidPointer;
1742 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001743 return Incompatible;
1744 }
1745
Chris Lattner78eca282008-04-07 06:49:41 +00001746 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001748 if (lhsType == Context.BoolTy)
1749 return Compatible;
1750
1751 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001752 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001753
Chris Lattner78eca282008-04-07 06:49:41 +00001754 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001756
1757 if (isa<BlockPointerType>(lhsType) &&
1758 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1759 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001760 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001761 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001762
Chris Lattnerfc144e22008-01-04 23:18:45 +00001763 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001764 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 }
1767 return Incompatible;
1768}
1769
Chris Lattner5cf216b2008-01-04 18:04:52 +00001770Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001771Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001772 if (getLangOptions().CPlusPlus) {
1773 if (!lhsType->isRecordType()) {
1774 // C++ 5.17p3: If the left operand is not of class type, the
1775 // expression is implicitly converted (C++ 4) to the
1776 // cv-unqualified type of the left operand.
1777 ImplicitConversionSequence ICS
1778 = TryCopyInitialization(rExpr, lhsType.getUnqualifiedType());
1779 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
1780 // No implicit conversion available; we cannot perform this
1781 // assignment.
1782 return Incompatible;
1783 } else {
1784 // Perform the appropriate cast to the right-handle side.
1785 ImpCastExprToType(rExpr, lhsType.getUnqualifiedType());
1786 return Compatible;
1787 }
1788 }
1789
1790 // FIXME: Currently, we fall through and treat C++ classes like C
1791 // structures.
1792 }
1793
Steve Naroff529a4ad2007-11-27 17:58:44 +00001794 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1795 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001796 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1797 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001798 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001799 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001800 return Compatible;
1801 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001802
1803 // We don't allow conversion of non-null-pointer constants to integers.
1804 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1805 return IntToBlockPointer;
1806
Chris Lattner943140e2007-10-16 02:55:40 +00001807 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001808 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001809 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001810 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001811 //
1812 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1813 // are better understood.
1814 if (!lhsType->isReferenceType())
1815 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001816
Chris Lattner5cf216b2008-01-04 18:04:52 +00001817 Sema::AssignConvertType result =
1818 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001819
1820 // C99 6.5.16.1p2: The value of the right operand is converted to the
1821 // type of the assignment expression.
1822 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001823 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001824 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001825}
1826
Chris Lattner5cf216b2008-01-04 18:04:52 +00001827Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001828Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1829 return CheckAssignmentConstraints(lhsType, rhsType);
1830}
1831
Chris Lattnerca5eede2007-12-12 05:47:28 +00001832QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 Diag(loc, diag::err_typecheck_invalid_operands,
1834 lex->getType().getAsString(), rex->getType().getAsString(),
1835 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001836 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001837}
1838
Steve Naroff49b45262007-07-13 16:58:59 +00001839inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1840 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001841 // For conversion purposes, we ignore any qualifiers.
1842 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001843 QualType lhsType =
1844 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1845 QualType rhsType =
1846 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001847
Nate Begemanbe2341d2008-07-14 18:02:46 +00001848 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001849 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001851
Nate Begemanbe2341d2008-07-14 18:02:46 +00001852 // Handle the case of a vector & extvector type of the same size and element
1853 // type. It would be nice if we only had one vector type someday.
1854 if (getLangOptions().LaxVectorConversions)
1855 if (const VectorType *LV = lhsType->getAsVectorType())
1856 if (const VectorType *RV = rhsType->getAsVectorType())
1857 if (LV->getElementType() == RV->getElementType() &&
1858 LV->getNumElements() == RV->getNumElements())
1859 return lhsType->isExtVectorType() ? lhsType : rhsType;
1860
1861 // If the lhs is an extended vector and the rhs is a scalar of the same type
1862 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001863 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001864 QualType eltType = V->getElementType();
1865
1866 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1867 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1868 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001869 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001870 return lhsType;
1871 }
1872 }
1873
Nate Begemanbe2341d2008-07-14 18:02:46 +00001874 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001875 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001876 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001877 QualType eltType = V->getElementType();
1878
1879 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1880 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1881 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001882 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001883 return rhsType;
1884 }
1885 }
1886
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 // You cannot convert between vector values of different size.
1888 Diag(loc, diag::err_typecheck_vector_not_convertable,
1889 lex->getType().getAsString(), rex->getType().getAsString(),
1890 lex->getSourceRange(), rex->getSourceRange());
1891 return QualType();
1892}
1893
1894inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001895 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001896{
Steve Naroff90045e82007-07-13 23:32:42 +00001897 QualType lhsType = lex->getType(), rhsType = rex->getType();
1898
1899 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001901
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001902 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001903
Steve Naroffa4332e22007-07-17 00:58:39 +00001904 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001905 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001906 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001907}
1908
1909inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001910 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001911{
Steve Naroff90045e82007-07-13 23:32:42 +00001912 QualType lhsType = lex->getType(), rhsType = rex->getType();
1913
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001914 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001915
Steve Naroffa4332e22007-07-17 00:58:39 +00001916 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001917 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001918 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001919}
1920
1921inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001922 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001923{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001924 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001925 return CheckVectorOperands(loc, lex, rex);
1926
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001927 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001928
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001930 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001931 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001932
Eli Friedmand72d16e2008-05-18 18:08:51 +00001933 // Put any potential pointer into PExp
1934 Expr* PExp = lex, *IExp = rex;
1935 if (IExp->getType()->isPointerType())
1936 std::swap(PExp, IExp);
1937
1938 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1939 if (IExp->getType()->isIntegerType()) {
1940 // Check for arithmetic on pointers to incomplete types
1941 if (!PTy->getPointeeType()->isObjectType()) {
1942 if (PTy->getPointeeType()->isVoidType()) {
1943 Diag(loc, diag::ext_gnu_void_ptr,
1944 lex->getSourceRange(), rex->getSourceRange());
1945 } else {
1946 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1947 lex->getType().getAsString(), lex->getSourceRange());
1948 return QualType();
1949 }
1950 }
1951 return PExp->getType();
1952 }
1953 }
1954
Chris Lattnerca5eede2007-12-12 05:47:28 +00001955 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001956}
1957
Chris Lattnereca7be62008-04-07 05:30:13 +00001958// C99 6.5.6
1959QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1960 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001961 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001963
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001964 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001965
Chris Lattner6e4ab612007-12-09 21:53:25 +00001966 // Enforce type constraints: C99 6.5.6p3.
1967
1968 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001969 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001970 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001971
1972 // Either ptr - int or ptr - ptr.
1973 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001974 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001975
Chris Lattner6e4ab612007-12-09 21:53:25 +00001976 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001977 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001978 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001979 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001980 Diag(loc, diag::ext_gnu_void_ptr,
1981 lex->getSourceRange(), rex->getSourceRange());
1982 } else {
1983 Diag(loc, diag::err_typecheck_sub_ptr_object,
1984 lex->getType().getAsString(), lex->getSourceRange());
1985 return QualType();
1986 }
1987 }
1988
1989 // The result type of a pointer-int computation is the pointer type.
1990 if (rex->getType()->isIntegerType())
1991 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001992
Chris Lattner6e4ab612007-12-09 21:53:25 +00001993 // Handle pointer-pointer subtractions.
1994 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001995 QualType rpointee = RHSPTy->getPointeeType();
1996
Chris Lattner6e4ab612007-12-09 21:53:25 +00001997 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001998 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001999 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002000 if (rpointee->isVoidType()) {
2001 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00002002 Diag(loc, diag::ext_gnu_void_ptr,
2003 lex->getSourceRange(), rex->getSourceRange());
2004 } else {
2005 Diag(loc, diag::err_typecheck_sub_ptr_object,
2006 rex->getType().getAsString(), rex->getSourceRange());
2007 return QualType();
2008 }
2009 }
2010
2011 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002012 if (!Context.typesAreCompatible(
2013 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2014 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002015 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2016 lex->getType().getAsString(), rex->getType().getAsString(),
2017 lex->getSourceRange(), rex->getSourceRange());
2018 return QualType();
2019 }
2020
2021 return Context.getPointerDiffType();
2022 }
2023 }
2024
Chris Lattnerca5eede2007-12-12 05:47:28 +00002025 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002026}
2027
Chris Lattnereca7be62008-04-07 05:30:13 +00002028// C99 6.5.7
2029QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2030 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002031 // C99 6.5.7p2: Each of the operands shall have integer type.
2032 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2033 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002034
Chris Lattnerca5eede2007-12-12 05:47:28 +00002035 // Shifts don't perform usual arithmetic conversions, they just do integer
2036 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002037 if (!isCompAssign)
2038 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002039 UsualUnaryConversions(rex);
2040
2041 // "The type of the result is that of the promoted left operand."
2042 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002043}
2044
Eli Friedman3d815e72008-08-22 00:56:42 +00002045static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2046 ASTContext& Context) {
2047 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2048 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2049 // ID acts sort of like void* for ObjC interfaces
2050 if (LHSIface && Context.isObjCIdType(RHS))
2051 return true;
2052 if (RHSIface && Context.isObjCIdType(LHS))
2053 return true;
2054 if (!LHSIface || !RHSIface)
2055 return false;
2056 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2057 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2058}
2059
Chris Lattnereca7be62008-04-07 05:30:13 +00002060// C99 6.5.8
2061QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2062 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002063 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2064 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2065
Chris Lattnera5937dd2007-08-26 01:18:55 +00002066 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002067 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2068 UsualArithmeticConversions(lex, rex);
2069 else {
2070 UsualUnaryConversions(lex);
2071 UsualUnaryConversions(rex);
2072 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002073 QualType lType = lex->getType();
2074 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002075
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002076 // For non-floating point types, check for self-comparisons of the form
2077 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2078 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002079 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002080 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2081 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002082 if (DRL->getDecl() == DRR->getDecl())
2083 Diag(loc, diag::warn_selfcomparison);
2084 }
2085
Chris Lattnera5937dd2007-08-26 01:18:55 +00002086 if (isRelational) {
2087 if (lType->isRealType() && rType->isRealType())
2088 return Context.IntTy;
2089 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002090 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002091 if (lType->isFloatingType()) {
2092 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002093 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002094 }
2095
Chris Lattnera5937dd2007-08-26 01:18:55 +00002096 if (lType->isArithmeticType() && rType->isArithmeticType())
2097 return Context.IntTy;
2098 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002099
Chris Lattnerd28f8152007-08-26 01:10:14 +00002100 bool LHSIsNull = lex->isNullPointerConstant(Context);
2101 bool RHSIsNull = rex->isNullPointerConstant(Context);
2102
Chris Lattnera5937dd2007-08-26 01:18:55 +00002103 // All of the following pointer related warnings are GCC extensions, except
2104 // when handling null pointer constants. One day, we can consider making them
2105 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002106 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002107 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002108 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002109 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002110 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002111
Steve Naroff66296cb2007-11-13 14:57:38 +00002112 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002113 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2114 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002115 RCanPointeeTy.getUnqualifiedType()) &&
2116 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002117 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2118 lType.getAsString(), rType.getAsString(),
2119 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002121 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002122 return Context.IntTy;
2123 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002124 // Handle block pointer types.
2125 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2126 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2127 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2128
2129 if (!LHSIsNull && !RHSIsNull &&
2130 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2131 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2132 lType.getAsString(), rType.getAsString(),
2133 lex->getSourceRange(), rex->getSourceRange());
2134 }
2135 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2136 return Context.IntTy;
2137 }
Steve Naroff59f53942008-09-28 01:11:11 +00002138 // Allow block pointers to be compared with null pointer constants.
2139 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2140 (lType->isPointerType() && rType->isBlockPointerType())) {
2141 if (!LHSIsNull && !RHSIsNull) {
2142 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2143 lType.getAsString(), rType.getAsString(),
2144 lex->getSourceRange(), rex->getSourceRange());
2145 }
2146 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2147 return Context.IntTy;
2148 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002149
Steve Naroff20373222008-06-03 14:04:54 +00002150 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff87f3b932008-10-20 18:19:10 +00002151 if ((lType->isPointerType() || rType->isPointerType()) &&
2152 !Context.typesAreCompatible(lType, rType)) {
2153 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2154 lType.getAsString(), rType.getAsString(),
2155 lex->getSourceRange(), rex->getSourceRange());
2156 return QualType();
2157 }
Steve Naroff20373222008-06-03 14:04:54 +00002158 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2159 ImpCastExprToType(rex, lType);
2160 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002161 } else {
2162 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2163 Diag(loc, diag::warn_incompatible_qualified_id_operands,
2164 lex->getType().getAsString(), rex->getType().getAsString(),
2165 lex->getSourceRange(), rex->getSourceRange());
2166 return QualType();
2167 }
Steve Naroff20373222008-06-03 14:04:54 +00002168 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002169 }
Steve Naroff20373222008-06-03 14:04:54 +00002170 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2171 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002172 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002173 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2174 lType.getAsString(), rType.getAsString(),
2175 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002176 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002177 return Context.IntTy;
2178 }
Steve Naroff20373222008-06-03 14:04:54 +00002179 if (lType->isIntegerType() &&
2180 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002181 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002182 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2183 lType.getAsString(), rType.getAsString(),
2184 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002185 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002186 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 }
Steve Naroff39218df2008-09-04 16:56:14 +00002188 // Handle block pointers.
2189 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2190 if (!RHSIsNull)
2191 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2192 lType.getAsString(), rType.getAsString(),
2193 lex->getSourceRange(), rex->getSourceRange());
2194 ImpCastExprToType(rex, lType); // promote the integer to pointer
2195 return Context.IntTy;
2196 }
2197 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2198 if (!LHSIsNull)
2199 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2200 lType.getAsString(), rType.getAsString(),
2201 lex->getSourceRange(), rex->getSourceRange());
2202 ImpCastExprToType(lex, rType); // promote the integer to pointer
2203 return Context.IntTy;
2204 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002205 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002206}
2207
Nate Begemanbe2341d2008-07-14 18:02:46 +00002208/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2209/// operates on extended vector types. Instead of producing an IntTy result,
2210/// like a scalar comparison, a vector comparison produces a vector of integer
2211/// types.
2212QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2213 SourceLocation loc,
2214 bool isRelational) {
2215 // Check to make sure we're operating on vectors of the same type and width,
2216 // Allowing one side to be a scalar of element type.
2217 QualType vType = CheckVectorOperands(loc, lex, rex);
2218 if (vType.isNull())
2219 return vType;
2220
2221 QualType lType = lex->getType();
2222 QualType rType = rex->getType();
2223
2224 // For non-floating point types, check for self-comparisons of the form
2225 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2226 // often indicate logic errors in the program.
2227 if (!lType->isFloatingType()) {
2228 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2229 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2230 if (DRL->getDecl() == DRR->getDecl())
2231 Diag(loc, diag::warn_selfcomparison);
2232 }
2233
2234 // Check for comparisons of floating point operands using != and ==.
2235 if (!isRelational && lType->isFloatingType()) {
2236 assert (rType->isFloatingType());
2237 CheckFloatComparison(loc,lex,rex);
2238 }
2239
2240 // Return the type for the comparison, which is the same as vector type for
2241 // integer vectors, or an integer type of identical size and number of
2242 // elements for floating point vectors.
2243 if (lType->isIntegerType())
2244 return lType;
2245
2246 const VectorType *VTy = lType->getAsVectorType();
2247
2248 // FIXME: need to deal with non-32b int / non-64b long long
2249 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2250 if (TypeSize == 32) {
2251 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2252 }
2253 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2254 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2255}
2256
Reid Spencer5f016e22007-07-11 17:01:13 +00002257inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002258 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002259{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002260 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002262
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002263 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002264
Steve Naroffa4332e22007-07-17 00:58:39 +00002265 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002266 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002267 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002268}
2269
2270inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002271 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002272{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002273 UsualUnaryConversions(lex);
2274 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002275
Eli Friedman5773a6c2008-05-13 20:16:47 +00002276 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002278 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002279}
2280
2281inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002282 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002283{
2284 QualType lhsType = lex->getType();
2285 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002286 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002287
2288 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002289 case Expr::MLV_Valid:
2290 break;
2291 case Expr::MLV_ConstQualified:
2292 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2293 return QualType();
2294 case Expr::MLV_ArrayType:
2295 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2296 lhsType.getAsString(), lex->getSourceRange());
2297 return QualType();
2298 case Expr::MLV_NotObjectType:
2299 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2300 lhsType.getAsString(), lex->getSourceRange());
2301 return QualType();
2302 case Expr::MLV_InvalidExpression:
2303 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2304 lex->getSourceRange());
2305 return QualType();
2306 case Expr::MLV_IncompleteType:
2307 case Expr::MLV_IncompleteVoidType:
2308 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2309 lhsType.getAsString(), lex->getSourceRange());
2310 return QualType();
2311 case Expr::MLV_DuplicateVectorComponents:
2312 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2313 lex->getSourceRange());
2314 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002315 case Expr::MLV_NotBlockQualified:
2316 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2317 lex->getSourceRange());
2318 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002320
Chris Lattner5cf216b2008-01-04 18:04:52 +00002321 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002322 if (compoundType.isNull()) {
2323 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002324 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002325
2326 // If the RHS is a unary plus or minus, check to see if they = and + are
2327 // right next to each other. If so, the user may have typo'd "x =+ 4"
2328 // instead of "x += 4".
2329 Expr *RHSCheck = rex;
2330 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2331 RHSCheck = ICE->getSubExpr();
2332 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2333 if ((UO->getOpcode() == UnaryOperator::Plus ||
2334 UO->getOpcode() == UnaryOperator::Minus) &&
2335 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2336 // Only if the two operators are exactly adjacent.
2337 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2338 Diag(loc, diag::warn_not_compound_assign,
2339 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2340 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2341 }
2342 } else {
2343 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002344 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002345 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002346
2347 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2348 rex, "assigning"))
2349 return QualType();
2350
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 // C99 6.5.16p3: The type of an assignment expression is the type of the
2352 // left operand unless the left operand has qualified type, in which case
2353 // it is the unqualified version of the type of the left operand.
2354 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2355 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002356 // C++ 5.17p1: the type of the assignment expression is that of its left
2357 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002358 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002359}
2360
2361inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002362 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002363
2364 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2365 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002366 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002367}
2368
Steve Naroff49b45262007-07-13 16:58:59 +00002369/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2370/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002371QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002372 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 assert(!resType.isNull() && "no type for increment/decrement expression");
2374
Steve Naroff084f9ed2007-08-24 17:20:07 +00002375 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002376 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002377 if (pt->getPointeeType()->isVoidType()) {
2378 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2379 } else if (!pt->getPointeeType()->isObjectType()) {
2380 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002381 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2382 resType.getAsString(), op->getSourceRange());
2383 return QualType();
2384 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002385 } else if (!resType->isRealType()) {
2386 if (resType->isComplexType())
2387 // C99 does not support ++/-- on complex types.
2388 Diag(OpLoc, diag::ext_integer_increment_complex,
2389 resType.getAsString(), op->getSourceRange());
2390 else {
2391 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2392 resType.getAsString(), op->getSourceRange());
2393 return QualType();
2394 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002396 // At this point, we know we have a real, complex or pointer type.
2397 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002398 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 if (mlval != Expr::MLV_Valid) {
2400 // FIXME: emit a more precise diagnostic...
2401 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2402 op->getSourceRange());
2403 return QualType();
2404 }
2405 return resType;
2406}
2407
Anders Carlsson369dee42008-02-01 07:15:58 +00002408/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002409/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002410/// where the declaration is needed for type checking. We only need to
2411/// handle cases when the expression references a function designator
2412/// or is an lvalue. Here are some examples:
2413/// - &(x) => x
2414/// - &*****f => f for f a function designator.
2415/// - &s.xx => s
2416/// - &s.zz[1].yy -> s, if zz is an array
2417/// - *(x + 1) -> x, if x is an array
2418/// - &"123"[2] -> 0
2419/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002420static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002421 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002423 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002425 // Fields cannot be declared with a 'register' storage class.
2426 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002427 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002428 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002429 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002430 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002431 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002432
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002433 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002434 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002435 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002436 return 0;
2437 else
2438 return VD;
2439 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002440 case Stmt::UnaryOperatorClass: {
2441 UnaryOperator *UO = cast<UnaryOperator>(E);
2442
2443 switch(UO->getOpcode()) {
2444 case UnaryOperator::Deref: {
2445 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002446 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2447 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2448 if (!VD || VD->getType()->isPointerType())
2449 return 0;
2450 return VD;
2451 }
2452 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002453 }
2454 case UnaryOperator::Real:
2455 case UnaryOperator::Imag:
2456 case UnaryOperator::Extension:
2457 return getPrimaryDecl(UO->getSubExpr());
2458 default:
2459 return 0;
2460 }
2461 }
2462 case Stmt::BinaryOperatorClass: {
2463 BinaryOperator *BO = cast<BinaryOperator>(E);
2464
2465 // Handle cases involving pointer arithmetic. The result of an
2466 // Assign or AddAssign is not an lvalue so they can be ignored.
2467
2468 // (x + n) or (n + x) => x
2469 if (BO->getOpcode() == BinaryOperator::Add) {
2470 if (BO->getLHS()->getType()->isPointerType()) {
2471 return getPrimaryDecl(BO->getLHS());
2472 } else if (BO->getRHS()->getType()->isPointerType()) {
2473 return getPrimaryDecl(BO->getRHS());
2474 }
2475 }
2476
2477 return 0;
2478 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002480 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002481 case Stmt::ImplicitCastExprClass:
2482 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002483 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 default:
2485 return 0;
2486 }
2487}
2488
2489/// CheckAddressOfOperand - The operand of & must be either a function
2490/// designator or an lvalue designating an object. If it is an lvalue, the
2491/// object cannot be declared with storage class register or be a bit field.
2492/// Note: The usual conversions are *not* applied to the operand of the &
2493/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2494QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002495 if (getLangOptions().C99) {
2496 // Implement C99-only parts of addressof rules.
2497 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2498 if (uOp->getOpcode() == UnaryOperator::Deref)
2499 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2500 // (assuming the deref expression is valid).
2501 return uOp->getSubExpr()->getType();
2502 }
2503 // Technically, there should be a check for array subscript
2504 // expressions here, but the result of one is always an lvalue anyway.
2505 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002506 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002507 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002508
2509 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002510 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2511 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2513 op->getSourceRange());
2514 return QualType();
2515 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002516 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2517 if (MemExpr->getMemberDecl()->isBitField()) {
2518 Diag(OpLoc, diag::err_typecheck_address_of,
2519 std::string("bit-field"), op->getSourceRange());
2520 return QualType();
2521 }
2522 // Check for Apple extension for accessing vector components.
2523 } else if (isa<ArraySubscriptExpr>(op) &&
2524 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2525 Diag(OpLoc, diag::err_typecheck_address_of,
2526 std::string("vector"), op->getSourceRange());
2527 return QualType();
2528 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 // We have an lvalue with a decl. Make sure the decl is not declared
2530 // with the register storage-class specifier.
2531 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2532 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002533 Diag(OpLoc, diag::err_typecheck_address_of,
2534 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 return QualType();
2536 }
2537 } else
2538 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002540
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 // If the operand has type "type", the result has type "pointer to type".
2542 return Context.getPointerType(op->getType());
2543}
2544
2545QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002546 UsualUnaryConversions(op);
2547 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002548
Chris Lattnerbefee482007-07-31 16:53:04 +00002549 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002550 // Note that per both C89 and C99, this is always legal, even
2551 // if ptype is an incomplete type or void.
2552 // It would be possible to warn about dereferencing a
2553 // void pointer, but it's completely well-defined,
2554 // and such a warning is unlikely to catch any mistakes.
2555 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 }
2557 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2558 qType.getAsString(), op->getSourceRange());
2559 return QualType();
2560}
2561
2562static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2563 tok::TokenKind Kind) {
2564 BinaryOperator::Opcode Opc;
2565 switch (Kind) {
2566 default: assert(0 && "Unknown binop!");
2567 case tok::star: Opc = BinaryOperator::Mul; break;
2568 case tok::slash: Opc = BinaryOperator::Div; break;
2569 case tok::percent: Opc = BinaryOperator::Rem; break;
2570 case tok::plus: Opc = BinaryOperator::Add; break;
2571 case tok::minus: Opc = BinaryOperator::Sub; break;
2572 case tok::lessless: Opc = BinaryOperator::Shl; break;
2573 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2574 case tok::lessequal: Opc = BinaryOperator::LE; break;
2575 case tok::less: Opc = BinaryOperator::LT; break;
2576 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2577 case tok::greater: Opc = BinaryOperator::GT; break;
2578 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2579 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2580 case tok::amp: Opc = BinaryOperator::And; break;
2581 case tok::caret: Opc = BinaryOperator::Xor; break;
2582 case tok::pipe: Opc = BinaryOperator::Or; break;
2583 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2584 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2585 case tok::equal: Opc = BinaryOperator::Assign; break;
2586 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2587 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2588 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2589 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2590 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2591 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2592 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2593 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2594 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2595 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2596 case tok::comma: Opc = BinaryOperator::Comma; break;
2597 }
2598 return Opc;
2599}
2600
2601static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2602 tok::TokenKind Kind) {
2603 UnaryOperator::Opcode Opc;
2604 switch (Kind) {
2605 default: assert(0 && "Unknown unary op!");
2606 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2607 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2608 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2609 case tok::star: Opc = UnaryOperator::Deref; break;
2610 case tok::plus: Opc = UnaryOperator::Plus; break;
2611 case tok::minus: Opc = UnaryOperator::Minus; break;
2612 case tok::tilde: Opc = UnaryOperator::Not; break;
2613 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2614 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2615 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2616 case tok::kw___real: Opc = UnaryOperator::Real; break;
2617 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2618 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2619 }
2620 return Opc;
2621}
2622
2623// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002624Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 ExprTy *LHS, ExprTy *RHS) {
2626 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2627 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2628
Steve Narofff69936d2007-09-16 03:34:24 +00002629 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2630 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002631
2632 QualType ResultTy; // Result type of the binary operator.
2633 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2634
2635 switch (Opc) {
2636 default:
2637 assert(0 && "Unknown binary expr!");
2638 case BinaryOperator::Assign:
2639 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2640 break;
2641 case BinaryOperator::Mul:
2642 case BinaryOperator::Div:
2643 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2644 break;
2645 case BinaryOperator::Rem:
2646 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2647 break;
2648 case BinaryOperator::Add:
2649 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2650 break;
2651 case BinaryOperator::Sub:
2652 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2653 break;
2654 case BinaryOperator::Shl:
2655 case BinaryOperator::Shr:
2656 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2657 break;
2658 case BinaryOperator::LE:
2659 case BinaryOperator::LT:
2660 case BinaryOperator::GE:
2661 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002662 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 break;
2664 case BinaryOperator::EQ:
2665 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002666 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 break;
2668 case BinaryOperator::And:
2669 case BinaryOperator::Xor:
2670 case BinaryOperator::Or:
2671 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2672 break;
2673 case BinaryOperator::LAnd:
2674 case BinaryOperator::LOr:
2675 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2676 break;
2677 case BinaryOperator::MulAssign:
2678 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002679 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 if (!CompTy.isNull())
2681 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2682 break;
2683 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002684 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 if (!CompTy.isNull())
2686 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2687 break;
2688 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002689 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 if (!CompTy.isNull())
2691 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2692 break;
2693 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002694 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 if (!CompTy.isNull())
2696 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2697 break;
2698 case BinaryOperator::ShlAssign:
2699 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002700 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 if (!CompTy.isNull())
2702 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2703 break;
2704 case BinaryOperator::AndAssign:
2705 case BinaryOperator::XorAssign:
2706 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002707 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 if (!CompTy.isNull())
2709 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2710 break;
2711 case BinaryOperator::Comma:
2712 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2713 break;
2714 }
2715 if (ResultTy.isNull())
2716 return true;
2717 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002718 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002719 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002720 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002721}
2722
2723// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002724Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 ExprTy *input) {
2726 Expr *Input = (Expr*)input;
2727 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2728 QualType resultType;
2729 switch (Opc) {
2730 default:
2731 assert(0 && "Unimplemented unary expr!");
2732 case UnaryOperator::PreInc:
2733 case UnaryOperator::PreDec:
2734 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2735 break;
2736 case UnaryOperator::AddrOf:
2737 resultType = CheckAddressOfOperand(Input, OpLoc);
2738 break;
2739 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002740 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 resultType = CheckIndirectionOperand(Input, OpLoc);
2742 break;
2743 case UnaryOperator::Plus:
2744 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002745 UsualUnaryConversions(Input);
2746 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2748 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2749 resultType.getAsString());
2750 break;
2751 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002752 UsualUnaryConversions(Input);
2753 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002754 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2755 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2756 // C99 does not support '~' for complex conjugation.
2757 Diag(OpLoc, diag::ext_integer_complement_complex,
2758 resultType.getAsString(), Input->getSourceRange());
2759 else if (!resultType->isIntegerType())
2760 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2761 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 break;
2763 case UnaryOperator::LNot: // logical negation
2764 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002765 DefaultFunctionArrayConversion(Input);
2766 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2768 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2769 resultType.getAsString());
2770 // LNot always has type int. C99 6.5.3.3p5.
2771 resultType = Context.IntTy;
2772 break;
2773 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002774 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2775 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 break;
2777 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002778 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2779 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002781 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002782 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002783 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002784 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 resultType = Input->getType();
2787 break;
2788 }
2789 if (resultType.isNull())
2790 return true;
2791 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2792}
2793
Steve Naroff1b273c42007-09-16 14:56:35 +00002794/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2795Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 SourceLocation LabLoc,
2797 IdentifierInfo *LabelII) {
2798 // Look up the record for this label identifier.
2799 LabelStmt *&LabelDecl = LabelMap[LabelII];
2800
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002801 // If we haven't seen this label yet, create a forward reference. It
2802 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 if (LabelDecl == 0)
2804 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2805
2806 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002807 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2808 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002809}
2810
Steve Naroff1b273c42007-09-16 14:56:35 +00002811Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002812 SourceLocation RPLoc) { // "({..})"
2813 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2814 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2815 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2816
2817 // FIXME: there are a variety of strange constraints to enforce here, for
2818 // example, it is not possible to goto into a stmt expression apparently.
2819 // More semantic analysis is needed.
2820
2821 // FIXME: the last statement in the compount stmt has its value used. We
2822 // should not warn about it being unused.
2823
2824 // If there are sub stmts in the compound stmt, take the type of the last one
2825 // as the type of the stmtexpr.
2826 QualType Ty = Context.VoidTy;
2827
Chris Lattner611b2ec2008-07-26 19:51:01 +00002828 if (!Compound->body_empty()) {
2829 Stmt *LastStmt = Compound->body_back();
2830 // If LastStmt is a label, skip down through into the body.
2831 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2832 LastStmt = Label->getSubStmt();
2833
2834 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002835 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002836 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002837
2838 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2839}
Steve Naroffd34e9152007-08-01 22:05:33 +00002840
Steve Naroff1b273c42007-09-16 14:56:35 +00002841Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002842 SourceLocation TypeLoc,
2843 TypeTy *argty,
2844 OffsetOfComponent *CompPtr,
2845 unsigned NumComponents,
2846 SourceLocation RPLoc) {
2847 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2848 assert(!ArgTy.isNull() && "Missing type argument!");
2849
2850 // We must have at least one component that refers to the type, and the first
2851 // one is known to be a field designator. Verify that the ArgTy represents
2852 // a struct/union/class.
2853 if (!ArgTy->isRecordType())
2854 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2855
2856 // Otherwise, create a compound literal expression as the base, and
2857 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002858 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002859
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002860 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2861 // GCC extension, diagnose them.
2862 if (NumComponents != 1)
2863 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2864 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2865
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002866 for (unsigned i = 0; i != NumComponents; ++i) {
2867 const OffsetOfComponent &OC = CompPtr[i];
2868 if (OC.isBrackets) {
2869 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002870 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002871 if (!AT) {
2872 delete Res;
2873 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2874 Res->getType().getAsString());
2875 }
2876
Chris Lattner704fe352007-08-30 17:59:59 +00002877 // FIXME: C++: Verify that operator[] isn't overloaded.
2878
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002879 // C99 6.5.2.1p1
2880 Expr *Idx = static_cast<Expr*>(OC.U.E);
2881 if (!Idx->getType()->isIntegerType())
2882 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2883 Idx->getSourceRange());
2884
2885 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2886 continue;
2887 }
2888
2889 const RecordType *RC = Res->getType()->getAsRecordType();
2890 if (!RC) {
2891 delete Res;
2892 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2893 Res->getType().getAsString());
2894 }
2895
2896 // Get the decl corresponding to this.
2897 RecordDecl *RD = RC->getDecl();
2898 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2899 if (!MemberDecl)
2900 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2901 OC.U.IdentInfo->getName(),
2902 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002903
2904 // FIXME: C++: Verify that MemberDecl isn't a static field.
2905 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002906 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2907 // matter here.
2908 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002909 }
2910
2911 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2912 BuiltinLoc);
2913}
2914
2915
Steve Naroff1b273c42007-09-16 14:56:35 +00002916Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002917 TypeTy *arg1, TypeTy *arg2,
2918 SourceLocation RPLoc) {
2919 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2920 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2921
2922 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2923
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002924 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002925}
2926
Steve Naroff1b273c42007-09-16 14:56:35 +00002927Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002928 ExprTy *expr1, ExprTy *expr2,
2929 SourceLocation RPLoc) {
2930 Expr *CondExpr = static_cast<Expr*>(cond);
2931 Expr *LHSExpr = static_cast<Expr*>(expr1);
2932 Expr *RHSExpr = static_cast<Expr*>(expr2);
2933
2934 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2935
2936 // The conditional expression is required to be a constant expression.
2937 llvm::APSInt condEval(32);
2938 SourceLocation ExpLoc;
2939 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2940 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2941 CondExpr->getSourceRange());
2942
2943 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2944 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2945 RHSExpr->getType();
2946 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2947}
2948
Steve Naroff4eb206b2008-09-03 18:15:37 +00002949//===----------------------------------------------------------------------===//
2950// Clang Extensions.
2951//===----------------------------------------------------------------------===//
2952
2953/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00002954void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002955 // Analyze block parameters.
2956 BlockSemaInfo *BSI = new BlockSemaInfo();
2957
2958 // Add BSI to CurBlock.
2959 BSI->PrevBlockInfo = CurBlock;
2960 CurBlock = BSI;
2961
2962 BSI->ReturnType = 0;
2963 BSI->TheScope = BlockScope;
2964
Steve Naroff090276f2008-10-10 01:28:17 +00002965 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2966 PushDeclContext(BSI->TheDecl);
2967}
2968
2969void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002970 // Analyze arguments to block.
2971 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2972 "Not a function declarator!");
2973 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2974
Steve Naroff090276f2008-10-10 01:28:17 +00002975 CurBlock->hasPrototype = FTI.hasPrototype;
2976 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002977
2978 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2979 // no arguments, not a function that takes a single void argument.
2980 if (FTI.hasPrototype &&
2981 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2982 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2983 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2984 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00002985 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002986 } else if (FTI.hasPrototype) {
2987 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00002988 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2989 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002990 }
Steve Naroff090276f2008-10-10 01:28:17 +00002991 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2992
2993 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2994 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2995 // If this has an identifier, add it to the scope stack.
2996 if ((*AI)->getIdentifier())
2997 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002998}
2999
3000/// ActOnBlockError - If there is an error parsing a block, this callback
3001/// is invoked to pop the information about the block from the action impl.
3002void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3003 // Ensure that CurBlock is deleted.
3004 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3005
3006 // Pop off CurBlock, handle nested blocks.
3007 CurBlock = CurBlock->PrevBlockInfo;
3008
3009 // FIXME: Delete the ParmVarDecl objects as well???
3010
3011}
3012
3013/// ActOnBlockStmtExpr - This is called when the body of a block statement
3014/// literal was successfully completed. ^(int x){...}
3015Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3016 Scope *CurScope) {
3017 // Ensure that CurBlock is deleted.
3018 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3019 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3020
Steve Naroff090276f2008-10-10 01:28:17 +00003021 PopDeclContext();
3022
Steve Naroff4eb206b2008-09-03 18:15:37 +00003023 // Pop off CurBlock, handle nested blocks.
3024 CurBlock = CurBlock->PrevBlockInfo;
3025
3026 QualType RetTy = Context.VoidTy;
3027 if (BSI->ReturnType)
3028 RetTy = QualType(BSI->ReturnType, 0);
3029
3030 llvm::SmallVector<QualType, 8> ArgTypes;
3031 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3032 ArgTypes.push_back(BSI->Params[i]->getType());
3033
3034 QualType BlockTy;
3035 if (!BSI->hasPrototype)
3036 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3037 else
3038 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
3039 BSI->isVariadic);
3040
3041 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003042
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003043 BSI->TheDecl->setBody(Body.take());
3044 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003045}
3046
Nate Begeman67295d02008-01-30 20:50:20 +00003047/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003048/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003049/// The number of arguments has already been validated to match the number of
3050/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003051static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3052 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003053 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003054 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003055 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3056 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003057
3058 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003059 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003060 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003061 return true;
3062}
3063
3064Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3065 SourceLocation *CommaLocs,
3066 SourceLocation BuiltinLoc,
3067 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003068 // __builtin_overload requires at least 2 arguments
3069 if (NumArgs < 2)
3070 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3071 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00003072
Nate Begemane2ce1d92008-01-17 17:46:27 +00003073 // The first argument is required to be a constant expression. It tells us
3074 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003075 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003076 Expr *NParamsExpr = Args[0];
3077 llvm::APSInt constEval(32);
3078 SourceLocation ExpLoc;
3079 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3080 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3081 NParamsExpr->getSourceRange());
3082
3083 // Verify that the number of parameters is > 0
3084 unsigned NumParams = constEval.getZExtValue();
3085 if (NumParams == 0)
3086 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3087 NParamsExpr->getSourceRange());
3088 // Verify that we have at least 1 + NumParams arguments to the builtin.
3089 if ((NumParams + 1) > NumArgs)
3090 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3091 SourceRange(BuiltinLoc, RParenLoc));
3092
3093 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003094 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003095 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003096 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3097 // UsualUnaryConversions will convert the function DeclRefExpr into a
3098 // pointer to function.
3099 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003100 const FunctionTypeProto *FnType = 0;
3101 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3102 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003103
3104 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3105 // parameters, and the number of parameters must match the value passed to
3106 // the builtin.
3107 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00003108 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3109 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00003110
3111 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003112 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003113 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003114 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003115 if (OE)
3116 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3117 OE->getFn()->getSourceRange());
3118 // Remember our match, and continue processing the remaining arguments
3119 // to catch any errors.
3120 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3121 BuiltinLoc, RParenLoc);
3122 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003123 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003124 // Return the newly created OverloadExpr node, if we succeded in matching
3125 // exactly one of the candidate functions.
3126 if (OE)
3127 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003128
3129 // If we didn't find a matching function Expr in the __builtin_overload list
3130 // the return an error.
3131 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003132 for (unsigned i = 0; i != NumParams; ++i) {
3133 if (i != 0) typeNames += ", ";
3134 typeNames += Args[i+1]->getType().getAsString();
3135 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003136
3137 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3138 SourceRange(BuiltinLoc, RParenLoc));
3139}
3140
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003141Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3142 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003143 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003144 Expr *E = static_cast<Expr*>(expr);
3145 QualType T = QualType::getFromOpaquePtr(type);
3146
3147 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003148
3149 // Get the va_list type
3150 QualType VaListType = Context.getBuiltinVaListType();
3151 // Deal with implicit array decay; for example, on x86-64,
3152 // va_list is an array, but it's supposed to decay to
3153 // a pointer for va_arg.
3154 if (VaListType->isArrayType())
3155 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003156 // Make sure the input expression also decays appropriately.
3157 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003158
3159 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003160 return Diag(E->getLocStart(),
3161 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3162 E->getType().getAsString(),
3163 E->getSourceRange());
3164
3165 // FIXME: Warn if a non-POD type is passed in.
3166
3167 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3168}
3169
Chris Lattner5cf216b2008-01-04 18:04:52 +00003170bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3171 SourceLocation Loc,
3172 QualType DstType, QualType SrcType,
3173 Expr *SrcExpr, const char *Flavor) {
3174 // Decode the result (notice that AST's are still created for extensions).
3175 bool isInvalid = false;
3176 unsigned DiagKind;
3177 switch (ConvTy) {
3178 default: assert(0 && "Unknown conversion type");
3179 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003180 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003181 DiagKind = diag::ext_typecheck_convert_pointer_int;
3182 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003183 case IntToPointer:
3184 DiagKind = diag::ext_typecheck_convert_int_pointer;
3185 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003186 case IncompatiblePointer:
3187 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3188 break;
3189 case FunctionVoidPointer:
3190 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3191 break;
3192 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003193 // If the qualifiers lost were because we were applying the
3194 // (deprecated) C++ conversion from a string literal to a char*
3195 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3196 // Ideally, this check would be performed in
3197 // CheckPointerTypesForAssignment. However, that would require a
3198 // bit of refactoring (so that the second argument is an
3199 // expression, rather than a type), which should be done as part
3200 // of a larger effort to fix CheckPointerTypesForAssignment for
3201 // C++ semantics.
3202 if (getLangOptions().CPlusPlus &&
3203 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3204 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003205 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3206 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003207 case IntToBlockPointer:
3208 DiagKind = diag::err_int_to_block_pointer;
3209 break;
3210 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003211 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003212 break;
3213 case BlockVoidPointer:
3214 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3215 break;
Steve Naroff39579072008-10-14 22:18:38 +00003216 case IncompatibleObjCQualifiedId:
3217 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3218 // it can give a more specific diagnostic.
3219 DiagKind = diag::warn_incompatible_qualified_id;
3220 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003221 case Incompatible:
3222 DiagKind = diag::err_typecheck_convert_incompatible;
3223 isInvalid = true;
3224 break;
3225 }
3226
3227 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3228 SrcExpr->getSourceRange());
3229 return isInvalid;
3230}