blob: 6fd1c5cc2fdd445439dcad557efe2c9fc4b5a224 [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 Kyrtzidis971c4fa2008-10-24 21:46:40 +0000405 // FIXME: Handle 'mutable'.
406 return new DeclRefExpr(FD,
407 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000408 }
409
410 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
411 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 if (isa<TypedefDecl>(D))
413 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000414 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000415 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000416 if (isa<NamespaceDecl>(D))
417 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000418
Steve Naroffdd972f22008-09-05 22:11:13 +0000419 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000420 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
421 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
422
Steve Naroffdd972f22008-09-05 22:11:13 +0000423 ValueDecl *VD = cast<ValueDecl>(D);
424
425 // check if referencing an identifier with __attribute__((deprecated)).
426 if (VD->getAttr<DeprecatedAttr>())
427 Diag(Loc, diag::warn_deprecated, VD->getName());
428
429 // Only create DeclRefExpr's for valid Decl's.
430 if (VD->isInvalidDecl())
431 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000432
433 // If the identifier reference is inside a block, and it refers to a value
434 // that is outside the block, create a BlockDeclRefExpr instead of a
435 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
436 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000437 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000438 // We do not do this for things like enum constants, global variables, etc,
439 // as they do not get snapshotted.
440 //
441 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000442 // The BlocksAttr indicates the variable is bound by-reference.
443 if (VD->getAttr<BlocksAttr>())
444 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
445
446 // Variable will be bound by-copy, make it const within the closure.
447 VD->getType().addConst();
448 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
449 }
450 // If this reference is not in a block or if the referenced variable is
451 // within the block, create a normal DeclRefExpr.
Douglas Gregore0a5d5f2008-10-22 04:14:44 +0000452 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000453}
454
Chris Lattnerd9f69102008-08-10 01:53:14 +0000455Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000456 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000457 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000458
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000460 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000461 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
462 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
463 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000465
466 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000467 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000468 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000469
Chris Lattnerfa28b302008-01-12 08:14:25 +0000470 // Pre-defined identifiers are of type char[x], where x is the length of the
471 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000472 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000473 if (getCurFunctionDecl())
474 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000475 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000476 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000477
Chris Lattner8f978d52008-01-12 19:32:28 +0000478 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000479 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000480 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000481 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000482}
483
Steve Narofff69936d2007-09-16 03:34:24 +0000484Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 llvm::SmallString<16> CharBuffer;
486 CharBuffer.resize(Tok.getLength());
487 const char *ThisTokBegin = &CharBuffer[0];
488 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
489
490 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
491 Tok.getLocation(), PP);
492 if (Literal.hadError())
493 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000494
495 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
496
Chris Lattnerc250aae2008-06-07 22:35:38 +0000497 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
498 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000499}
500
Steve Narofff69936d2007-09-16 03:34:24 +0000501Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 // fast path for a single digit (which is quite common). A single digit
503 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
504 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000505 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
Chris Lattner98be4942008-03-05 18:54:05 +0000507 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000508 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 Context.IntTy,
510 Tok.getLocation()));
511 }
512 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000513 // Add padding so that NumericLiteralParser can overread by one character.
514 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 const char *ThisTokBegin = &IntegerBuffer[0];
516
517 // Get the spelling of the token, which eliminates trigraphs, etc.
518 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
521 Tok.getLocation(), PP);
522 if (Literal.hadError)
523 return ExprResult(true);
524
Chris Lattner5d661452007-08-26 03:42:43 +0000525 Expr *Res;
526
527 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000528 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000529 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000530 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000531 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000532 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000533 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000534 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000535
536 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
537
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000538 // isExact will be set by GetFloatValue().
539 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000540 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000541 Ty, Tok.getLocation());
542
Chris Lattner5d661452007-08-26 03:42:43 +0000543 } else if (!Literal.isIntegerLiteral()) {
544 return ExprResult(true);
545 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000546 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000547
Neil Boothb9449512007-08-29 22:00:19 +0000548 // long long is a C99 feature.
549 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000550 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000551 Diag(Tok.getLocation(), diag::ext_longlong);
552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000554 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000555
556 if (Literal.GetIntegerValue(ResultVal)) {
557 // If this value didn't fit into uintmax_t, warn and force to ull.
558 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000559 Ty = Context.UnsignedLongLongTy;
560 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000561 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 } else {
563 // If this value fits into a ULL, try to figure out what else it fits into
564 // according to the rules of C99 6.4.4.1p5.
565
566 // Octal, Hexadecimal, and integers with a U suffix are allowed to
567 // be an unsigned int.
568 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
569
570 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000571 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000572 if (!Literal.isLong && !Literal.isLongLong) {
573 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000574 unsigned IntSize = Context.Target.getIntWidth();
575
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 // Does it fit in a unsigned int?
577 if (ResultVal.isIntN(IntSize)) {
578 // Does it fit in a signed int?
579 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000580 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000582 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000583 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 }
586
587 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000588 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000589 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000590
591 // Does it fit in a unsigned long?
592 if (ResultVal.isIntN(LongSize)) {
593 // Does it fit in a signed long?
594 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000595 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000597 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000598 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 }
601
602 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000603 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000604 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000605
606 // Does it fit in a unsigned long long?
607 if (ResultVal.isIntN(LongLongSize)) {
608 // Does it fit in a signed long long?
609 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000610 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000612 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000613 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 }
615 }
616
617 // If we still couldn't decide a type, we probably have something that
618 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000619 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000621 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000622 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000624
625 if (ResultVal.getBitWidth() != Width)
626 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 }
628
Chris Lattnerf0467b32008-04-02 04:24:33 +0000629 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 }
Chris Lattner5d661452007-08-26 03:42:43 +0000631
632 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
633 if (Literal.isImaginary)
634 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
635
636 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000637}
638
Steve Narofff69936d2007-09-16 03:34:24 +0000639Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000641 Expr *E = (Expr *)Val;
642 assert((E != 0) && "ActOnParenExpr() missing expr");
643 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000644}
645
646/// The UsualUnaryConversions() function is *not* called by this routine.
647/// See C99 6.3.2.1p[2-4] for more details.
648QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000649 SourceLocation OpLoc,
650 const SourceRange &ExprRange,
651 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 // C99 6.5.3.4p1:
653 if (isa<FunctionType>(exprType) && isSizeof)
654 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000655 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000657 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
658 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 else if (exprType->isIncompleteType()) {
660 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
661 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000662 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 return QualType(); // error
664 }
665 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
666 return Context.getSizeType();
667}
668
669Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000670ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 SourceLocation LPLoc, TypeTy *Ty,
672 SourceLocation RPLoc) {
673 // If error parsing type, ignore.
674 if (Ty == 0) return true;
675
676 // Verify that this is a valid expression.
677 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
678
Chris Lattnerbb280a42008-07-25 21:45:37 +0000679 QualType resultType =
680 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000681
682 if (resultType.isNull())
683 return true;
684 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
685}
686
Chris Lattner5d794252007-08-24 21:41:10 +0000687QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000688 DefaultFunctionArrayConversion(V);
689
Chris Lattnercc26ed72007-08-26 05:39:26 +0000690 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000691 if (const ComplexType *CT = V->getType()->getAsComplexType())
692 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000693
694 // Otherwise they pass through real integer and floating point types here.
695 if (V->getType()->isArithmeticType())
696 return V->getType();
697
698 // Reject anything else.
699 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
700 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000701}
702
703
Reid Spencer5f016e22007-07-11 17:01:13 +0000704
Steve Narofff69936d2007-09-16 03:34:24 +0000705Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 tok::TokenKind Kind,
707 ExprTy *Input) {
708 UnaryOperator::Opcode Opc;
709 switch (Kind) {
710 default: assert(0 && "Unknown unary op!");
711 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
712 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
713 }
714 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
715 if (result.isNull())
716 return true;
717 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
718}
719
720Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000721ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000723 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000724
725 // Perform default conversions.
726 DefaultFunctionArrayConversion(LHSExp);
727 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000728
Chris Lattner12d9ff62007-07-16 00:14:47 +0000729 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000732 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 // in the subscript position. As a result, we need to derive the array base
734 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000735 Expr *BaseExpr, *IndexExpr;
736 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000737 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000738 BaseExpr = LHSExp;
739 IndexExpr = RHSExp;
740 // FIXME: need to deal with const...
741 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000742 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000743 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000744 BaseExpr = RHSExp;
745 IndexExpr = LHSExp;
746 // FIXME: need to deal with const...
747 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000748 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
749 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000750 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000751
752 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000753 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
754 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000755 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000756 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000757 // FIXME: need to deal with const...
758 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000760 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
761 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 }
763 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000764 if (!IndexExpr->getType()->isIntegerType())
765 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
766 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000767
Chris Lattner12d9ff62007-07-16 00:14:47 +0000768 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
769 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000770 // void (*)(int)) and pointers to incomplete types. Functions are not
771 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000772 if (!ResultType->isObjectType())
773 return Diag(BaseExpr->getLocStart(),
774 diag::err_typecheck_subscript_not_object,
775 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
776
777 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778}
779
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000780QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000781CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000782 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000783 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000784
785 // This flag determines whether or not the component is to be treated as a
786 // special name, or a regular GLSL-style component access.
787 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000788
789 // The vector accessor can't exceed the number of elements.
790 const char *compStr = CompName.getName();
791 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000792 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000793 baseType.getAsString(), SourceRange(CompLoc));
794 return QualType();
795 }
Nate Begeman8a997642008-05-09 06:41:27 +0000796
797 // Check that we've found one of the special components, or that the component
798 // names must come from the same set.
799 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
800 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
801 SpecialComponent = true;
802 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000803 do
804 compStr++;
805 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
806 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
807 do
808 compStr++;
809 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
810 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
811 do
812 compStr++;
813 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
814 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000815
Nate Begeman8a997642008-05-09 06:41:27 +0000816 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000817 // We didn't get to the end of the string. This means the component names
818 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000819 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000820 std::string(compStr,compStr+1), SourceRange(CompLoc));
821 return QualType();
822 }
823 // Each component accessor can't exceed the vector type.
824 compStr = CompName.getName();
825 while (*compStr) {
826 if (vecType->isAccessorWithinNumElements(*compStr))
827 compStr++;
828 else
829 break;
830 }
Nate Begeman8a997642008-05-09 06:41:27 +0000831 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000832 // We didn't get to the end of the string. This means a component accessor
833 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000834 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000835 baseType.getAsString(), SourceRange(CompLoc));
836 return QualType();
837 }
Nate Begeman8a997642008-05-09 06:41:27 +0000838
839 // If we have a special component name, verify that the current vector length
840 // is an even number, since all special component names return exactly half
841 // the elements.
842 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbarabee2d72008-09-30 17:22:47 +0000843 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
844 baseType.getAsString(), SourceRange(CompLoc));
Nate Begeman8a997642008-05-09 06:41:27 +0000845 return QualType();
846 }
847
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000848 // The component accessor looks fine - now we need to compute the actual type.
849 // The vector type is implied by the component accessor. For example,
850 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000851 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
852 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
853 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000854 if (CompSize == 1)
855 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000856
Nate Begeman213541a2008-04-18 23:10:10 +0000857 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000858 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000859 // diagostics look bad. We want extended vector types to appear built-in.
860 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
861 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
862 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000863 }
864 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000865}
866
Daniel Dunbar2307d312008-09-03 01:05:41 +0000867/// constructSetterName - Return the setter name for the given
868/// identifier, i.e. "set" + Name where the initial character of Name
869/// has been capitalized.
870// FIXME: Merge with same routine in Parser. But where should this
871// live?
872static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
873 const IdentifierInfo *Name) {
874 unsigned N = Name->getLength();
875 char *SelectorName = new char[3 + N];
876 memcpy(SelectorName, "set", 3);
877 memcpy(&SelectorName[3], Name->getName(), N);
878 SelectorName[3] = toupper(SelectorName[3]);
879
880 IdentifierInfo *Setter =
881 &Idents.get(SelectorName, &SelectorName[3 + N]);
882 delete[] SelectorName;
883 return Setter;
884}
885
Reid Spencer5f016e22007-07-11 17:01:13 +0000886Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000887ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 tok::TokenKind OpKind, SourceLocation MemberLoc,
889 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000890 Expr *BaseExpr = static_cast<Expr *>(Base);
891 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000892
893 // Perform default conversions.
894 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000895
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000896 QualType BaseType = BaseExpr->getType();
897 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000898
Chris Lattner68a057b2008-07-21 04:36:39 +0000899 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
900 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000902 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000903 BaseType = PT->getPointeeType();
904 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000905 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
906 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000908
Chris Lattner68a057b2008-07-21 04:36:39 +0000909 // Handle field access to simple records. This also handles access to fields
910 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000911 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000912 RecordDecl *RDecl = RTy->getDecl();
913 if (RTy->isIncompleteType())
914 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
915 BaseExpr->getSourceRange());
916 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000917 FieldDecl *MemberDecl = RDecl->getMember(&Member);
918 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000919 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
920 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000921
922 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000923 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000924 QualType MemberType = MemberDecl->getType();
925 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000926 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000927 MemberType = MemberType.getQualifiedType(combinedQualifiers);
928
Chris Lattner68a057b2008-07-21 04:36:39 +0000929 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000930 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000931 }
932
Chris Lattnera38e6b12008-07-21 04:59:05 +0000933 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
934 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000935 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
936 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000937 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000938 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000939 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000940 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000941 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000942 }
943
Chris Lattnera38e6b12008-07-21 04:59:05 +0000944 // Handle Objective-C property access, which is "Obj.property" where Obj is a
945 // pointer to a (potentially qualified) interface type.
946 const PointerType *PTy;
947 const ObjCInterfaceType *IFTy;
948 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
949 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
950 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000951
Daniel Dunbar2307d312008-09-03 01:05:41 +0000952 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000953 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
954 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
955
Daniel Dunbar2307d312008-09-03 01:05:41 +0000956 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000957 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
958 E = IFTy->qual_end(); I != E; ++I)
959 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
960 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000961
962 // If that failed, look for an "implicit" property by seeing if the nullary
963 // selector is implemented.
964
965 // FIXME: The logic for looking up nullary and unary selectors should be
966 // shared with the code in ActOnInstanceMessage.
967
968 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
969 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
970
971 // If this reference is in an @implementation, check for 'private' methods.
972 if (!Getter)
973 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
974 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
975 if (ObjCImplementationDecl *ImpDecl =
976 ObjCImplementations[ClassDecl->getIdentifier()])
977 Getter = ImpDecl->getInstanceMethod(Sel);
978
Steve Naroff7692ed62008-10-22 19:16:27 +0000979 // Look through local category implementations associated with the class.
980 if (!Getter) {
981 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
982 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
983 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
984 }
985 }
Daniel Dunbar2307d312008-09-03 01:05:41 +0000986 if (Getter) {
987 // If we found a getter then this may be a valid dot-reference, we
988 // need to also look for the matching setter.
989 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
990 &Member);
991 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
992 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
993
994 if (!Setter) {
995 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
996 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
997 if (ObjCImplementationDecl *ImpDecl =
998 ObjCImplementations[ClassDecl->getIdentifier()])
999 Setter = ImpDecl->getInstanceMethod(SetterSel);
1000 }
1001
1002 // FIXME: There are some issues here. First, we are not
1003 // diagnosing accesses to read-only properties because we do not
1004 // know if this is a getter or setter yet. Second, we are
1005 // checking that the type of the setter matches the type we
1006 // expect.
1007 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1008 MemberLoc, BaseExpr);
1009 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001010 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001011 // Handle properties on qualified "id" protocols.
1012 const ObjCQualifiedIdType *QIdTy;
1013 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1014 // Check protocols on qualified interfaces.
1015 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1016 E = QIdTy->qual_end(); I != E; ++I)
1017 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1018 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1019 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001020 // Handle 'field access' to vectors, such as 'V.xx'.
1021 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1022 // Component access limited to variables (reject vec4.rg.g).
1023 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1024 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +00001025 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1026 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001027 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1028 if (ret.isNull())
1029 return true;
1030 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1031 }
1032
Chris Lattner2a01b722008-07-21 05:35:34 +00001033 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1034 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001035}
1036
Steve Narofff69936d2007-09-16 03:34:24 +00001037/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001038/// This provides the location of the left/right parens and a list of comma
1039/// locations.
1040Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001041ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001042 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001044 Expr *Fn = static_cast<Expr *>(fn);
1045 Expr **Args = reinterpret_cast<Expr**>(args);
1046 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001047 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001048 OverloadedFunctionDecl *Ovl = NULL;
1049
1050 // If we're directly calling a function or a set of overloaded
1051 // functions, get the appropriate declaration.
1052 {
1053 DeclRefExpr *DRExpr = NULL;
1054 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1055 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1056 else
1057 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1058
1059 if (DRExpr) {
1060 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1061 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1062 }
1063 }
1064
1065 // If we have a set of overloaded functions, perform overload
1066 // resolution to pick the function.
1067 if (Ovl) {
1068 OverloadCandidateSet CandidateSet;
1069 OverloadCandidateSet::iterator Best;
1070 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1071 switch (BestViableFunction(CandidateSet, Best)) {
1072 case OR_Success:
1073 {
1074 // Success! Let the remainder of this function build a call to
1075 // the function selected by overload resolution.
1076 FDecl = Best->Function;
1077 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1078 Fn->getSourceRange().getBegin());
1079 delete Fn;
1080 Fn = NewFn;
1081 }
1082 break;
1083
1084 case OR_No_Viable_Function:
1085 if (CandidateSet.empty())
1086 Diag(Fn->getSourceRange().getBegin(),
1087 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1088 Fn->getSourceRange());
1089 else {
1090 Diag(Fn->getSourceRange().getBegin(),
1091 diag::err_ovl_no_viable_function_in_call_with_cands,
1092 Ovl->getName(), Fn->getSourceRange());
1093 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1094 }
1095 return true;
1096
1097 case OR_Ambiguous:
1098 Diag(Fn->getSourceRange().getBegin(),
1099 diag::err_ovl_ambiguous_call, Ovl->getName(),
1100 Fn->getSourceRange());
1101 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1102 return true;
1103 }
1104 }
Chris Lattner04421082008-04-08 04:40:51 +00001105
1106 // Promote the function operand.
1107 UsualUnaryConversions(Fn);
1108
Chris Lattner925e60d2007-12-28 05:29:59 +00001109 // Make the call expr early, before semantic checks. This guarantees cleanup
1110 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001111 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001112 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001113 const FunctionType *FuncT;
1114 if (!Fn->getType()->isBlockPointerType()) {
1115 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1116 // have type pointer to function".
1117 const PointerType *PT = Fn->getType()->getAsPointerType();
1118 if (PT == 0)
1119 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1120 Fn->getSourceRange());
1121 FuncT = PT->getPointeeType()->getAsFunctionType();
1122 } else { // This is a block call.
1123 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1124 getAsFunctionType();
1125 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001126 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001127 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1128 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001129
1130 // We know the result type of the call, set it.
1131 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
Chris Lattner925e60d2007-12-28 05:29:59 +00001133 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1135 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001136 unsigned NumArgsInProto = Proto->getNumArgs();
1137 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001138
Chris Lattner04421082008-04-08 04:40:51 +00001139 // If too few arguments are available (and we don't have default
1140 // arguments for the remaining parameters), don't make the call.
1141 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001142 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001143 // Use default arguments for missing arguments
1144 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001145 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001146 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001147 return Diag(RParenLoc,
1148 !Fn->getType()->isBlockPointerType()
1149 ? diag::err_typecheck_call_too_few_args
1150 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001151 Fn->getSourceRange());
1152 }
1153
Chris Lattner925e60d2007-12-28 05:29:59 +00001154 // If too many are passed and not variadic, error on the extras and drop
1155 // them.
1156 if (NumArgs > NumArgsInProto) {
1157 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001158 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001159 !Fn->getType()->isBlockPointerType()
1160 ? diag::err_typecheck_call_too_many_args
1161 : diag::err_typecheck_block_too_many_args,
1162 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001163 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001164 Args[NumArgs-1]->getLocEnd()));
1165 // This deletes the extra arguments.
1166 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 }
1168 NumArgsToCheck = NumArgsInProto;
1169 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001172 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001173 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001174
1175 Expr *Arg;
1176 if (i < NumArgs)
1177 Arg = Args[i];
1178 else
1179 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001180 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001181
Chris Lattner925e60d2007-12-28 05:29:59 +00001182 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001183 AssignConvertType ConvTy =
1184 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001185 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001186
Chris Lattner5cf216b2008-01-04 18:04:52 +00001187 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1188 ArgType, Arg, "passing"))
1189 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001191
1192 // If this is a variadic call, handle args passed through "...".
1193 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001194 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001195 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1196 Expr *Arg = Args[i];
1197 DefaultArgumentPromotion(Arg);
1198 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001199 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001200 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001201 } else {
1202 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1203
Steve Naroffb291ab62007-08-28 23:30:39 +00001204 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001205 for (unsigned i = 0; i != NumArgs; i++) {
1206 Expr *Arg = Args[i];
1207 DefaultArgumentPromotion(Arg);
1208 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001209 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001211
Chris Lattner59907c42007-08-10 20:18:51 +00001212 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001213 if (FDecl)
1214 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001215
Chris Lattner925e60d2007-12-28 05:29:59 +00001216 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001217}
1218
1219Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001220ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001221 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001222 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001223 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001224 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001225 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001226 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001227
Eli Friedman6223c222008-05-20 05:22:08 +00001228 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001229 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001230 return Diag(LParenLoc,
1231 diag::err_variable_object_no_init,
1232 SourceRange(LParenLoc,
1233 literalExpr->getSourceRange().getEnd()));
1234 } else if (literalType->isIncompleteType()) {
1235 return Diag(LParenLoc,
1236 diag::err_typecheck_decl_incomplete_type,
1237 literalType.getAsString(),
1238 SourceRange(LParenLoc,
1239 literalExpr->getSourceRange().getEnd()));
1240 }
1241
Steve Naroffd0091aa2008-01-10 22:15:12 +00001242 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001243 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001244
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001245 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001246 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001247 if (CheckForConstantInitializer(literalExpr, literalType))
1248 return true;
1249 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001250 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001251}
1252
1253Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001254ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001255 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001256 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001257
Steve Naroff08d92e42007-09-15 18:49:24 +00001258 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001259 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001260
Chris Lattnerf0467b32008-04-02 04:24:33 +00001261 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1262 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1263 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001264}
1265
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001266/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001267bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001268 UsualUnaryConversions(castExpr);
1269
1270 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1271 // type needs to be scalar.
1272 if (castType->isVoidType()) {
1273 // Cast to void allows any expr type.
1274 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1275 // GCC struct/union extension: allow cast to self.
1276 if (Context.getCanonicalType(castType) !=
1277 Context.getCanonicalType(castExpr->getType()) ||
1278 (!castType->isStructureType() && !castType->isUnionType())) {
1279 // Reject any other conversions to non-scalar types.
1280 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1281 castType.getAsString(), castExpr->getSourceRange());
1282 }
1283
1284 // accept this, but emit an ext-warn.
1285 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1286 castType.getAsString(), castExpr->getSourceRange());
1287 } else if (!castExpr->getType()->isScalarType() &&
1288 !castExpr->getType()->isVectorType()) {
1289 return Diag(castExpr->getLocStart(),
1290 diag::err_typecheck_expect_scalar_operand,
1291 castExpr->getType().getAsString(),castExpr->getSourceRange());
1292 } else if (castExpr->getType()->isVectorType()) {
1293 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1294 return true;
1295 } else if (castType->isVectorType()) {
1296 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1297 return true;
1298 }
1299 return false;
1300}
1301
Chris Lattnerfe23e212007-12-20 00:44:32 +00001302bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001303 assert(VectorTy->isVectorType() && "Not a vector type!");
1304
1305 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001306 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001307 return Diag(R.getBegin(),
1308 Ty->isVectorType() ?
1309 diag::err_invalid_conversion_between_vectors :
1310 diag::err_invalid_conversion_between_vector_and_integer,
1311 VectorTy.getAsString().c_str(),
1312 Ty.getAsString().c_str(), R);
1313 } else
1314 return Diag(R.getBegin(),
1315 diag::err_invalid_conversion_between_vector_and_scalar,
1316 VectorTy.getAsString().c_str(),
1317 Ty.getAsString().c_str(), R);
1318
1319 return false;
1320}
1321
Steve Naroff4aa88f82007-07-19 01:06:55 +00001322Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001323ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001325 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001326
1327 Expr *castExpr = static_cast<Expr*>(Op);
1328 QualType castType = QualType::getFromOpaquePtr(Ty);
1329
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001330 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1331 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001332 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001333}
1334
Chris Lattnera21ddb32007-11-26 01:40:58 +00001335/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1336/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001337inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001338 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001339 UsualUnaryConversions(cond);
1340 UsualUnaryConversions(lex);
1341 UsualUnaryConversions(rex);
1342 QualType condT = cond->getType();
1343 QualType lexT = lex->getType();
1344 QualType rexT = rex->getType();
1345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001347 if (!condT->isScalarType()) { // C99 6.5.15p2
1348 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1349 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 return QualType();
1351 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001352
1353 // Now check the two expressions.
1354
1355 // If both operands have arithmetic type, do the usual arithmetic conversions
1356 // to find a common type: C99 6.5.15p3,5.
1357 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001358 UsualArithmeticConversions(lex, rex);
1359 return lex->getType();
1360 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001361
1362 // If both operands are the same structure or union type, the result is that
1363 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001364 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001365 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001366 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001367 // "If both the operands have structure or union type, the result has
1368 // that type." This implies that CV qualifiers are dropped.
1369 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001371
1372 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001373 // The following || allows only one side to be void (a GCC-ism).
1374 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001375 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001376 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1377 rex->getSourceRange());
1378 if (!rexT->isVoidType())
1379 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001380 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001381 ImpCastExprToType(lex, Context.VoidTy);
1382 ImpCastExprToType(rex, Context.VoidTy);
1383 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001384 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001385 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1386 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001387 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1388 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001389 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001390 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001391 return lexT;
1392 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001393 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1394 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001395 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001396 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001397 return rexT;
1398 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001399 // Handle the case where both operands are pointers before we handle null
1400 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001401 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1402 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1403 // get the "pointed to" types
1404 QualType lhptee = LHSPT->getPointeeType();
1405 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001406
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001407 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1408 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001409 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001410 // Figure out necessary qualifiers (C99 6.5.15p6)
1411 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001412 QualType destType = Context.getPointerType(destPointee);
1413 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1414 ImpCastExprToType(rex, destType); // promote to void*
1415 return destType;
1416 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001417 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001418 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001419 QualType destType = Context.getPointerType(destPointee);
1420 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1421 ImpCastExprToType(rex, destType); // promote to void*
1422 return destType;
1423 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001424
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001425 QualType compositeType = lexT;
1426
1427 // If either type is an Objective-C object type then check
1428 // compatibility according to Objective-C.
1429 if (Context.isObjCObjectPointerType(lexT) ||
1430 Context.isObjCObjectPointerType(rexT)) {
1431 // If both operands are interfaces and either operand can be
1432 // assigned to the other, use that type as the composite
1433 // type. This allows
1434 // xxx ? (A*) a : (B*) b
1435 // where B is a subclass of A.
1436 //
1437 // Additionally, as for assignment, if either type is 'id'
1438 // allow silent coercion. Finally, if the types are
1439 // incompatible then make sure to use 'id' as the composite
1440 // type so the result is acceptable for sending messages to.
1441
1442 // FIXME: This code should not be localized to here. Also this
1443 // should use a compatible check instead of abusing the
1444 // canAssignObjCInterfaces code.
1445 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1446 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1447 if (LHSIface && RHSIface &&
1448 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1449 compositeType = lexT;
1450 } else if (LHSIface && RHSIface &&
1451 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1452 compositeType = rexT;
1453 } else if (Context.isObjCIdType(lhptee) ||
1454 Context.isObjCIdType(rhptee)) {
1455 // FIXME: This code looks wrong, because isObjCIdType checks
1456 // the struct but getObjCIdType returns the pointer to
1457 // struct. This is horrible and should be fixed.
1458 compositeType = Context.getObjCIdType();
1459 } else {
1460 QualType incompatTy = Context.getObjCIdType();
1461 ImpCastExprToType(lex, incompatTy);
1462 ImpCastExprToType(rex, incompatTy);
1463 return incompatTy;
1464 }
1465 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1466 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001467 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001468 lexT.getAsString(), rexT.getAsString(),
1469 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001470 // In this situation, we assume void* type. No especially good
1471 // reason, but this is what gcc does, and we do have to pick
1472 // to get a consistent AST.
1473 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001474 ImpCastExprToType(lex, incompatTy);
1475 ImpCastExprToType(rex, incompatTy);
1476 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001477 }
1478 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001479 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1480 // differently qualified versions of compatible types, the result type is
1481 // a pointer to an appropriately qualified version of the *composite*
1482 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001483 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001484 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001485 ImpCastExprToType(lex, compositeType);
1486 ImpCastExprToType(rex, compositeType);
1487 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 }
1489 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001490 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1491 // evaluates to "struct objc_object *" (and is handled above when comparing
1492 // id with statically typed objects).
1493 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1494 // GCC allows qualified id and any Objective-C type to devolve to
1495 // id. Currently localizing to here until clear this should be
1496 // part of ObjCQualifiedIdTypesAreCompatible.
1497 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1498 (lexT->isObjCQualifiedIdType() &&
1499 Context.isObjCObjectPointerType(rexT)) ||
1500 (rexT->isObjCQualifiedIdType() &&
1501 Context.isObjCObjectPointerType(lexT))) {
1502 // FIXME: This is not the correct composite type. This only
1503 // happens to work because id can more or less be used anywhere,
1504 // however this may change the type of method sends.
1505 // FIXME: gcc adds some type-checking of the arguments and emits
1506 // (confusing) incompatible comparison warnings in some
1507 // cases. Investigate.
1508 QualType compositeType = Context.getObjCIdType();
1509 ImpCastExprToType(lex, compositeType);
1510 ImpCastExprToType(rex, compositeType);
1511 return compositeType;
1512 }
1513 }
1514
Steve Naroff61f40a22008-09-10 19:17:48 +00001515 // Selection between block pointer types is ok as long as they are the same.
1516 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1517 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1518 return lexT;
1519
Chris Lattner70d67a92008-01-06 22:42:25 +00001520 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001522 lexT.getAsString(), rexT.getAsString(),
1523 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 return QualType();
1525}
1526
Steve Narofff69936d2007-09-16 03:34:24 +00001527/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001528/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001529Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 SourceLocation ColonLoc,
1531 ExprTy *Cond, ExprTy *LHS,
1532 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001533 Expr *CondExpr = (Expr *) Cond;
1534 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001535
1536 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1537 // was the condition.
1538 bool isLHSNull = LHSExpr == 0;
1539 if (isLHSNull)
1540 LHSExpr = CondExpr;
1541
Chris Lattner26824902007-07-16 21:39:03 +00001542 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1543 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 if (result.isNull())
1545 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001546 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1547 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001548}
1549
Reid Spencer5f016e22007-07-11 17:01:13 +00001550
1551// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1552// being closely modeled after the C99 spec:-). The odd characteristic of this
1553// routine is it effectively iqnores the qualifiers on the top level pointee.
1554// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1555// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001556Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001557Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1558 QualType lhptee, rhptee;
1559
1560 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001561 lhptee = lhsType->getAsPointerType()->getPointeeType();
1562 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001563
1564 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001565 lhptee = Context.getCanonicalType(lhptee);
1566 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001567
Chris Lattner5cf216b2008-01-04 18:04:52 +00001568 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001569
1570 // C99 6.5.16.1p1: This following citation is common to constraints
1571 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1572 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001573 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001574 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001575 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001576
1577 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1578 // incomplete type and the other is a pointer to a qualified or unqualified
1579 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001580 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001581 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001582 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001583
1584 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001585 assert(rhptee->isFunctionType());
1586 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001587 }
1588
1589 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001590 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001591 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001592
1593 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001594 assert(lhptee->isFunctionType());
1595 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001596 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001597
1598 // Check for ObjC interfaces
1599 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1600 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1601 if (LHSIface && RHSIface &&
1602 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1603 return ConvTy;
1604
1605 // ID acts sort of like void* for ObjC interfaces
1606 if (LHSIface && Context.isObjCIdType(rhptee))
1607 return ConvTy;
1608 if (RHSIface && Context.isObjCIdType(lhptee))
1609 return ConvTy;
1610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1612 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001613 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1614 rhptee.getUnqualifiedType()))
1615 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001616 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001617}
1618
Steve Naroff1c7d0672008-09-04 15:10:53 +00001619/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1620/// block pointer types are compatible or whether a block and normal pointer
1621/// are compatible. It is more restrict than comparing two function pointer
1622// types.
1623Sema::AssignConvertType
1624Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1625 QualType rhsType) {
1626 QualType lhptee, rhptee;
1627
1628 // get the "pointed to" type (ignoring qualifiers at the top level)
1629 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1630 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1631
1632 // make sure we operate on the canonical type
1633 lhptee = Context.getCanonicalType(lhptee);
1634 rhptee = Context.getCanonicalType(rhptee);
1635
1636 AssignConvertType ConvTy = Compatible;
1637
1638 // For blocks we enforce that qualifiers are identical.
1639 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1640 ConvTy = CompatiblePointerDiscardsQualifiers;
1641
1642 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1643 return IncompatibleBlockPointer;
1644 return ConvTy;
1645}
1646
Reid Spencer5f016e22007-07-11 17:01:13 +00001647/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1648/// has code to accommodate several GCC extensions when type checking
1649/// pointers. Here are some objectionable examples that GCC considers warnings:
1650///
1651/// int a, *pint;
1652/// short *pshort;
1653/// struct foo *pfoo;
1654///
1655/// pint = pshort; // warning: assignment from incompatible pointer type
1656/// a = pint; // warning: assignment makes integer from pointer without a cast
1657/// pint = a; // warning: assignment makes pointer from integer without a cast
1658/// pint = pfoo; // warning: assignment from incompatible pointer type
1659///
1660/// As a result, the code for dealing with pointers is more complex than the
1661/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001662///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001663Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001664Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001665 // Get canonical types. We're not formatting these types, just comparing
1666 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001667 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1668 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001669
1670 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001671 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001672
Anders Carlsson793680e2007-10-12 23:56:29 +00001673 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001674 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001675 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001676 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001677 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001678
Chris Lattnereca7be62008-04-07 05:30:13 +00001679 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1680 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001681 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001682 // Relax integer conversions like we do for pointers below.
1683 if (rhsType->isIntegerType())
1684 return IntToPointer;
1685 if (lhsType->isIntegerType())
1686 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001687 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001688 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001689
Nate Begemanbe2341d2008-07-14 18:02:46 +00001690 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001691 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001692 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1693 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001694 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001695
Nate Begemanbe2341d2008-07-14 18:02:46 +00001696 // If we are allowing lax vector conversions, and LHS and RHS are both
1697 // vectors, the total size only needs to be the same. This is a bitcast;
1698 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001699 if (getLangOptions().LaxVectorConversions &&
1700 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001701 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1702 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001703 }
1704 return Incompatible;
1705 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001706
Chris Lattnere8b3e962008-01-04 23:32:24 +00001707 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001709
Chris Lattner78eca282008-04-07 06:49:41 +00001710 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001712 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001713
Chris Lattner78eca282008-04-07 06:49:41 +00001714 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001716
Steve Naroffb4406862008-09-29 18:10:17 +00001717 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001718 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001719 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001720
1721 // Treat block pointers as objects.
1722 if (getLangOptions().ObjC1 &&
1723 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1724 return Compatible;
1725 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001726 return Incompatible;
1727 }
1728
1729 if (isa<BlockPointerType>(lhsType)) {
1730 if (rhsType->isIntegerType())
1731 return IntToPointer;
1732
Steve Naroffb4406862008-09-29 18:10:17 +00001733 // Treat block pointers as objects.
1734 if (getLangOptions().ObjC1 &&
1735 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1736 return Compatible;
1737
Steve Naroff1c7d0672008-09-04 15:10:53 +00001738 if (rhsType->isBlockPointerType())
1739 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1740
1741 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1742 if (RHSPT->getPointeeType()->isVoidType())
1743 return BlockVoidPointer;
1744 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001745 return Incompatible;
1746 }
1747
Chris Lattner78eca282008-04-07 06:49:41 +00001748 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001750 if (lhsType == Context.BoolTy)
1751 return Compatible;
1752
1753 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001754 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001755
Chris Lattner78eca282008-04-07 06:49:41 +00001756 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001758
1759 if (isa<BlockPointerType>(lhsType) &&
1760 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1761 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001762 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001763 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001764
Chris Lattnerfc144e22008-01-04 23:18:45 +00001765 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001766 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 }
1769 return Incompatible;
1770}
1771
Chris Lattner5cf216b2008-01-04 18:04:52 +00001772Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001773Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001774 if (getLangOptions().CPlusPlus) {
1775 if (!lhsType->isRecordType()) {
1776 // C++ 5.17p3: If the left operand is not of class type, the
1777 // expression is implicitly converted (C++ 4) to the
1778 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001779 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001780 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001781 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00001782 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001783 }
1784
1785 // FIXME: Currently, we fall through and treat C++ classes like C
1786 // structures.
1787 }
1788
Steve Naroff529a4ad2007-11-27 17:58:44 +00001789 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1790 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001791 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1792 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001793 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001794 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001795 return Compatible;
1796 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001797
1798 // We don't allow conversion of non-null-pointer constants to integers.
1799 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1800 return IntToBlockPointer;
1801
Chris Lattner943140e2007-10-16 02:55:40 +00001802 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001803 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001804 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001805 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001806 //
Douglas Gregor2f639b92008-10-24 15:36:09 +00001807 // Suppress this for references: C++ 8.5.3p5. FIXME: revisit when references
Chris Lattner943140e2007-10-16 02:55:40 +00001808 // are better understood.
1809 if (!lhsType->isReferenceType())
1810 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001811
Chris Lattner5cf216b2008-01-04 18:04:52 +00001812 Sema::AssignConvertType result =
1813 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001814
1815 // C99 6.5.16.1p2: The value of the right operand is converted to the
1816 // type of the assignment expression.
1817 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001818 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001819 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001820}
1821
Chris Lattner5cf216b2008-01-04 18:04:52 +00001822Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001823Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1824 return CheckAssignmentConstraints(lhsType, rhsType);
1825}
1826
Chris Lattnerca5eede2007-12-12 05:47:28 +00001827QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 Diag(loc, diag::err_typecheck_invalid_operands,
1829 lex->getType().getAsString(), rex->getType().getAsString(),
1830 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001831 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001832}
1833
Steve Naroff49b45262007-07-13 16:58:59 +00001834inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1835 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001836 // For conversion purposes, we ignore any qualifiers.
1837 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001838 QualType lhsType =
1839 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1840 QualType rhsType =
1841 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001842
Nate Begemanbe2341d2008-07-14 18:02:46 +00001843 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001844 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001846
Nate Begemanbe2341d2008-07-14 18:02:46 +00001847 // Handle the case of a vector & extvector type of the same size and element
1848 // type. It would be nice if we only had one vector type someday.
1849 if (getLangOptions().LaxVectorConversions)
1850 if (const VectorType *LV = lhsType->getAsVectorType())
1851 if (const VectorType *RV = rhsType->getAsVectorType())
1852 if (LV->getElementType() == RV->getElementType() &&
1853 LV->getNumElements() == RV->getNumElements())
1854 return lhsType->isExtVectorType() ? lhsType : rhsType;
1855
1856 // If the lhs is an extended vector and the rhs is a scalar of the same type
1857 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001858 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001859 QualType eltType = V->getElementType();
1860
1861 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1862 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1863 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001864 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001865 return lhsType;
1866 }
1867 }
1868
Nate Begemanbe2341d2008-07-14 18:02:46 +00001869 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001870 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001871 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001872 QualType eltType = V->getElementType();
1873
1874 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1875 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1876 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001877 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001878 return rhsType;
1879 }
1880 }
1881
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 // You cannot convert between vector values of different size.
1883 Diag(loc, diag::err_typecheck_vector_not_convertable,
1884 lex->getType().getAsString(), rex->getType().getAsString(),
1885 lex->getSourceRange(), rex->getSourceRange());
1886 return QualType();
1887}
1888
1889inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001890 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001891{
Steve Naroff90045e82007-07-13 23:32:42 +00001892 QualType lhsType = lex->getType(), rhsType = rex->getType();
1893
1894 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001896
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001897 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001898
Steve Naroffa4332e22007-07-17 00:58:39 +00001899 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001900 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001901 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001902}
1903
1904inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001905 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001906{
Steve Naroff90045e82007-07-13 23:32:42 +00001907 QualType lhsType = lex->getType(), rhsType = rex->getType();
1908
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001909 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001910
Steve Naroffa4332e22007-07-17 00:58:39 +00001911 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001912 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001913 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001914}
1915
1916inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001917 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001918{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001919 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001920 return CheckVectorOperands(loc, lex, rex);
1921
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001922 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001923
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001925 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001926 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001927
Eli Friedmand72d16e2008-05-18 18:08:51 +00001928 // Put any potential pointer into PExp
1929 Expr* PExp = lex, *IExp = rex;
1930 if (IExp->getType()->isPointerType())
1931 std::swap(PExp, IExp);
1932
1933 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1934 if (IExp->getType()->isIntegerType()) {
1935 // Check for arithmetic on pointers to incomplete types
1936 if (!PTy->getPointeeType()->isObjectType()) {
1937 if (PTy->getPointeeType()->isVoidType()) {
1938 Diag(loc, diag::ext_gnu_void_ptr,
1939 lex->getSourceRange(), rex->getSourceRange());
1940 } else {
1941 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1942 lex->getType().getAsString(), lex->getSourceRange());
1943 return QualType();
1944 }
1945 }
1946 return PExp->getType();
1947 }
1948 }
1949
Chris Lattnerca5eede2007-12-12 05:47:28 +00001950 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001951}
1952
Chris Lattnereca7be62008-04-07 05:30:13 +00001953// C99 6.5.6
1954QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1955 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001956 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001958
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001959 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001960
Chris Lattner6e4ab612007-12-09 21:53:25 +00001961 // Enforce type constraints: C99 6.5.6p3.
1962
1963 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001964 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001965 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001966
1967 // Either ptr - int or ptr - ptr.
1968 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001969 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001970
Chris Lattner6e4ab612007-12-09 21:53:25 +00001971 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001972 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001973 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001974 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001975 Diag(loc, diag::ext_gnu_void_ptr,
1976 lex->getSourceRange(), rex->getSourceRange());
1977 } else {
1978 Diag(loc, diag::err_typecheck_sub_ptr_object,
1979 lex->getType().getAsString(), lex->getSourceRange());
1980 return QualType();
1981 }
1982 }
1983
1984 // The result type of a pointer-int computation is the pointer type.
1985 if (rex->getType()->isIntegerType())
1986 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001987
Chris Lattner6e4ab612007-12-09 21:53:25 +00001988 // Handle pointer-pointer subtractions.
1989 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001990 QualType rpointee = RHSPTy->getPointeeType();
1991
Chris Lattner6e4ab612007-12-09 21:53:25 +00001992 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001993 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001994 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001995 if (rpointee->isVoidType()) {
1996 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001997 Diag(loc, diag::ext_gnu_void_ptr,
1998 lex->getSourceRange(), rex->getSourceRange());
1999 } else {
2000 Diag(loc, diag::err_typecheck_sub_ptr_object,
2001 rex->getType().getAsString(), rex->getSourceRange());
2002 return QualType();
2003 }
2004 }
2005
2006 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002007 if (!Context.typesAreCompatible(
2008 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2009 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002010 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2011 lex->getType().getAsString(), rex->getType().getAsString(),
2012 lex->getSourceRange(), rex->getSourceRange());
2013 return QualType();
2014 }
2015
2016 return Context.getPointerDiffType();
2017 }
2018 }
2019
Chris Lattnerca5eede2007-12-12 05:47:28 +00002020 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002021}
2022
Chris Lattnereca7be62008-04-07 05:30:13 +00002023// C99 6.5.7
2024QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2025 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002026 // C99 6.5.7p2: Each of the operands shall have integer type.
2027 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2028 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002029
Chris Lattnerca5eede2007-12-12 05:47:28 +00002030 // Shifts don't perform usual arithmetic conversions, they just do integer
2031 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002032 if (!isCompAssign)
2033 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002034 UsualUnaryConversions(rex);
2035
2036 // "The type of the result is that of the promoted left operand."
2037 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002038}
2039
Eli Friedman3d815e72008-08-22 00:56:42 +00002040static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2041 ASTContext& Context) {
2042 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2043 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2044 // ID acts sort of like void* for ObjC interfaces
2045 if (LHSIface && Context.isObjCIdType(RHS))
2046 return true;
2047 if (RHSIface && Context.isObjCIdType(LHS))
2048 return true;
2049 if (!LHSIface || !RHSIface)
2050 return false;
2051 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2052 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2053}
2054
Chris Lattnereca7be62008-04-07 05:30:13 +00002055// C99 6.5.8
2056QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2057 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002058 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2059 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2060
Chris Lattnera5937dd2007-08-26 01:18:55 +00002061 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002062 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2063 UsualArithmeticConversions(lex, rex);
2064 else {
2065 UsualUnaryConversions(lex);
2066 UsualUnaryConversions(rex);
2067 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002068 QualType lType = lex->getType();
2069 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002070
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002071 // For non-floating point types, check for self-comparisons of the form
2072 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2073 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002074 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002075 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2076 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002077 if (DRL->getDecl() == DRR->getDecl())
2078 Diag(loc, diag::warn_selfcomparison);
2079 }
2080
Chris Lattnera5937dd2007-08-26 01:18:55 +00002081 if (isRelational) {
2082 if (lType->isRealType() && rType->isRealType())
2083 return Context.IntTy;
2084 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002085 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002086 if (lType->isFloatingType()) {
2087 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002088 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002089 }
2090
Chris Lattnera5937dd2007-08-26 01:18:55 +00002091 if (lType->isArithmeticType() && rType->isArithmeticType())
2092 return Context.IntTy;
2093 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002094
Chris Lattnerd28f8152007-08-26 01:10:14 +00002095 bool LHSIsNull = lex->isNullPointerConstant(Context);
2096 bool RHSIsNull = rex->isNullPointerConstant(Context);
2097
Chris Lattnera5937dd2007-08-26 01:18:55 +00002098 // All of the following pointer related warnings are GCC extensions, except
2099 // when handling null pointer constants. One day, we can consider making them
2100 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002101 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002102 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002103 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002104 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002105 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002106
Steve Naroff66296cb2007-11-13 14:57:38 +00002107 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002108 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2109 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002110 RCanPointeeTy.getUnqualifiedType()) &&
2111 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002112 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2113 lType.getAsString(), rType.getAsString(),
2114 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002116 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002117 return Context.IntTy;
2118 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002119 // Handle block pointer types.
2120 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2121 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2122 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2123
2124 if (!LHSIsNull && !RHSIsNull &&
2125 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2126 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2127 lType.getAsString(), rType.getAsString(),
2128 lex->getSourceRange(), rex->getSourceRange());
2129 }
2130 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2131 return Context.IntTy;
2132 }
Steve Naroff59f53942008-09-28 01:11:11 +00002133 // Allow block pointers to be compared with null pointer constants.
2134 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2135 (lType->isPointerType() && rType->isBlockPointerType())) {
2136 if (!LHSIsNull && !RHSIsNull) {
2137 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2138 lType.getAsString(), rType.getAsString(),
2139 lex->getSourceRange(), rex->getSourceRange());
2140 }
2141 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2142 return Context.IntTy;
2143 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002144
Steve Naroff20373222008-06-03 14:04:54 +00002145 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff87f3b932008-10-20 18:19:10 +00002146 if ((lType->isPointerType() || rType->isPointerType()) &&
2147 !Context.typesAreCompatible(lType, rType)) {
2148 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2149 lType.getAsString(), rType.getAsString(),
2150 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002151 ImpCastExprToType(rex, lType);
Steve Naroff8970fea2008-10-22 22:40:28 +00002152 return Context.IntTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002153 }
Steve Naroff20373222008-06-03 14:04:54 +00002154 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2155 ImpCastExprToType(rex, lType);
2156 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002157 } else {
2158 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2159 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002160 lType.getAsString(), rType.getAsString(),
Steve Naroff39579072008-10-14 22:18:38 +00002161 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002162 ImpCastExprToType(rex, lType);
Steve Naroff8970fea2008-10-22 22:40:28 +00002163 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002164 }
Steve Naroff20373222008-06-03 14:04:54 +00002165 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002166 }
Steve Naroff20373222008-06-03 14:04:54 +00002167 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2168 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002169 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002170 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2171 lType.getAsString(), rType.getAsString(),
2172 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002173 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002174 return Context.IntTy;
2175 }
Steve Naroff20373222008-06-03 14:04:54 +00002176 if (lType->isIntegerType() &&
2177 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002178 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002179 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2180 lType.getAsString(), rType.getAsString(),
2181 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002182 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002183 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 }
Steve Naroff39218df2008-09-04 16:56:14 +00002185 // Handle block pointers.
2186 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2187 if (!RHSIsNull)
2188 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2189 lType.getAsString(), rType.getAsString(),
2190 lex->getSourceRange(), rex->getSourceRange());
2191 ImpCastExprToType(rex, lType); // promote the integer to pointer
2192 return Context.IntTy;
2193 }
2194 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2195 if (!LHSIsNull)
2196 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2197 lType.getAsString(), rType.getAsString(),
2198 lex->getSourceRange(), rex->getSourceRange());
2199 ImpCastExprToType(lex, rType); // promote the integer to pointer
2200 return Context.IntTy;
2201 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002202 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002203}
2204
Nate Begemanbe2341d2008-07-14 18:02:46 +00002205/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2206/// operates on extended vector types. Instead of producing an IntTy result,
2207/// like a scalar comparison, a vector comparison produces a vector of integer
2208/// types.
2209QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2210 SourceLocation loc,
2211 bool isRelational) {
2212 // Check to make sure we're operating on vectors of the same type and width,
2213 // Allowing one side to be a scalar of element type.
2214 QualType vType = CheckVectorOperands(loc, lex, rex);
2215 if (vType.isNull())
2216 return vType;
2217
2218 QualType lType = lex->getType();
2219 QualType rType = rex->getType();
2220
2221 // For non-floating point types, check for self-comparisons of the form
2222 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2223 // often indicate logic errors in the program.
2224 if (!lType->isFloatingType()) {
2225 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2226 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2227 if (DRL->getDecl() == DRR->getDecl())
2228 Diag(loc, diag::warn_selfcomparison);
2229 }
2230
2231 // Check for comparisons of floating point operands using != and ==.
2232 if (!isRelational && lType->isFloatingType()) {
2233 assert (rType->isFloatingType());
2234 CheckFloatComparison(loc,lex,rex);
2235 }
2236
2237 // Return the type for the comparison, which is the same as vector type for
2238 // integer vectors, or an integer type of identical size and number of
2239 // elements for floating point vectors.
2240 if (lType->isIntegerType())
2241 return lType;
2242
2243 const VectorType *VTy = lType->getAsVectorType();
2244
2245 // FIXME: need to deal with non-32b int / non-64b long long
2246 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2247 if (TypeSize == 32) {
2248 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2249 }
2250 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2251 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2252}
2253
Reid Spencer5f016e22007-07-11 17:01:13 +00002254inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002255 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002256{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002257 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002259
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002260 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261
Steve Naroffa4332e22007-07-17 00:58:39 +00002262 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002263 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002264 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002265}
2266
2267inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002268 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002269{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002270 UsualUnaryConversions(lex);
2271 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002272
Eli Friedman5773a6c2008-05-13 20:16:47 +00002273 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002275 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002276}
2277
2278inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002279 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002280{
2281 QualType lhsType = lex->getType();
2282 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002283 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002284
2285 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002286 case Expr::MLV_Valid:
2287 break;
2288 case Expr::MLV_ConstQualified:
2289 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2290 return QualType();
2291 case Expr::MLV_ArrayType:
2292 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2293 lhsType.getAsString(), lex->getSourceRange());
2294 return QualType();
2295 case Expr::MLV_NotObjectType:
2296 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2297 lhsType.getAsString(), lex->getSourceRange());
2298 return QualType();
2299 case Expr::MLV_InvalidExpression:
2300 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2301 lex->getSourceRange());
2302 return QualType();
2303 case Expr::MLV_IncompleteType:
2304 case Expr::MLV_IncompleteVoidType:
2305 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2306 lhsType.getAsString(), lex->getSourceRange());
2307 return QualType();
2308 case Expr::MLV_DuplicateVectorComponents:
2309 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2310 lex->getSourceRange());
2311 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002312 case Expr::MLV_NotBlockQualified:
2313 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2314 lex->getSourceRange());
2315 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002317
Chris Lattner5cf216b2008-01-04 18:04:52 +00002318 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002319 if (compoundType.isNull()) {
2320 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002321 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002322
2323 // If the RHS is a unary plus or minus, check to see if they = and + are
2324 // right next to each other. If so, the user may have typo'd "x =+ 4"
2325 // instead of "x += 4".
2326 Expr *RHSCheck = rex;
2327 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2328 RHSCheck = ICE->getSubExpr();
2329 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2330 if ((UO->getOpcode() == UnaryOperator::Plus ||
2331 UO->getOpcode() == UnaryOperator::Minus) &&
2332 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2333 // Only if the two operators are exactly adjacent.
2334 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2335 Diag(loc, diag::warn_not_compound_assign,
2336 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2337 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2338 }
2339 } else {
2340 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002341 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002342 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002343
2344 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2345 rex, "assigning"))
2346 return QualType();
2347
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 // C99 6.5.16p3: The type of an assignment expression is the type of the
2349 // left operand unless the left operand has qualified type, in which case
2350 // it is the unqualified version of the type of the left operand.
2351 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2352 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002353 // C++ 5.17p1: the type of the assignment expression is that of its left
2354 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002355 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002356}
2357
2358inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002359 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002360
2361 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2362 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002363 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002364}
2365
Steve Naroff49b45262007-07-13 16:58:59 +00002366/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2367/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002368QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002369 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 assert(!resType.isNull() && "no type for increment/decrement expression");
2371
Steve Naroff084f9ed2007-08-24 17:20:07 +00002372 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002373 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002374 if (pt->getPointeeType()->isVoidType()) {
2375 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2376 } else if (!pt->getPointeeType()->isObjectType()) {
2377 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2379 resType.getAsString(), op->getSourceRange());
2380 return QualType();
2381 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002382 } else if (!resType->isRealType()) {
2383 if (resType->isComplexType())
2384 // C99 does not support ++/-- on complex types.
2385 Diag(OpLoc, diag::ext_integer_increment_complex,
2386 resType.getAsString(), op->getSourceRange());
2387 else {
2388 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2389 resType.getAsString(), op->getSourceRange());
2390 return QualType();
2391 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002393 // At this point, we know we have a real, complex or pointer type.
2394 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002395 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002396 if (mlval != Expr::MLV_Valid) {
2397 // FIXME: emit a more precise diagnostic...
2398 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2399 op->getSourceRange());
2400 return QualType();
2401 }
2402 return resType;
2403}
2404
Anders Carlsson369dee42008-02-01 07:15:58 +00002405/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002406/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002407/// where the declaration is needed for type checking. We only need to
2408/// handle cases when the expression references a function designator
2409/// or is an lvalue. Here are some examples:
2410/// - &(x) => x
2411/// - &*****f => f for f a function designator.
2412/// - &s.xx => s
2413/// - &s.zz[1].yy -> s, if zz is an array
2414/// - *(x + 1) -> x, if x is an array
2415/// - &"123"[2] -> 0
2416/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002417static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002418 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002419 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002420 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002421 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002422 // Fields cannot be declared with a 'register' storage class.
2423 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002424 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002425 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002426 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002427 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002428 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002430 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002431 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002432 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002433 return 0;
2434 else
2435 return VD;
2436 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002437 case Stmt::UnaryOperatorClass: {
2438 UnaryOperator *UO = cast<UnaryOperator>(E);
2439
2440 switch(UO->getOpcode()) {
2441 case UnaryOperator::Deref: {
2442 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002443 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2444 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2445 if (!VD || VD->getType()->isPointerType())
2446 return 0;
2447 return VD;
2448 }
2449 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002450 }
2451 case UnaryOperator::Real:
2452 case UnaryOperator::Imag:
2453 case UnaryOperator::Extension:
2454 return getPrimaryDecl(UO->getSubExpr());
2455 default:
2456 return 0;
2457 }
2458 }
2459 case Stmt::BinaryOperatorClass: {
2460 BinaryOperator *BO = cast<BinaryOperator>(E);
2461
2462 // Handle cases involving pointer arithmetic. The result of an
2463 // Assign or AddAssign is not an lvalue so they can be ignored.
2464
2465 // (x + n) or (n + x) => x
2466 if (BO->getOpcode() == BinaryOperator::Add) {
2467 if (BO->getLHS()->getType()->isPointerType()) {
2468 return getPrimaryDecl(BO->getLHS());
2469 } else if (BO->getRHS()->getType()->isPointerType()) {
2470 return getPrimaryDecl(BO->getRHS());
2471 }
2472 }
2473
2474 return 0;
2475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002477 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002478 case Stmt::ImplicitCastExprClass:
2479 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002480 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 default:
2482 return 0;
2483 }
2484}
2485
2486/// CheckAddressOfOperand - The operand of & must be either a function
2487/// designator or an lvalue designating an object. If it is an lvalue, the
2488/// object cannot be declared with storage class register or be a bit field.
2489/// Note: The usual conversions are *not* applied to the operand of the &
2490/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2491QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002492 if (getLangOptions().C99) {
2493 // Implement C99-only parts of addressof rules.
2494 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2495 if (uOp->getOpcode() == UnaryOperator::Deref)
2496 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2497 // (assuming the deref expression is valid).
2498 return uOp->getSubExpr()->getType();
2499 }
2500 // Technically, there should be a check for array subscript
2501 // expressions here, but the result of one is always an lvalue anyway.
2502 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002503 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002504 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002505
2506 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002507 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2508 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002509 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2510 op->getSourceRange());
2511 return QualType();
2512 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002513 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2514 if (MemExpr->getMemberDecl()->isBitField()) {
2515 Diag(OpLoc, diag::err_typecheck_address_of,
2516 std::string("bit-field"), op->getSourceRange());
2517 return QualType();
2518 }
2519 // Check for Apple extension for accessing vector components.
2520 } else if (isa<ArraySubscriptExpr>(op) &&
2521 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2522 Diag(OpLoc, diag::err_typecheck_address_of,
2523 std::string("vector"), op->getSourceRange());
2524 return QualType();
2525 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 // We have an lvalue with a decl. Make sure the decl is not declared
2527 // with the register storage-class specifier.
2528 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2529 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002530 Diag(OpLoc, diag::err_typecheck_address_of,
2531 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002532 return QualType();
2533 }
2534 } else
2535 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002537
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 // If the operand has type "type", the result has type "pointer to type".
2539 return Context.getPointerType(op->getType());
2540}
2541
2542QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002543 UsualUnaryConversions(op);
2544 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002545
Chris Lattnerbefee482007-07-31 16:53:04 +00002546 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002547 // Note that per both C89 and C99, this is always legal, even
2548 // if ptype is an incomplete type or void.
2549 // It would be possible to warn about dereferencing a
2550 // void pointer, but it's completely well-defined,
2551 // and such a warning is unlikely to catch any mistakes.
2552 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 }
2554 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2555 qType.getAsString(), op->getSourceRange());
2556 return QualType();
2557}
2558
2559static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2560 tok::TokenKind Kind) {
2561 BinaryOperator::Opcode Opc;
2562 switch (Kind) {
2563 default: assert(0 && "Unknown binop!");
2564 case tok::star: Opc = BinaryOperator::Mul; break;
2565 case tok::slash: Opc = BinaryOperator::Div; break;
2566 case tok::percent: Opc = BinaryOperator::Rem; break;
2567 case tok::plus: Opc = BinaryOperator::Add; break;
2568 case tok::minus: Opc = BinaryOperator::Sub; break;
2569 case tok::lessless: Opc = BinaryOperator::Shl; break;
2570 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2571 case tok::lessequal: Opc = BinaryOperator::LE; break;
2572 case tok::less: Opc = BinaryOperator::LT; break;
2573 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2574 case tok::greater: Opc = BinaryOperator::GT; break;
2575 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2576 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2577 case tok::amp: Opc = BinaryOperator::And; break;
2578 case tok::caret: Opc = BinaryOperator::Xor; break;
2579 case tok::pipe: Opc = BinaryOperator::Or; break;
2580 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2581 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2582 case tok::equal: Opc = BinaryOperator::Assign; break;
2583 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2584 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2585 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2586 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2587 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2588 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2589 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2590 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2591 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2592 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2593 case tok::comma: Opc = BinaryOperator::Comma; break;
2594 }
2595 return Opc;
2596}
2597
2598static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2599 tok::TokenKind Kind) {
2600 UnaryOperator::Opcode Opc;
2601 switch (Kind) {
2602 default: assert(0 && "Unknown unary op!");
2603 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2604 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2605 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2606 case tok::star: Opc = UnaryOperator::Deref; break;
2607 case tok::plus: Opc = UnaryOperator::Plus; break;
2608 case tok::minus: Opc = UnaryOperator::Minus; break;
2609 case tok::tilde: Opc = UnaryOperator::Not; break;
2610 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2611 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2612 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2613 case tok::kw___real: Opc = UnaryOperator::Real; break;
2614 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2615 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2616 }
2617 return Opc;
2618}
2619
2620// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002621Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 ExprTy *LHS, ExprTy *RHS) {
2623 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2624 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2625
Steve Narofff69936d2007-09-16 03:34:24 +00002626 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2627 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002628
2629 QualType ResultTy; // Result type of the binary operator.
2630 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2631
2632 switch (Opc) {
2633 default:
2634 assert(0 && "Unknown binary expr!");
2635 case BinaryOperator::Assign:
2636 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2637 break;
2638 case BinaryOperator::Mul:
2639 case BinaryOperator::Div:
2640 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2641 break;
2642 case BinaryOperator::Rem:
2643 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2644 break;
2645 case BinaryOperator::Add:
2646 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2647 break;
2648 case BinaryOperator::Sub:
2649 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2650 break;
2651 case BinaryOperator::Shl:
2652 case BinaryOperator::Shr:
2653 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2654 break;
2655 case BinaryOperator::LE:
2656 case BinaryOperator::LT:
2657 case BinaryOperator::GE:
2658 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002659 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 break;
2661 case BinaryOperator::EQ:
2662 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002663 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 break;
2665 case BinaryOperator::And:
2666 case BinaryOperator::Xor:
2667 case BinaryOperator::Or:
2668 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2669 break;
2670 case BinaryOperator::LAnd:
2671 case BinaryOperator::LOr:
2672 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2673 break;
2674 case BinaryOperator::MulAssign:
2675 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002676 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 if (!CompTy.isNull())
2678 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2679 break;
2680 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002681 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 if (!CompTy.isNull())
2683 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2684 break;
2685 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002686 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 if (!CompTy.isNull())
2688 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2689 break;
2690 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002691 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 if (!CompTy.isNull())
2693 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2694 break;
2695 case BinaryOperator::ShlAssign:
2696 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002697 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 if (!CompTy.isNull())
2699 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2700 break;
2701 case BinaryOperator::AndAssign:
2702 case BinaryOperator::XorAssign:
2703 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002704 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 if (!CompTy.isNull())
2706 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2707 break;
2708 case BinaryOperator::Comma:
2709 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2710 break;
2711 }
2712 if (ResultTy.isNull())
2713 return true;
2714 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002715 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002717 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002718}
2719
2720// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002721Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 ExprTy *input) {
2723 Expr *Input = (Expr*)input;
2724 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2725 QualType resultType;
2726 switch (Opc) {
2727 default:
2728 assert(0 && "Unimplemented unary expr!");
2729 case UnaryOperator::PreInc:
2730 case UnaryOperator::PreDec:
2731 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2732 break;
2733 case UnaryOperator::AddrOf:
2734 resultType = CheckAddressOfOperand(Input, OpLoc);
2735 break;
2736 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002737 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 resultType = CheckIndirectionOperand(Input, OpLoc);
2739 break;
2740 case UnaryOperator::Plus:
2741 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002742 UsualUnaryConversions(Input);
2743 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2745 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2746 resultType.getAsString());
2747 break;
2748 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002749 UsualUnaryConversions(Input);
2750 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002751 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2752 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2753 // C99 does not support '~' for complex conjugation.
2754 Diag(OpLoc, diag::ext_integer_complement_complex,
2755 resultType.getAsString(), Input->getSourceRange());
2756 else if (!resultType->isIntegerType())
2757 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2758 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 break;
2760 case UnaryOperator::LNot: // logical negation
2761 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002762 DefaultFunctionArrayConversion(Input);
2763 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2765 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2766 resultType.getAsString());
2767 // LNot always has type int. C99 6.5.3.3p5.
2768 resultType = Context.IntTy;
2769 break;
2770 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002771 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2772 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 break;
2774 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002775 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2776 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002778 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002779 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002780 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002781 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 resultType = Input->getType();
2784 break;
2785 }
2786 if (resultType.isNull())
2787 return true;
2788 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2789}
2790
Steve Naroff1b273c42007-09-16 14:56:35 +00002791/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2792Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 SourceLocation LabLoc,
2794 IdentifierInfo *LabelII) {
2795 // Look up the record for this label identifier.
2796 LabelStmt *&LabelDecl = LabelMap[LabelII];
2797
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002798 // If we haven't seen this label yet, create a forward reference. It
2799 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 if (LabelDecl == 0)
2801 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2802
2803 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002804 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2805 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002806}
2807
Steve Naroff1b273c42007-09-16 14:56:35 +00002808Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002809 SourceLocation RPLoc) { // "({..})"
2810 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2811 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2812 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2813
2814 // FIXME: there are a variety of strange constraints to enforce here, for
2815 // example, it is not possible to goto into a stmt expression apparently.
2816 // More semantic analysis is needed.
2817
2818 // FIXME: the last statement in the compount stmt has its value used. We
2819 // should not warn about it being unused.
2820
2821 // If there are sub stmts in the compound stmt, take the type of the last one
2822 // as the type of the stmtexpr.
2823 QualType Ty = Context.VoidTy;
2824
Chris Lattner611b2ec2008-07-26 19:51:01 +00002825 if (!Compound->body_empty()) {
2826 Stmt *LastStmt = Compound->body_back();
2827 // If LastStmt is a label, skip down through into the body.
2828 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2829 LastStmt = Label->getSubStmt();
2830
2831 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002832 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002833 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002834
2835 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2836}
Steve Naroffd34e9152007-08-01 22:05:33 +00002837
Steve Naroff1b273c42007-09-16 14:56:35 +00002838Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002839 SourceLocation TypeLoc,
2840 TypeTy *argty,
2841 OffsetOfComponent *CompPtr,
2842 unsigned NumComponents,
2843 SourceLocation RPLoc) {
2844 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2845 assert(!ArgTy.isNull() && "Missing type argument!");
2846
2847 // We must have at least one component that refers to the type, and the first
2848 // one is known to be a field designator. Verify that the ArgTy represents
2849 // a struct/union/class.
2850 if (!ArgTy->isRecordType())
2851 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2852
2853 // Otherwise, create a compound literal expression as the base, and
2854 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002855 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002856
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002857 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2858 // GCC extension, diagnose them.
2859 if (NumComponents != 1)
2860 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2861 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2862
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002863 for (unsigned i = 0; i != NumComponents; ++i) {
2864 const OffsetOfComponent &OC = CompPtr[i];
2865 if (OC.isBrackets) {
2866 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002867 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002868 if (!AT) {
2869 delete Res;
2870 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2871 Res->getType().getAsString());
2872 }
2873
Chris Lattner704fe352007-08-30 17:59:59 +00002874 // FIXME: C++: Verify that operator[] isn't overloaded.
2875
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002876 // C99 6.5.2.1p1
2877 Expr *Idx = static_cast<Expr*>(OC.U.E);
2878 if (!Idx->getType()->isIntegerType())
2879 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2880 Idx->getSourceRange());
2881
2882 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2883 continue;
2884 }
2885
2886 const RecordType *RC = Res->getType()->getAsRecordType();
2887 if (!RC) {
2888 delete Res;
2889 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2890 Res->getType().getAsString());
2891 }
2892
2893 // Get the decl corresponding to this.
2894 RecordDecl *RD = RC->getDecl();
2895 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2896 if (!MemberDecl)
2897 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2898 OC.U.IdentInfo->getName(),
2899 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002900
2901 // FIXME: C++: Verify that MemberDecl isn't a static field.
2902 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002903 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2904 // matter here.
2905 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002906 }
2907
2908 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2909 BuiltinLoc);
2910}
2911
2912
Steve Naroff1b273c42007-09-16 14:56:35 +00002913Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002914 TypeTy *arg1, TypeTy *arg2,
2915 SourceLocation RPLoc) {
2916 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2917 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2918
2919 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2920
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002921 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002922}
2923
Steve Naroff1b273c42007-09-16 14:56:35 +00002924Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002925 ExprTy *expr1, ExprTy *expr2,
2926 SourceLocation RPLoc) {
2927 Expr *CondExpr = static_cast<Expr*>(cond);
2928 Expr *LHSExpr = static_cast<Expr*>(expr1);
2929 Expr *RHSExpr = static_cast<Expr*>(expr2);
2930
2931 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2932
2933 // The conditional expression is required to be a constant expression.
2934 llvm::APSInt condEval(32);
2935 SourceLocation ExpLoc;
2936 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2937 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2938 CondExpr->getSourceRange());
2939
2940 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2941 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2942 RHSExpr->getType();
2943 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2944}
2945
Steve Naroff4eb206b2008-09-03 18:15:37 +00002946//===----------------------------------------------------------------------===//
2947// Clang Extensions.
2948//===----------------------------------------------------------------------===//
2949
2950/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00002951void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002952 // Analyze block parameters.
2953 BlockSemaInfo *BSI = new BlockSemaInfo();
2954
2955 // Add BSI to CurBlock.
2956 BSI->PrevBlockInfo = CurBlock;
2957 CurBlock = BSI;
2958
2959 BSI->ReturnType = 0;
2960 BSI->TheScope = BlockScope;
2961
Steve Naroff090276f2008-10-10 01:28:17 +00002962 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2963 PushDeclContext(BSI->TheDecl);
2964}
2965
2966void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002967 // Analyze arguments to block.
2968 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2969 "Not a function declarator!");
2970 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2971
Steve Naroff090276f2008-10-10 01:28:17 +00002972 CurBlock->hasPrototype = FTI.hasPrototype;
2973 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002974
2975 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2976 // no arguments, not a function that takes a single void argument.
2977 if (FTI.hasPrototype &&
2978 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2979 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2980 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2981 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00002982 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002983 } else if (FTI.hasPrototype) {
2984 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00002985 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2986 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002987 }
Steve Naroff090276f2008-10-10 01:28:17 +00002988 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2989
2990 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2991 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2992 // If this has an identifier, add it to the scope stack.
2993 if ((*AI)->getIdentifier())
2994 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002995}
2996
2997/// ActOnBlockError - If there is an error parsing a block, this callback
2998/// is invoked to pop the information about the block from the action impl.
2999void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3000 // Ensure that CurBlock is deleted.
3001 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3002
3003 // Pop off CurBlock, handle nested blocks.
3004 CurBlock = CurBlock->PrevBlockInfo;
3005
3006 // FIXME: Delete the ParmVarDecl objects as well???
3007
3008}
3009
3010/// ActOnBlockStmtExpr - This is called when the body of a block statement
3011/// literal was successfully completed. ^(int x){...}
3012Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3013 Scope *CurScope) {
3014 // Ensure that CurBlock is deleted.
3015 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3016 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3017
Steve Naroff090276f2008-10-10 01:28:17 +00003018 PopDeclContext();
3019
Steve Naroff4eb206b2008-09-03 18:15:37 +00003020 // Pop off CurBlock, handle nested blocks.
3021 CurBlock = CurBlock->PrevBlockInfo;
3022
3023 QualType RetTy = Context.VoidTy;
3024 if (BSI->ReturnType)
3025 RetTy = QualType(BSI->ReturnType, 0);
3026
3027 llvm::SmallVector<QualType, 8> ArgTypes;
3028 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3029 ArgTypes.push_back(BSI->Params[i]->getType());
3030
3031 QualType BlockTy;
3032 if (!BSI->hasPrototype)
3033 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3034 else
3035 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
3036 BSI->isVariadic);
3037
3038 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003039
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003040 BSI->TheDecl->setBody(Body.take());
3041 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003042}
3043
Nate Begeman67295d02008-01-30 20:50:20 +00003044/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003045/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003046/// The number of arguments has already been validated to match the number of
3047/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003048static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3049 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003050 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003051 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003052 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3053 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003054
3055 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003056 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003057 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003058 return true;
3059}
3060
3061Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3062 SourceLocation *CommaLocs,
3063 SourceLocation BuiltinLoc,
3064 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003065 // __builtin_overload requires at least 2 arguments
3066 if (NumArgs < 2)
3067 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3068 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00003069
Nate Begemane2ce1d92008-01-17 17:46:27 +00003070 // The first argument is required to be a constant expression. It tells us
3071 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003072 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003073 Expr *NParamsExpr = Args[0];
3074 llvm::APSInt constEval(32);
3075 SourceLocation ExpLoc;
3076 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3077 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3078 NParamsExpr->getSourceRange());
3079
3080 // Verify that the number of parameters is > 0
3081 unsigned NumParams = constEval.getZExtValue();
3082 if (NumParams == 0)
3083 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3084 NParamsExpr->getSourceRange());
3085 // Verify that we have at least 1 + NumParams arguments to the builtin.
3086 if ((NumParams + 1) > NumArgs)
3087 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3088 SourceRange(BuiltinLoc, RParenLoc));
3089
3090 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003091 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003092 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003093 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3094 // UsualUnaryConversions will convert the function DeclRefExpr into a
3095 // pointer to function.
3096 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003097 const FunctionTypeProto *FnType = 0;
3098 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3099 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003100
3101 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3102 // parameters, and the number of parameters must match the value passed to
3103 // the builtin.
3104 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00003105 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3106 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00003107
3108 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003109 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003110 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003111 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003112 if (OE)
3113 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3114 OE->getFn()->getSourceRange());
3115 // Remember our match, and continue processing the remaining arguments
3116 // to catch any errors.
3117 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3118 BuiltinLoc, RParenLoc);
3119 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003120 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003121 // Return the newly created OverloadExpr node, if we succeded in matching
3122 // exactly one of the candidate functions.
3123 if (OE)
3124 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003125
3126 // If we didn't find a matching function Expr in the __builtin_overload list
3127 // the return an error.
3128 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003129 for (unsigned i = 0; i != NumParams; ++i) {
3130 if (i != 0) typeNames += ", ";
3131 typeNames += Args[i+1]->getType().getAsString();
3132 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003133
3134 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3135 SourceRange(BuiltinLoc, RParenLoc));
3136}
3137
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003138Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3139 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003140 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003141 Expr *E = static_cast<Expr*>(expr);
3142 QualType T = QualType::getFromOpaquePtr(type);
3143
3144 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003145
3146 // Get the va_list type
3147 QualType VaListType = Context.getBuiltinVaListType();
3148 // Deal with implicit array decay; for example, on x86-64,
3149 // va_list is an array, but it's supposed to decay to
3150 // a pointer for va_arg.
3151 if (VaListType->isArrayType())
3152 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003153 // Make sure the input expression also decays appropriately.
3154 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003155
3156 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003157 return Diag(E->getLocStart(),
3158 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3159 E->getType().getAsString(),
3160 E->getSourceRange());
3161
3162 // FIXME: Warn if a non-POD type is passed in.
3163
3164 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3165}
3166
Chris Lattner5cf216b2008-01-04 18:04:52 +00003167bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3168 SourceLocation Loc,
3169 QualType DstType, QualType SrcType,
3170 Expr *SrcExpr, const char *Flavor) {
3171 // Decode the result (notice that AST's are still created for extensions).
3172 bool isInvalid = false;
3173 unsigned DiagKind;
3174 switch (ConvTy) {
3175 default: assert(0 && "Unknown conversion type");
3176 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003177 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003178 DiagKind = diag::ext_typecheck_convert_pointer_int;
3179 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003180 case IntToPointer:
3181 DiagKind = diag::ext_typecheck_convert_int_pointer;
3182 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003183 case IncompatiblePointer:
3184 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3185 break;
3186 case FunctionVoidPointer:
3187 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3188 break;
3189 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003190 // If the qualifiers lost were because we were applying the
3191 // (deprecated) C++ conversion from a string literal to a char*
3192 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3193 // Ideally, this check would be performed in
3194 // CheckPointerTypesForAssignment. However, that would require a
3195 // bit of refactoring (so that the second argument is an
3196 // expression, rather than a type), which should be done as part
3197 // of a larger effort to fix CheckPointerTypesForAssignment for
3198 // C++ semantics.
3199 if (getLangOptions().CPlusPlus &&
3200 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3201 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003202 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3203 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003204 case IntToBlockPointer:
3205 DiagKind = diag::err_int_to_block_pointer;
3206 break;
3207 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003208 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003209 break;
3210 case BlockVoidPointer:
3211 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3212 break;
Steve Naroff39579072008-10-14 22:18:38 +00003213 case IncompatibleObjCQualifiedId:
3214 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3215 // it can give a more specific diagnostic.
3216 DiagKind = diag::warn_incompatible_qualified_id;
3217 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003218 case Incompatible:
3219 DiagKind = diag::err_typecheck_convert_incompatible;
3220 isInvalid = true;
3221 break;
3222 }
3223
3224 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3225 SrcExpr->getSourceRange());
3226 return isInvalid;
3227}