blob: 563718ccc8d53ebafee175c688f928005611a979 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Chris Lattner299b8842008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattner299b8842008-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 Lattner2aa68822008-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).
Argiris Kirtzidisf580b4d2008-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 Lattner2aa68822008-07-25 21:33:13 +000057 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58 }
Chris Lattner299b8842008-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 Lattner9305c3d2008-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 Lattner299b8842008-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 Lattnerd5a56aa2008-07-26 22:17:49 +0000111 QualType lhs =
112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113 QualType rhs =
114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-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 Naroff87d58b42007-09-16 03:34:24 +0000266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff87d58b42007-09-16 03:34:24 +0000273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera6dcce32008-02-11 00:02:17 +0000283
284 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-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()));
Chris Lattner4b009652007-07-25 00:24:17 +0000289
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000291 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-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 Lattnera6dcce32008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000308 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000309 StringToks[NumStringToks-1].getLocation());
310}
311
Chris Lattnerb2ebd482008-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 Naroff0acc9c92007-09-15 18:49:24 +0000342/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000343/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000344/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000345Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000346 IdentifierInfo &II,
347 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000348 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000349 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000350
351 // If this reference is in an Objective-C method, then ivar lookup happens as
352 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000353 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000354 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-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 Naroffe57c21a2008-04-01 23:04:06 +0000360 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000361 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000362 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-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 Naroff0ccfaa42008-08-10 19:10:41 +0000371 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000372 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000373 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000374 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000375 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000376 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000377 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerc72d22d2008-03-31 00:36:02 +0000382 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerc72d22d2008-03-31 00:36:02 +0000390
Argiris Kirtzidis38f16712008-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
405 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
406 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
407 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
408 true, FD, Loc, FD->getType());
409 }
410
411 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
412 }
Chris Lattner4b009652007-07-25 00:24:17 +0000413 if (isa<TypedefDecl>(D))
414 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000415 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000416 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000417 if (isa<NamespaceDecl>(D))
418 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000419
Steve Naroffd6163f32008-09-05 22:11:13 +0000420 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
421 ValueDecl *VD = cast<ValueDecl>(D);
422
423 // check if referencing an identifier with __attribute__((deprecated)).
424 if (VD->getAttr<DeprecatedAttr>())
425 Diag(Loc, diag::warn_deprecated, VD->getName());
426
427 // Only create DeclRefExpr's for valid Decl's.
428 if (VD->isInvalidDecl())
429 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000430
431 // If the identifier reference is inside a block, and it refers to a value
432 // that is outside the block, create a BlockDeclRefExpr instead of a
433 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
434 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000435 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000436 // We do not do this for things like enum constants, global variables, etc,
437 // as they do not get snapshotted.
438 //
439 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000440 // The BlocksAttr indicates the variable is bound by-reference.
441 if (VD->getAttr<BlocksAttr>())
442 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
443
444 // Variable will be bound by-copy, make it const within the closure.
445 VD->getType().addConst();
446 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
447 }
448 // If this reference is not in a block or if the referenced variable is
449 // within the block, create a normal DeclRefExpr.
450 return new DeclRefExpr(VD, VD->getType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000451}
452
Chris Lattner69909292008-08-10 01:53:14 +0000453Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000454 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000455 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000456
457 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000458 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000459 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
460 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
461 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000462 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000463
464 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000465 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000466 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000467
Chris Lattner7e637512008-01-12 08:14:25 +0000468 // Pre-defined identifiers are of type char[x], where x is the length of the
469 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000470 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000471 if (getCurFunctionDecl())
472 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000473 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000474 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000475
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000476 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000477 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000478 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000479 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000480}
481
Steve Naroff87d58b42007-09-16 03:34:24 +0000482Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000483 llvm::SmallString<16> CharBuffer;
484 CharBuffer.resize(Tok.getLength());
485 const char *ThisTokBegin = &CharBuffer[0];
486 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
487
488 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
489 Tok.getLocation(), PP);
490 if (Literal.hadError())
491 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000492
493 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
494
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000495 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
496 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000497}
498
Steve Naroff87d58b42007-09-16 03:34:24 +0000499Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000500 // fast path for a single digit (which is quite common). A single digit
501 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
502 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000503 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000504
Chris Lattner8cd0e932008-03-05 18:54:05 +0000505 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000506 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000507 Context.IntTy,
508 Tok.getLocation()));
509 }
510 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000511 // Add padding so that NumericLiteralParser can overread by one character.
512 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000513 const char *ThisTokBegin = &IntegerBuffer[0];
514
515 // Get the spelling of the token, which eliminates trigraphs, etc.
516 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000517
Chris Lattner4b009652007-07-25 00:24:17 +0000518 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
519 Tok.getLocation(), PP);
520 if (Literal.hadError)
521 return ExprResult(true);
522
Chris Lattner1de66eb2007-08-26 03:42:43 +0000523 Expr *Res;
524
525 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000526 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000527 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000528 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000529 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000530 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000531 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000532 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000533
534 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
535
Ted Kremenekddedbe22007-11-29 00:56:49 +0000536 // isExact will be set by GetFloatValue().
537 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000538 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000539 Ty, Tok.getLocation());
540
Chris Lattner1de66eb2007-08-26 03:42:43 +0000541 } else if (!Literal.isIntegerLiteral()) {
542 return ExprResult(true);
543 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000544 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000545
Neil Booth7421e9c2007-08-29 22:00:19 +0000546 // long long is a C99 feature.
547 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000548 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000549 Diag(Tok.getLocation(), diag::ext_longlong);
550
Chris Lattner4b009652007-07-25 00:24:17 +0000551 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000552 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000553
554 if (Literal.GetIntegerValue(ResultVal)) {
555 // If this value didn't fit into uintmax_t, warn and force to ull.
556 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000557 Ty = Context.UnsignedLongLongTy;
558 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000559 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000560 } else {
561 // If this value fits into a ULL, try to figure out what else it fits into
562 // according to the rules of C99 6.4.4.1p5.
563
564 // Octal, Hexadecimal, and integers with a U suffix are allowed to
565 // be an unsigned int.
566 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
567
568 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000569 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000570 if (!Literal.isLong && !Literal.isLongLong) {
571 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000572 unsigned IntSize = Context.Target.getIntWidth();
573
Chris Lattner4b009652007-07-25 00:24:17 +0000574 // Does it fit in a unsigned int?
575 if (ResultVal.isIntN(IntSize)) {
576 // Does it fit in a signed int?
577 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000578 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000579 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000580 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000581 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000582 }
Chris Lattner4b009652007-07-25 00:24:17 +0000583 }
584
585 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000586 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000587 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000588
589 // Does it fit in a unsigned long?
590 if (ResultVal.isIntN(LongSize)) {
591 // Does it fit in a signed long?
592 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000593 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000594 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000595 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000596 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000597 }
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
599
600 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000601 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000602 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000603
604 // Does it fit in a unsigned long long?
605 if (ResultVal.isIntN(LongLongSize)) {
606 // Does it fit in a signed long long?
607 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000608 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000609 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000610 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000611 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000612 }
613 }
614
615 // If we still couldn't decide a type, we probably have something that
616 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000617 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000618 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000619 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000620 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000621 }
Chris Lattnere4068872008-05-09 05:59:00 +0000622
623 if (ResultVal.getBitWidth() != Width)
624 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
626
Chris Lattner48d7f382008-04-02 04:24:33 +0000627 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000628 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000629
630 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
631 if (Literal.isImaginary)
632 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
633
634 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000635}
636
Steve Naroff87d58b42007-09-16 03:34:24 +0000637Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000638 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000639 Expr *E = (Expr *)Val;
640 assert((E != 0) && "ActOnParenExpr() missing expr");
641 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000642}
643
644/// The UsualUnaryConversions() function is *not* called by this routine.
645/// See C99 6.3.2.1p[2-4] for more details.
646QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000647 SourceLocation OpLoc,
648 const SourceRange &ExprRange,
649 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000650 // C99 6.5.3.4p1:
651 if (isa<FunctionType>(exprType) && isSizeof)
652 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000653 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000654 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000655 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
656 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000657 else if (exprType->isIncompleteType()) {
658 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
659 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000660 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000661 return QualType(); // error
662 }
663 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
664 return Context.getSizeType();
665}
666
667Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000668ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000669 SourceLocation LPLoc, TypeTy *Ty,
670 SourceLocation RPLoc) {
671 // If error parsing type, ignore.
672 if (Ty == 0) return true;
673
674 // Verify that this is a valid expression.
675 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
676
Chris Lattnerf814d882008-07-25 21:45:37 +0000677 QualType resultType =
678 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000679
680 if (resultType.isNull())
681 return true;
682 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
683}
684
Chris Lattner5110ad52007-08-24 21:41:10 +0000685QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000686 DefaultFunctionArrayConversion(V);
687
Chris Lattnera16e42d2007-08-26 05:39:26 +0000688 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000689 if (const ComplexType *CT = V->getType()->getAsComplexType())
690 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000691
692 // Otherwise they pass through real integer and floating point types here.
693 if (V->getType()->isArithmeticType())
694 return V->getType();
695
696 // Reject anything else.
697 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
698 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000699}
700
701
Chris Lattner4b009652007-07-25 00:24:17 +0000702
Steve Naroff87d58b42007-09-16 03:34:24 +0000703Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000704 tok::TokenKind Kind,
705 ExprTy *Input) {
706 UnaryOperator::Opcode Opc;
707 switch (Kind) {
708 default: assert(0 && "Unknown unary op!");
709 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
710 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
711 }
712 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
713 if (result.isNull())
714 return true;
715 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
716}
717
718Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000719ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000720 ExprTy *Idx, SourceLocation RLoc) {
721 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
722
723 // Perform default conversions.
724 DefaultFunctionArrayConversion(LHSExp);
725 DefaultFunctionArrayConversion(RHSExp);
726
727 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
728
729 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000730 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000731 // in the subscript position. As a result, we need to derive the array base
732 // and index from the expression types.
733 Expr *BaseExpr, *IndexExpr;
734 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000735 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000736 BaseExpr = LHSExp;
737 IndexExpr = RHSExp;
738 // FIXME: need to deal with const...
739 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000740 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000741 // Handle the uncommon case of "123[Ptr]".
742 BaseExpr = RHSExp;
743 IndexExpr = LHSExp;
744 // FIXME: need to deal with const...
745 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000746 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
747 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000748 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000749
750 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000751 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
752 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000753 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000754 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000755 // FIXME: need to deal with const...
756 ResultType = VTy->getElementType();
757 } else {
758 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
759 RHSExp->getSourceRange());
760 }
761 // C99 6.5.2.1p1
762 if (!IndexExpr->getType()->isIntegerType())
763 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
764 IndexExpr->getSourceRange());
765
766 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
767 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000768 // void (*)(int)) and pointers to incomplete types. Functions are not
769 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000770 if (!ResultType->isObjectType())
771 return Diag(BaseExpr->getLocStart(),
772 diag::err_typecheck_subscript_not_object,
773 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
774
775 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
776}
777
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000778QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000779CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000780 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000781 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000782
783 // This flag determines whether or not the component is to be treated as a
784 // special name, or a regular GLSL-style component access.
785 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000786
787 // The vector accessor can't exceed the number of elements.
788 const char *compStr = CompName.getName();
789 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000790 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000791 baseType.getAsString(), SourceRange(CompLoc));
792 return QualType();
793 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000794
795 // Check that we've found one of the special components, or that the component
796 // names must come from the same set.
797 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
798 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
799 SpecialComponent = true;
800 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000801 do
802 compStr++;
803 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
804 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
805 do
806 compStr++;
807 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
808 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
809 do
810 compStr++;
811 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
812 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000813
Nate Begemanc8e51f82008-05-09 06:41:27 +0000814 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000815 // We didn't get to the end of the string. This means the component names
816 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000817 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000818 std::string(compStr,compStr+1), SourceRange(CompLoc));
819 return QualType();
820 }
821 // Each component accessor can't exceed the vector type.
822 compStr = CompName.getName();
823 while (*compStr) {
824 if (vecType->isAccessorWithinNumElements(*compStr))
825 compStr++;
826 else
827 break;
828 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000829 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000830 // We didn't get to the end of the string. This means a component accessor
831 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000832 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000833 baseType.getAsString(), SourceRange(CompLoc));
834 return QualType();
835 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000836
837 // If we have a special component name, verify that the current vector length
838 // is an even number, since all special component names return exactly half
839 // the elements.
840 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000841 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
842 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000843 return QualType();
844 }
845
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000846 // The component accessor looks fine - now we need to compute the actual type.
847 // The vector type is implied by the component accessor. For example,
848 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000849 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
850 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
851 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000852 if (CompSize == 1)
853 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000854
Nate Begemanaf6ed502008-04-18 23:10:10 +0000855 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000856 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000857 // diagostics look bad. We want extended vector types to appear built-in.
858 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
859 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
860 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000861 }
862 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000863}
864
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000865/// constructSetterName - Return the setter name for the given
866/// identifier, i.e. "set" + Name where the initial character of Name
867/// has been capitalized.
868// FIXME: Merge with same routine in Parser. But where should this
869// live?
870static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
871 const IdentifierInfo *Name) {
872 unsigned N = Name->getLength();
873 char *SelectorName = new char[3 + N];
874 memcpy(SelectorName, "set", 3);
875 memcpy(&SelectorName[3], Name->getName(), N);
876 SelectorName[3] = toupper(SelectorName[3]);
877
878 IdentifierInfo *Setter =
879 &Idents.get(SelectorName, &SelectorName[3 + N]);
880 delete[] SelectorName;
881 return Setter;
882}
883
Chris Lattner4b009652007-07-25 00:24:17 +0000884Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000885ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000886 tok::TokenKind OpKind, SourceLocation MemberLoc,
887 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000888 Expr *BaseExpr = static_cast<Expr *>(Base);
889 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000890
891 // Perform default conversions.
892 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000893
Steve Naroff2cb66382007-07-26 03:11:44 +0000894 QualType BaseType = BaseExpr->getType();
895 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000896
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000897 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
898 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000899 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000900 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000901 BaseType = PT->getPointeeType();
902 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000903 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
904 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000905 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000906
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000907 // Handle field access to simple records. This also handles access to fields
908 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000909 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000910 RecordDecl *RDecl = RTy->getDecl();
911 if (RTy->isIncompleteType())
912 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
913 BaseExpr->getSourceRange());
914 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000915 FieldDecl *MemberDecl = RDecl->getMember(&Member);
916 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000917 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
918 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000919
920 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000921 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000922 QualType MemberType = MemberDecl->getType();
923 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000924 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000925 MemberType = MemberType.getQualifiedType(combinedQualifiers);
926
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000927 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000928 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000929 }
930
Chris Lattnere9d71612008-07-21 04:59:05 +0000931 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
932 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000933 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
934 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000935 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000936 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000937 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000938 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000939 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000940 }
941
Chris Lattnere9d71612008-07-21 04:59:05 +0000942 // Handle Objective-C property access, which is "Obj.property" where Obj is a
943 // pointer to a (potentially qualified) interface type.
944 const PointerType *PTy;
945 const ObjCInterfaceType *IFTy;
946 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
947 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
948 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000949
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000950 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000951 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
952 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
953
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000954 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000955 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
956 E = IFTy->qual_end(); I != E; ++I)
957 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
958 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000959
960 // If that failed, look for an "implicit" property by seeing if the nullary
961 // selector is implemented.
962
963 // FIXME: The logic for looking up nullary and unary selectors should be
964 // shared with the code in ActOnInstanceMessage.
965
966 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
967 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
968
969 // If this reference is in an @implementation, check for 'private' methods.
970 if (!Getter)
971 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
972 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
973 if (ObjCImplementationDecl *ImpDecl =
974 ObjCImplementations[ClassDecl->getIdentifier()])
975 Getter = ImpDecl->getInstanceMethod(Sel);
976
977 if (Getter) {
978 // If we found a getter then this may be a valid dot-reference, we
979 // need to also look for the matching setter.
980 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
981 &Member);
982 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
983 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
984
985 if (!Setter) {
986 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
987 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
988 if (ObjCImplementationDecl *ImpDecl =
989 ObjCImplementations[ClassDecl->getIdentifier()])
990 Setter = ImpDecl->getInstanceMethod(SetterSel);
991 }
992
993 // FIXME: There are some issues here. First, we are not
994 // diagnosing accesses to read-only properties because we do not
995 // know if this is a getter or setter yet. Second, we are
996 // checking that the type of the setter matches the type we
997 // expect.
998 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
999 MemberLoc, BaseExpr);
1000 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001001 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001002
1003 // Handle 'field access' to vectors, such as 'V.xx'.
1004 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1005 // Component access limited to variables (reject vec4.rg.g).
1006 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1007 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001008 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1009 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001010 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1011 if (ret.isNull())
1012 return true;
1013 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1014 }
1015
Chris Lattner7d5a8762008-07-21 05:35:34 +00001016 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1017 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001018}
1019
Steve Naroff87d58b42007-09-16 03:34:24 +00001020/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001021/// This provides the location of the left/right parens and a list of comma
1022/// locations.
1023Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001024ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001025 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001026 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1027 Expr *Fn = static_cast<Expr *>(fn);
1028 Expr **Args = reinterpret_cast<Expr**>(args);
1029 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001030 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001031
1032 // Promote the function operand.
1033 UsualUnaryConversions(Fn);
1034
1035 // If we're directly calling a function, get the declaration for
1036 // that function.
1037 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1038 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1039 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1040
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001041 // Make the call expr early, before semantic checks. This guarantees cleanup
1042 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001043 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001044 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001045 const FunctionType *FuncT;
1046 if (!Fn->getType()->isBlockPointerType()) {
1047 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1048 // have type pointer to function".
1049 const PointerType *PT = Fn->getType()->getAsPointerType();
1050 if (PT == 0)
1051 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1052 Fn->getSourceRange());
1053 FuncT = PT->getPointeeType()->getAsFunctionType();
1054 } else { // This is a block call.
1055 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1056 getAsFunctionType();
1057 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001058 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001059 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1060 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001061
1062 // We know the result type of the call, set it.
1063 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001064
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001065 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001066 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1067 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001068 unsigned NumArgsInProto = Proto->getNumArgs();
1069 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001070
Chris Lattner3e254fb2008-04-08 04:40:51 +00001071 // If too few arguments are available (and we don't have default
1072 // arguments for the remaining parameters), don't make the call.
1073 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001074 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001075 // Use default arguments for missing arguments
1076 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001077 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001078 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001079 return Diag(RParenLoc,
1080 !Fn->getType()->isBlockPointerType()
1081 ? diag::err_typecheck_call_too_few_args
1082 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001083 Fn->getSourceRange());
1084 }
1085
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001086 // If too many are passed and not variadic, error on the extras and drop
1087 // them.
1088 if (NumArgs > NumArgsInProto) {
1089 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001090 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001091 !Fn->getType()->isBlockPointerType()
1092 ? diag::err_typecheck_call_too_many_args
1093 : diag::err_typecheck_block_too_many_args,
1094 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001095 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001096 Args[NumArgs-1]->getLocEnd()));
1097 // This deletes the extra arguments.
1098 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001099 }
1100 NumArgsToCheck = NumArgsInProto;
1101 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001102
Chris Lattner4b009652007-07-25 00:24:17 +00001103 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001104 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001105 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001106
1107 Expr *Arg;
1108 if (i < NumArgs)
1109 Arg = Args[i];
1110 else
1111 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001112 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001113
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001114 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001115 AssignConvertType ConvTy =
1116 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001117 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001118
Chris Lattner005ed752008-01-04 18:04:52 +00001119 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1120 ArgType, Arg, "passing"))
1121 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001122 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001123
1124 // If this is a variadic call, handle args passed through "...".
1125 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001126 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001127 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1128 Expr *Arg = Args[i];
1129 DefaultArgumentPromotion(Arg);
1130 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001131 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001132 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001133 } else {
1134 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1135
Steve Naroffdb65e052007-08-28 23:30:39 +00001136 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001137 for (unsigned i = 0; i != NumArgs; i++) {
1138 Expr *Arg = Args[i];
1139 DefaultArgumentPromotion(Arg);
1140 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001141 }
Chris Lattner4b009652007-07-25 00:24:17 +00001142 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001143
Chris Lattner2e64c072007-08-10 20:18:51 +00001144 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001145 if (FDecl)
1146 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001147
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001148 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001149}
1150
1151Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001152ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001153 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001154 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001155 QualType literalType = QualType::getFromOpaquePtr(Ty);
1156 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001157 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001158 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001159
Eli Friedman8c2173d2008-05-20 05:22:08 +00001160 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001161 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001162 return Diag(LParenLoc,
1163 diag::err_variable_object_no_init,
1164 SourceRange(LParenLoc,
1165 literalExpr->getSourceRange().getEnd()));
1166 } else if (literalType->isIncompleteType()) {
1167 return Diag(LParenLoc,
1168 diag::err_typecheck_decl_incomplete_type,
1169 literalType.getAsString(),
1170 SourceRange(LParenLoc,
1171 literalExpr->getSourceRange().getEnd()));
1172 }
1173
Steve Narofff0b23542008-01-10 22:15:12 +00001174 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001175 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001176
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001177 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001178 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001179 if (CheckForConstantInitializer(literalExpr, literalType))
1180 return true;
1181 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001182 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001183}
1184
1185Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001186ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001187 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001188 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001189
Steve Naroff0acc9c92007-09-15 18:49:24 +00001190 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001191 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001192
Chris Lattner48d7f382008-04-02 04:24:33 +00001193 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1194 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1195 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001196}
1197
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001198/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001199bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001200 UsualUnaryConversions(castExpr);
1201
1202 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1203 // type needs to be scalar.
1204 if (castType->isVoidType()) {
1205 // Cast to void allows any expr type.
1206 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1207 // GCC struct/union extension: allow cast to self.
1208 if (Context.getCanonicalType(castType) !=
1209 Context.getCanonicalType(castExpr->getType()) ||
1210 (!castType->isStructureType() && !castType->isUnionType())) {
1211 // Reject any other conversions to non-scalar types.
1212 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1213 castType.getAsString(), castExpr->getSourceRange());
1214 }
1215
1216 // accept this, but emit an ext-warn.
1217 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1218 castType.getAsString(), castExpr->getSourceRange());
1219 } else if (!castExpr->getType()->isScalarType() &&
1220 !castExpr->getType()->isVectorType()) {
1221 return Diag(castExpr->getLocStart(),
1222 diag::err_typecheck_expect_scalar_operand,
1223 castExpr->getType().getAsString(),castExpr->getSourceRange());
1224 } else if (castExpr->getType()->isVectorType()) {
1225 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1226 return true;
1227 } else if (castType->isVectorType()) {
1228 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1229 return true;
1230 }
1231 return false;
1232}
1233
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001234bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001235 assert(VectorTy->isVectorType() && "Not a vector type!");
1236
1237 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001238 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001239 return Diag(R.getBegin(),
1240 Ty->isVectorType() ?
1241 diag::err_invalid_conversion_between_vectors :
1242 diag::err_invalid_conversion_between_vector_and_integer,
1243 VectorTy.getAsString().c_str(),
1244 Ty.getAsString().c_str(), R);
1245 } else
1246 return Diag(R.getBegin(),
1247 diag::err_invalid_conversion_between_vector_and_scalar,
1248 VectorTy.getAsString().c_str(),
1249 Ty.getAsString().c_str(), R);
1250
1251 return false;
1252}
1253
Chris Lattner4b009652007-07-25 00:24:17 +00001254Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001255ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001256 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001257 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001258
1259 Expr *castExpr = static_cast<Expr*>(Op);
1260 QualType castType = QualType::getFromOpaquePtr(Ty);
1261
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001262 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1263 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001264 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001265}
1266
Chris Lattner98a425c2007-11-26 01:40:58 +00001267/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1268/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001269inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1270 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1271 UsualUnaryConversions(cond);
1272 UsualUnaryConversions(lex);
1273 UsualUnaryConversions(rex);
1274 QualType condT = cond->getType();
1275 QualType lexT = lex->getType();
1276 QualType rexT = rex->getType();
1277
1278 // first, check the condition.
1279 if (!condT->isScalarType()) { // C99 6.5.15p2
1280 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1281 condT.getAsString());
1282 return QualType();
1283 }
Chris Lattner992ae932008-01-06 22:42:25 +00001284
1285 // Now check the two expressions.
1286
1287 // If both operands have arithmetic type, do the usual arithmetic conversions
1288 // to find a common type: C99 6.5.15p3,5.
1289 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001290 UsualArithmeticConversions(lex, rex);
1291 return lex->getType();
1292 }
Chris Lattner992ae932008-01-06 22:42:25 +00001293
1294 // If both operands are the same structure or union type, the result is that
1295 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001296 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001297 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001298 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001299 // "If both the operands have structure or union type, the result has
1300 // that type." This implies that CV qualifiers are dropped.
1301 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001302 }
Chris Lattner992ae932008-01-06 22:42:25 +00001303
1304 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001305 // The following || allows only one side to be void (a GCC-ism).
1306 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001307 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001308 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1309 rex->getSourceRange());
1310 if (!rexT->isVoidType())
1311 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001312 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001313 ImpCastExprToType(lex, Context.VoidTy);
1314 ImpCastExprToType(rex, Context.VoidTy);
1315 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001316 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001317 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1318 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001319 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1320 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001321 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001322 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001323 return lexT;
1324 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001325 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1326 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001327 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001328 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001329 return rexT;
1330 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001331 // Handle the case where both operands are pointers before we handle null
1332 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001333 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1334 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1335 // get the "pointed to" types
1336 QualType lhptee = LHSPT->getPointeeType();
1337 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001338
Chris Lattner71225142007-07-31 21:27:01 +00001339 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1340 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001341 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001342 // Figure out necessary qualifiers (C99 6.5.15p6)
1343 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001344 QualType destType = Context.getPointerType(destPointee);
1345 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1346 ImpCastExprToType(rex, destType); // promote to void*
1347 return destType;
1348 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001349 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001350 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001351 QualType destType = Context.getPointerType(destPointee);
1352 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1353 ImpCastExprToType(rex, destType); // promote to void*
1354 return destType;
1355 }
Chris Lattner4b009652007-07-25 00:24:17 +00001356
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001357 QualType compositeType = lexT;
1358
1359 // If either type is an Objective-C object type then check
1360 // compatibility according to Objective-C.
1361 if (Context.isObjCObjectPointerType(lexT) ||
1362 Context.isObjCObjectPointerType(rexT)) {
1363 // If both operands are interfaces and either operand can be
1364 // assigned to the other, use that type as the composite
1365 // type. This allows
1366 // xxx ? (A*) a : (B*) b
1367 // where B is a subclass of A.
1368 //
1369 // Additionally, as for assignment, if either type is 'id'
1370 // allow silent coercion. Finally, if the types are
1371 // incompatible then make sure to use 'id' as the composite
1372 // type so the result is acceptable for sending messages to.
1373
1374 // FIXME: This code should not be localized to here. Also this
1375 // should use a compatible check instead of abusing the
1376 // canAssignObjCInterfaces code.
1377 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1378 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1379 if (LHSIface && RHSIface &&
1380 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1381 compositeType = lexT;
1382 } else if (LHSIface && RHSIface &&
1383 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1384 compositeType = rexT;
1385 } else if (Context.isObjCIdType(lhptee) ||
1386 Context.isObjCIdType(rhptee)) {
1387 // FIXME: This code looks wrong, because isObjCIdType checks
1388 // the struct but getObjCIdType returns the pointer to
1389 // struct. This is horrible and should be fixed.
1390 compositeType = Context.getObjCIdType();
1391 } else {
1392 QualType incompatTy = Context.getObjCIdType();
1393 ImpCastExprToType(lex, incompatTy);
1394 ImpCastExprToType(rex, incompatTy);
1395 return incompatTy;
1396 }
1397 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1398 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001399 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001400 lexT.getAsString(), rexT.getAsString(),
1401 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001402 // In this situation, we assume void* type. No especially good
1403 // reason, but this is what gcc does, and we do have to pick
1404 // to get a consistent AST.
1405 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001406 ImpCastExprToType(lex, incompatTy);
1407 ImpCastExprToType(rex, incompatTy);
1408 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001409 }
1410 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001411 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1412 // differently qualified versions of compatible types, the result type is
1413 // a pointer to an appropriately qualified version of the *composite*
1414 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001415 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001416 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001417 ImpCastExprToType(lex, compositeType);
1418 ImpCastExprToType(rex, compositeType);
1419 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001420 }
Chris Lattner4b009652007-07-25 00:24:17 +00001421 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001422 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1423 // evaluates to "struct objc_object *" (and is handled above when comparing
1424 // id with statically typed objects).
1425 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1426 // GCC allows qualified id and any Objective-C type to devolve to
1427 // id. Currently localizing to here until clear this should be
1428 // part of ObjCQualifiedIdTypesAreCompatible.
1429 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1430 (lexT->isObjCQualifiedIdType() &&
1431 Context.isObjCObjectPointerType(rexT)) ||
1432 (rexT->isObjCQualifiedIdType() &&
1433 Context.isObjCObjectPointerType(lexT))) {
1434 // FIXME: This is not the correct composite type. This only
1435 // happens to work because id can more or less be used anywhere,
1436 // however this may change the type of method sends.
1437 // FIXME: gcc adds some type-checking of the arguments and emits
1438 // (confusing) incompatible comparison warnings in some
1439 // cases. Investigate.
1440 QualType compositeType = Context.getObjCIdType();
1441 ImpCastExprToType(lex, compositeType);
1442 ImpCastExprToType(rex, compositeType);
1443 return compositeType;
1444 }
1445 }
1446
Steve Naroff3eac7692008-09-10 19:17:48 +00001447 // Selection between block pointer types is ok as long as they are the same.
1448 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1449 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1450 return lexT;
1451
Chris Lattner992ae932008-01-06 22:42:25 +00001452 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001453 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1454 lexT.getAsString(), rexT.getAsString(),
1455 lex->getSourceRange(), rex->getSourceRange());
1456 return QualType();
1457}
1458
Steve Naroff87d58b42007-09-16 03:34:24 +00001459/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001460/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001461Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001462 SourceLocation ColonLoc,
1463 ExprTy *Cond, ExprTy *LHS,
1464 ExprTy *RHS) {
1465 Expr *CondExpr = (Expr *) Cond;
1466 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001467
1468 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1469 // was the condition.
1470 bool isLHSNull = LHSExpr == 0;
1471 if (isLHSNull)
1472 LHSExpr = CondExpr;
1473
Chris Lattner4b009652007-07-25 00:24:17 +00001474 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1475 RHSExpr, QuestionLoc);
1476 if (result.isNull())
1477 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001478 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1479 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001480}
1481
Chris Lattner4b009652007-07-25 00:24:17 +00001482
1483// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1484// being closely modeled after the C99 spec:-). The odd characteristic of this
1485// routine is it effectively iqnores the qualifiers on the top level pointee.
1486// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1487// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001488Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001489Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1490 QualType lhptee, rhptee;
1491
1492 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001493 lhptee = lhsType->getAsPointerType()->getPointeeType();
1494 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001495
1496 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001497 lhptee = Context.getCanonicalType(lhptee);
1498 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001499
Chris Lattner005ed752008-01-04 18:04:52 +00001500 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001501
1502 // C99 6.5.16.1p1: This following citation is common to constraints
1503 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1504 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001505 // FIXME: Handle ASQualType
1506 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1507 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001508 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001509
1510 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1511 // incomplete type and the other is a pointer to a qualified or unqualified
1512 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001513 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001514 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001515 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001516
1517 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001518 assert(rhptee->isFunctionType());
1519 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001520 }
1521
1522 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001523 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001524 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001525
1526 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001527 assert(lhptee->isFunctionType());
1528 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001529 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001530
1531 // Check for ObjC interfaces
1532 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1533 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1534 if (LHSIface && RHSIface &&
1535 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1536 return ConvTy;
1537
1538 // ID acts sort of like void* for ObjC interfaces
1539 if (LHSIface && Context.isObjCIdType(rhptee))
1540 return ConvTy;
1541 if (RHSIface && Context.isObjCIdType(lhptee))
1542 return ConvTy;
1543
Chris Lattner4b009652007-07-25 00:24:17 +00001544 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1545 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001546 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1547 rhptee.getUnqualifiedType()))
1548 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001549 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001550}
1551
Steve Naroff3454b6c2008-09-04 15:10:53 +00001552/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1553/// block pointer types are compatible or whether a block and normal pointer
1554/// are compatible. It is more restrict than comparing two function pointer
1555// types.
1556Sema::AssignConvertType
1557Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1558 QualType rhsType) {
1559 QualType lhptee, rhptee;
1560
1561 // get the "pointed to" type (ignoring qualifiers at the top level)
1562 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1563 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1564
1565 // make sure we operate on the canonical type
1566 lhptee = Context.getCanonicalType(lhptee);
1567 rhptee = Context.getCanonicalType(rhptee);
1568
1569 AssignConvertType ConvTy = Compatible;
1570
1571 // For blocks we enforce that qualifiers are identical.
1572 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1573 ConvTy = CompatiblePointerDiscardsQualifiers;
1574
1575 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1576 return IncompatibleBlockPointer;
1577 return ConvTy;
1578}
1579
Chris Lattner4b009652007-07-25 00:24:17 +00001580/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1581/// has code to accommodate several GCC extensions when type checking
1582/// pointers. Here are some objectionable examples that GCC considers warnings:
1583///
1584/// int a, *pint;
1585/// short *pshort;
1586/// struct foo *pfoo;
1587///
1588/// pint = pshort; // warning: assignment from incompatible pointer type
1589/// a = pint; // warning: assignment makes integer from pointer without a cast
1590/// pint = a; // warning: assignment makes pointer from integer without a cast
1591/// pint = pfoo; // warning: assignment from incompatible pointer type
1592///
1593/// As a result, the code for dealing with pointers is more complex than the
1594/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001595///
Chris Lattner005ed752008-01-04 18:04:52 +00001596Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001597Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001598 // Get canonical types. We're not formatting these types, just comparing
1599 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001600 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1601 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001602
1603 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001604 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001605
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001606 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001607 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001608 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001609 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001610 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001611
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001612 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1613 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001614 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001615 // Relax integer conversions like we do for pointers below.
1616 if (rhsType->isIntegerType())
1617 return IntToPointer;
1618 if (lhsType->isIntegerType())
1619 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001620 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001621 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001622
Nate Begemanc5f0f652008-07-14 18:02:46 +00001623 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001624 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001625 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1626 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001627 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001628
Nate Begemanc5f0f652008-07-14 18:02:46 +00001629 // If we are allowing lax vector conversions, and LHS and RHS are both
1630 // vectors, the total size only needs to be the same. This is a bitcast;
1631 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001632 if (getLangOptions().LaxVectorConversions &&
1633 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001634 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1635 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001636 }
1637 return Incompatible;
1638 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001639
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001640 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001641 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001642
Chris Lattner390564e2008-04-07 06:49:41 +00001643 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001644 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001645 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001646
Chris Lattner390564e2008-04-07 06:49:41 +00001647 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001648 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001649
Steve Naroffa982c712008-09-29 18:10:17 +00001650 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001651 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001652 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001653
1654 // Treat block pointers as objects.
1655 if (getLangOptions().ObjC1 &&
1656 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1657 return Compatible;
1658 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001659 return Incompatible;
1660 }
1661
1662 if (isa<BlockPointerType>(lhsType)) {
1663 if (rhsType->isIntegerType())
1664 return IntToPointer;
1665
Steve Naroffa982c712008-09-29 18:10:17 +00001666 // Treat block pointers as objects.
1667 if (getLangOptions().ObjC1 &&
1668 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1669 return Compatible;
1670
Steve Naroff3454b6c2008-09-04 15:10:53 +00001671 if (rhsType->isBlockPointerType())
1672 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1673
1674 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1675 if (RHSPT->getPointeeType()->isVoidType())
1676 return BlockVoidPointer;
1677 }
Chris Lattner1853da22008-01-04 23:18:45 +00001678 return Incompatible;
1679 }
1680
Chris Lattner390564e2008-04-07 06:49:41 +00001681 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001682 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001683 if (lhsType == Context.BoolTy)
1684 return Compatible;
1685
1686 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001687 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001688
Chris Lattner390564e2008-04-07 06:49:41 +00001689 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001690 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001691
1692 if (isa<BlockPointerType>(lhsType) &&
1693 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1694 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001695 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001696 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001697
Chris Lattner1853da22008-01-04 23:18:45 +00001698 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001699 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001700 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001701 }
1702 return Incompatible;
1703}
1704
Chris Lattner005ed752008-01-04 18:04:52 +00001705Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001706Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001707 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1708 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001709 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1710 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001711 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001712 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001713 return Compatible;
1714 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001715
1716 // We don't allow conversion of non-null-pointer constants to integers.
1717 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1718 return IntToBlockPointer;
1719
Chris Lattner5f505bf2007-10-16 02:55:40 +00001720 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001721 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001722 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001723 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001724 //
1725 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1726 // are better understood.
1727 if (!lhsType->isReferenceType())
1728 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001729
Chris Lattner005ed752008-01-04 18:04:52 +00001730 Sema::AssignConvertType result =
1731 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001732
1733 // C99 6.5.16.1p2: The value of the right operand is converted to the
1734 // type of the assignment expression.
1735 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001736 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001737 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001738}
1739
Chris Lattner005ed752008-01-04 18:04:52 +00001740Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001741Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1742 return CheckAssignmentConstraints(lhsType, rhsType);
1743}
1744
Chris Lattner2c8bff72007-12-12 05:47:28 +00001745QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001746 Diag(loc, diag::err_typecheck_invalid_operands,
1747 lex->getType().getAsString(), rex->getType().getAsString(),
1748 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001749 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001750}
1751
1752inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1753 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001754 // For conversion purposes, we ignore any qualifiers.
1755 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001756 QualType lhsType =
1757 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1758 QualType rhsType =
1759 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001760
Nate Begemanc5f0f652008-07-14 18:02:46 +00001761 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001762 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001763 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001764
Nate Begemanc5f0f652008-07-14 18:02:46 +00001765 // Handle the case of a vector & extvector type of the same size and element
1766 // type. It would be nice if we only had one vector type someday.
1767 if (getLangOptions().LaxVectorConversions)
1768 if (const VectorType *LV = lhsType->getAsVectorType())
1769 if (const VectorType *RV = rhsType->getAsVectorType())
1770 if (LV->getElementType() == RV->getElementType() &&
1771 LV->getNumElements() == RV->getNumElements())
1772 return lhsType->isExtVectorType() ? lhsType : rhsType;
1773
1774 // If the lhs is an extended vector and the rhs is a scalar of the same type
1775 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001776 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001777 QualType eltType = V->getElementType();
1778
1779 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1780 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1781 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001782 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001783 return lhsType;
1784 }
1785 }
1786
Nate Begemanc5f0f652008-07-14 18:02:46 +00001787 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001788 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001789 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001790 QualType eltType = V->getElementType();
1791
1792 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1793 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1794 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001795 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001796 return rhsType;
1797 }
1798 }
1799
Chris Lattner4b009652007-07-25 00:24:17 +00001800 // You cannot convert between vector values of different size.
1801 Diag(loc, diag::err_typecheck_vector_not_convertable,
1802 lex->getType().getAsString(), rex->getType().getAsString(),
1803 lex->getSourceRange(), rex->getSourceRange());
1804 return QualType();
1805}
1806
1807inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001808 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001809{
1810 QualType lhsType = lex->getType(), rhsType = rex->getType();
1811
1812 if (lhsType->isVectorType() || rhsType->isVectorType())
1813 return CheckVectorOperands(loc, lex, rex);
1814
Steve Naroff8f708362007-08-24 19:07:16 +00001815 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001816
Chris Lattner4b009652007-07-25 00:24:17 +00001817 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001818 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001819 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001820}
1821
1822inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001823 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001824{
1825 QualType lhsType = lex->getType(), rhsType = rex->getType();
1826
Steve Naroff8f708362007-08-24 19:07:16 +00001827 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001828
Chris Lattner4b009652007-07-25 00:24:17 +00001829 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001830 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001831 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001832}
1833
1834inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001835 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001836{
1837 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1838 return CheckVectorOperands(loc, lex, rex);
1839
Steve Naroff8f708362007-08-24 19:07:16 +00001840 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001841
Chris Lattner4b009652007-07-25 00:24:17 +00001842 // handle the common case first (both operands are arithmetic).
1843 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001844 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001845
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001846 // Put any potential pointer into PExp
1847 Expr* PExp = lex, *IExp = rex;
1848 if (IExp->getType()->isPointerType())
1849 std::swap(PExp, IExp);
1850
1851 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1852 if (IExp->getType()->isIntegerType()) {
1853 // Check for arithmetic on pointers to incomplete types
1854 if (!PTy->getPointeeType()->isObjectType()) {
1855 if (PTy->getPointeeType()->isVoidType()) {
1856 Diag(loc, diag::ext_gnu_void_ptr,
1857 lex->getSourceRange(), rex->getSourceRange());
1858 } else {
1859 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1860 lex->getType().getAsString(), lex->getSourceRange());
1861 return QualType();
1862 }
1863 }
1864 return PExp->getType();
1865 }
1866 }
1867
Chris Lattner2c8bff72007-12-12 05:47:28 +00001868 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001869}
1870
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001871// C99 6.5.6
1872QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1873 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001874 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1875 return CheckVectorOperands(loc, lex, rex);
1876
Steve Naroff8f708362007-08-24 19:07:16 +00001877 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001878
Chris Lattnerf6da2912007-12-09 21:53:25 +00001879 // Enforce type constraints: C99 6.5.6p3.
1880
1881 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001882 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001883 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001884
1885 // Either ptr - int or ptr - ptr.
1886 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001887 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001888
Chris Lattnerf6da2912007-12-09 21:53:25 +00001889 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001890 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001891 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001892 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001893 Diag(loc, diag::ext_gnu_void_ptr,
1894 lex->getSourceRange(), rex->getSourceRange());
1895 } else {
1896 Diag(loc, diag::err_typecheck_sub_ptr_object,
1897 lex->getType().getAsString(), lex->getSourceRange());
1898 return QualType();
1899 }
1900 }
1901
1902 // The result type of a pointer-int computation is the pointer type.
1903 if (rex->getType()->isIntegerType())
1904 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001905
Chris Lattnerf6da2912007-12-09 21:53:25 +00001906 // Handle pointer-pointer subtractions.
1907 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001908 QualType rpointee = RHSPTy->getPointeeType();
1909
Chris Lattnerf6da2912007-12-09 21:53:25 +00001910 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001911 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001912 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001913 if (rpointee->isVoidType()) {
1914 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001915 Diag(loc, diag::ext_gnu_void_ptr,
1916 lex->getSourceRange(), rex->getSourceRange());
1917 } else {
1918 Diag(loc, diag::err_typecheck_sub_ptr_object,
1919 rex->getType().getAsString(), rex->getSourceRange());
1920 return QualType();
1921 }
1922 }
1923
1924 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00001925 if (!Context.typesAreCompatible(
1926 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1927 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001928 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1929 lex->getType().getAsString(), rex->getType().getAsString(),
1930 lex->getSourceRange(), rex->getSourceRange());
1931 return QualType();
1932 }
1933
1934 return Context.getPointerDiffType();
1935 }
1936 }
1937
Chris Lattner2c8bff72007-12-12 05:47:28 +00001938 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001939}
1940
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001941// C99 6.5.7
1942QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1943 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001944 // C99 6.5.7p2: Each of the operands shall have integer type.
1945 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1946 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001947
Chris Lattner2c8bff72007-12-12 05:47:28 +00001948 // Shifts don't perform usual arithmetic conversions, they just do integer
1949 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001950 if (!isCompAssign)
1951 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001952 UsualUnaryConversions(rex);
1953
1954 // "The type of the result is that of the promoted left operand."
1955 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001956}
1957
Eli Friedman0d9549b2008-08-22 00:56:42 +00001958static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1959 ASTContext& Context) {
1960 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1961 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1962 // ID acts sort of like void* for ObjC interfaces
1963 if (LHSIface && Context.isObjCIdType(RHS))
1964 return true;
1965 if (RHSIface && Context.isObjCIdType(LHS))
1966 return true;
1967 if (!LHSIface || !RHSIface)
1968 return false;
1969 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1970 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1971}
1972
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001973// C99 6.5.8
1974QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1975 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001976 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1977 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1978
Chris Lattner254f3bc2007-08-26 01:18:55 +00001979 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001980 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1981 UsualArithmeticConversions(lex, rex);
1982 else {
1983 UsualUnaryConversions(lex);
1984 UsualUnaryConversions(rex);
1985 }
Chris Lattner4b009652007-07-25 00:24:17 +00001986 QualType lType = lex->getType();
1987 QualType rType = rex->getType();
1988
Ted Kremenek486509e2007-10-29 17:13:39 +00001989 // For non-floating point types, check for self-comparisons of the form
1990 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1991 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001992 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001993 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1994 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001995 if (DRL->getDecl() == DRR->getDecl())
1996 Diag(loc, diag::warn_selfcomparison);
1997 }
1998
Chris Lattner254f3bc2007-08-26 01:18:55 +00001999 if (isRelational) {
2000 if (lType->isRealType() && rType->isRealType())
2001 return Context.IntTy;
2002 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002003 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002004 if (lType->isFloatingType()) {
2005 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002006 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002007 }
2008
Chris Lattner254f3bc2007-08-26 01:18:55 +00002009 if (lType->isArithmeticType() && rType->isArithmeticType())
2010 return Context.IntTy;
2011 }
Chris Lattner4b009652007-07-25 00:24:17 +00002012
Chris Lattner22be8422007-08-26 01:10:14 +00002013 bool LHSIsNull = lex->isNullPointerConstant(Context);
2014 bool RHSIsNull = rex->isNullPointerConstant(Context);
2015
Chris Lattner254f3bc2007-08-26 01:18:55 +00002016 // All of the following pointer related warnings are GCC extensions, except
2017 // when handling null pointer constants. One day, we can consider making them
2018 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002019 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002020 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002021 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002022 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002023 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002024
Steve Naroff3b435622007-11-13 14:57:38 +00002025 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002026 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2027 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002028 RCanPointeeTy.getUnqualifiedType()) &&
2029 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002030 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2031 lType.getAsString(), rType.getAsString(),
2032 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002033 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002034 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002035 return Context.IntTy;
2036 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002037 // Handle block pointer types.
2038 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2039 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2040 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2041
2042 if (!LHSIsNull && !RHSIsNull &&
2043 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2044 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2045 lType.getAsString(), rType.getAsString(),
2046 lex->getSourceRange(), rex->getSourceRange());
2047 }
2048 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2049 return Context.IntTy;
2050 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002051 // Allow block pointers to be compared with null pointer constants.
2052 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2053 (lType->isPointerType() && rType->isBlockPointerType())) {
2054 if (!LHSIsNull && !RHSIsNull) {
2055 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2056 lType.getAsString(), rType.getAsString(),
2057 lex->getSourceRange(), rex->getSourceRange());
2058 }
2059 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2060 return Context.IntTy;
2061 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002062
Steve Naroff936c4362008-06-03 14:04:54 +00002063 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2064 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2065 ImpCastExprToType(rex, lType);
2066 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002067 } else {
2068 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2069 Diag(loc, diag::warn_incompatible_qualified_id_operands,
2070 lex->getType().getAsString(), rex->getType().getAsString(),
2071 lex->getSourceRange(), rex->getSourceRange());
2072 return QualType();
2073 }
Steve Naroff936c4362008-06-03 14:04:54 +00002074 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002075 }
Steve Naroff936c4362008-06-03 14:04:54 +00002076 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2077 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002078 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002079 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2080 lType.getAsString(), rType.getAsString(),
2081 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002082 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002083 return Context.IntTy;
2084 }
Steve Naroff936c4362008-06-03 14:04:54 +00002085 if (lType->isIntegerType() &&
2086 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002087 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002088 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2089 lType.getAsString(), rType.getAsString(),
2090 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002091 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002092 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002093 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002094 // Handle block pointers.
2095 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2096 if (!RHSIsNull)
2097 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2098 lType.getAsString(), rType.getAsString(),
2099 lex->getSourceRange(), rex->getSourceRange());
2100 ImpCastExprToType(rex, lType); // promote the integer to pointer
2101 return Context.IntTy;
2102 }
2103 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2104 if (!LHSIsNull)
2105 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2106 lType.getAsString(), rType.getAsString(),
2107 lex->getSourceRange(), rex->getSourceRange());
2108 ImpCastExprToType(lex, rType); // promote the integer to pointer
2109 return Context.IntTy;
2110 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002111 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002112}
2113
Nate Begemanc5f0f652008-07-14 18:02:46 +00002114/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2115/// operates on extended vector types. Instead of producing an IntTy result,
2116/// like a scalar comparison, a vector comparison produces a vector of integer
2117/// types.
2118QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2119 SourceLocation loc,
2120 bool isRelational) {
2121 // Check to make sure we're operating on vectors of the same type and width,
2122 // Allowing one side to be a scalar of element type.
2123 QualType vType = CheckVectorOperands(loc, lex, rex);
2124 if (vType.isNull())
2125 return vType;
2126
2127 QualType lType = lex->getType();
2128 QualType rType = rex->getType();
2129
2130 // For non-floating point types, check for self-comparisons of the form
2131 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2132 // often indicate logic errors in the program.
2133 if (!lType->isFloatingType()) {
2134 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2135 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2136 if (DRL->getDecl() == DRR->getDecl())
2137 Diag(loc, diag::warn_selfcomparison);
2138 }
2139
2140 // Check for comparisons of floating point operands using != and ==.
2141 if (!isRelational && lType->isFloatingType()) {
2142 assert (rType->isFloatingType());
2143 CheckFloatComparison(loc,lex,rex);
2144 }
2145
2146 // Return the type for the comparison, which is the same as vector type for
2147 // integer vectors, or an integer type of identical size and number of
2148 // elements for floating point vectors.
2149 if (lType->isIntegerType())
2150 return lType;
2151
2152 const VectorType *VTy = lType->getAsVectorType();
2153
2154 // FIXME: need to deal with non-32b int / non-64b long long
2155 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2156 if (TypeSize == 32) {
2157 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2158 }
2159 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2160 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2161}
2162
Chris Lattner4b009652007-07-25 00:24:17 +00002163inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002164 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002165{
2166 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2167 return CheckVectorOperands(loc, lex, rex);
2168
Steve Naroff8f708362007-08-24 19:07:16 +00002169 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002170
2171 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002172 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002173 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002174}
2175
2176inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2177 Expr *&lex, Expr *&rex, SourceLocation loc)
2178{
2179 UsualUnaryConversions(lex);
2180 UsualUnaryConversions(rex);
2181
Eli Friedmanbea3f842008-05-13 20:16:47 +00002182 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002183 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002184 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002185}
2186
2187inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002188 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002189{
2190 QualType lhsType = lex->getType();
2191 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002192 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002193
2194 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002195 case Expr::MLV_Valid:
2196 break;
2197 case Expr::MLV_ConstQualified:
2198 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2199 return QualType();
2200 case Expr::MLV_ArrayType:
2201 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2202 lhsType.getAsString(), lex->getSourceRange());
2203 return QualType();
2204 case Expr::MLV_NotObjectType:
2205 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2206 lhsType.getAsString(), lex->getSourceRange());
2207 return QualType();
2208 case Expr::MLV_InvalidExpression:
2209 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2210 lex->getSourceRange());
2211 return QualType();
2212 case Expr::MLV_IncompleteType:
2213 case Expr::MLV_IncompleteVoidType:
2214 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2215 lhsType.getAsString(), lex->getSourceRange());
2216 return QualType();
2217 case Expr::MLV_DuplicateVectorComponents:
2218 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2219 lex->getSourceRange());
2220 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002221 case Expr::MLV_NotBlockQualified:
2222 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2223 lex->getSourceRange());
2224 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002225 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002226
Chris Lattner005ed752008-01-04 18:04:52 +00002227 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002228 if (compoundType.isNull()) {
2229 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002230 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002231
2232 // If the RHS is a unary plus or minus, check to see if they = and + are
2233 // right next to each other. If so, the user may have typo'd "x =+ 4"
2234 // instead of "x += 4".
2235 Expr *RHSCheck = rex;
2236 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2237 RHSCheck = ICE->getSubExpr();
2238 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2239 if ((UO->getOpcode() == UnaryOperator::Plus ||
2240 UO->getOpcode() == UnaryOperator::Minus) &&
2241 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2242 // Only if the two operators are exactly adjacent.
2243 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2244 Diag(loc, diag::warn_not_compound_assign,
2245 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2246 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2247 }
2248 } else {
2249 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002250 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002251 }
Chris Lattner005ed752008-01-04 18:04:52 +00002252
2253 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2254 rex, "assigning"))
2255 return QualType();
2256
Chris Lattner4b009652007-07-25 00:24:17 +00002257 // C99 6.5.16p3: The type of an assignment expression is the type of the
2258 // left operand unless the left operand has qualified type, in which case
2259 // it is the unqualified version of the type of the left operand.
2260 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2261 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002262 // C++ 5.17p1: the type of the assignment expression is that of its left
2263 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002264 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002265}
2266
2267inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2268 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002269
2270 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2271 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002272 return rex->getType();
2273}
2274
2275/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2276/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2277QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2278 QualType resType = op->getType();
2279 assert(!resType.isNull() && "no type for increment/decrement expression");
2280
Steve Naroffd30e1932007-08-24 17:20:07 +00002281 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002282 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002283 if (pt->getPointeeType()->isVoidType()) {
2284 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2285 } else if (!pt->getPointeeType()->isObjectType()) {
2286 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002287 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2288 resType.getAsString(), op->getSourceRange());
2289 return QualType();
2290 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002291 } else if (!resType->isRealType()) {
2292 if (resType->isComplexType())
2293 // C99 does not support ++/-- on complex types.
2294 Diag(OpLoc, diag::ext_integer_increment_complex,
2295 resType.getAsString(), op->getSourceRange());
2296 else {
2297 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2298 resType.getAsString(), op->getSourceRange());
2299 return QualType();
2300 }
Chris Lattner4b009652007-07-25 00:24:17 +00002301 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002302 // At this point, we know we have a real, complex or pointer type.
2303 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002304 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002305 if (mlval != Expr::MLV_Valid) {
2306 // FIXME: emit a more precise diagnostic...
2307 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2308 op->getSourceRange());
2309 return QualType();
2310 }
2311 return resType;
2312}
2313
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002314/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002315/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002316/// where the declaration is needed for type checking. We only need to
2317/// handle cases when the expression references a function designator
2318/// or is an lvalue. Here are some examples:
2319/// - &(x) => x
2320/// - &*****f => f for f a function designator.
2321/// - &s.xx => s
2322/// - &s.zz[1].yy -> s, if zz is an array
2323/// - *(x + 1) -> x, if x is an array
2324/// - &"123"[2] -> 0
2325/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00002326static ValueDecl *getPrimaryDecl(Expr *E) {
2327 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002328 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002329 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002330 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002331 // Fields cannot be declared with a 'register' storage class.
2332 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002333 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002334 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002335 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002336 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002337 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002338
Chris Lattner48d7f382008-04-02 04:24:33 +00002339 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00002340 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002341 return 0;
2342 else
2343 return VD;
2344 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002345 case Stmt::UnaryOperatorClass: {
2346 UnaryOperator *UO = cast<UnaryOperator>(E);
2347
2348 switch(UO->getOpcode()) {
2349 case UnaryOperator::Deref: {
2350 // *(X + 1) refers to X if X is not a pointer.
2351 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2352 if (!VD || VD->getType()->isPointerType())
2353 return 0;
2354 return VD;
2355 }
2356 case UnaryOperator::Real:
2357 case UnaryOperator::Imag:
2358 case UnaryOperator::Extension:
2359 return getPrimaryDecl(UO->getSubExpr());
2360 default:
2361 return 0;
2362 }
2363 }
2364 case Stmt::BinaryOperatorClass: {
2365 BinaryOperator *BO = cast<BinaryOperator>(E);
2366
2367 // Handle cases involving pointer arithmetic. The result of an
2368 // Assign or AddAssign is not an lvalue so they can be ignored.
2369
2370 // (x + n) or (n + x) => x
2371 if (BO->getOpcode() == BinaryOperator::Add) {
2372 if (BO->getLHS()->getType()->isPointerType()) {
2373 return getPrimaryDecl(BO->getLHS());
2374 } else if (BO->getRHS()->getType()->isPointerType()) {
2375 return getPrimaryDecl(BO->getRHS());
2376 }
2377 }
2378
2379 return 0;
2380 }
Chris Lattner4b009652007-07-25 00:24:17 +00002381 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002382 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002383 case Stmt::ImplicitCastExprClass:
2384 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002385 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002386 default:
2387 return 0;
2388 }
2389}
2390
2391/// CheckAddressOfOperand - The operand of & must be either a function
2392/// designator or an lvalue designating an object. If it is an lvalue, the
2393/// object cannot be declared with storage class register or be a bit field.
2394/// Note: The usual conversions are *not* applied to the operand of the &
2395/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2396QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002397 if (getLangOptions().C99) {
2398 // Implement C99-only parts of addressof rules.
2399 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2400 if (uOp->getOpcode() == UnaryOperator::Deref)
2401 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2402 // (assuming the deref expression is valid).
2403 return uOp->getSubExpr()->getType();
2404 }
2405 // Technically, there should be a check for array subscript
2406 // expressions here, but the result of one is always an lvalue anyway.
2407 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002408 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002409 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002410
2411 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002412 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2413 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002414 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2415 op->getSourceRange());
2416 return QualType();
2417 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002418 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2419 if (MemExpr->getMemberDecl()->isBitField()) {
2420 Diag(OpLoc, diag::err_typecheck_address_of,
2421 std::string("bit-field"), op->getSourceRange());
2422 return QualType();
2423 }
2424 // Check for Apple extension for accessing vector components.
2425 } else if (isa<ArraySubscriptExpr>(op) &&
2426 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2427 Diag(OpLoc, diag::err_typecheck_address_of,
2428 std::string("vector"), op->getSourceRange());
2429 return QualType();
2430 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002431 // We have an lvalue with a decl. Make sure the decl is not declared
2432 // with the register storage-class specifier.
2433 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2434 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002435 Diag(OpLoc, diag::err_typecheck_address_of,
2436 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002437 return QualType();
2438 }
2439 } else
2440 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002441 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002442
Chris Lattner4b009652007-07-25 00:24:17 +00002443 // If the operand has type "type", the result has type "pointer to type".
2444 return Context.getPointerType(op->getType());
2445}
2446
2447QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2448 UsualUnaryConversions(op);
2449 QualType qType = op->getType();
2450
Chris Lattner7931f4a2007-07-31 16:53:04 +00002451 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002452 // Note that per both C89 and C99, this is always legal, even
2453 // if ptype is an incomplete type or void.
2454 // It would be possible to warn about dereferencing a
2455 // void pointer, but it's completely well-defined,
2456 // and such a warning is unlikely to catch any mistakes.
2457 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002458 }
2459 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2460 qType.getAsString(), op->getSourceRange());
2461 return QualType();
2462}
2463
2464static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2465 tok::TokenKind Kind) {
2466 BinaryOperator::Opcode Opc;
2467 switch (Kind) {
2468 default: assert(0 && "Unknown binop!");
2469 case tok::star: Opc = BinaryOperator::Mul; break;
2470 case tok::slash: Opc = BinaryOperator::Div; break;
2471 case tok::percent: Opc = BinaryOperator::Rem; break;
2472 case tok::plus: Opc = BinaryOperator::Add; break;
2473 case tok::minus: Opc = BinaryOperator::Sub; break;
2474 case tok::lessless: Opc = BinaryOperator::Shl; break;
2475 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2476 case tok::lessequal: Opc = BinaryOperator::LE; break;
2477 case tok::less: Opc = BinaryOperator::LT; break;
2478 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2479 case tok::greater: Opc = BinaryOperator::GT; break;
2480 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2481 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2482 case tok::amp: Opc = BinaryOperator::And; break;
2483 case tok::caret: Opc = BinaryOperator::Xor; break;
2484 case tok::pipe: Opc = BinaryOperator::Or; break;
2485 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2486 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2487 case tok::equal: Opc = BinaryOperator::Assign; break;
2488 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2489 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2490 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2491 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2492 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2493 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2494 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2495 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2496 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2497 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2498 case tok::comma: Opc = BinaryOperator::Comma; break;
2499 }
2500 return Opc;
2501}
2502
2503static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2504 tok::TokenKind Kind) {
2505 UnaryOperator::Opcode Opc;
2506 switch (Kind) {
2507 default: assert(0 && "Unknown unary op!");
2508 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2509 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2510 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2511 case tok::star: Opc = UnaryOperator::Deref; break;
2512 case tok::plus: Opc = UnaryOperator::Plus; break;
2513 case tok::minus: Opc = UnaryOperator::Minus; break;
2514 case tok::tilde: Opc = UnaryOperator::Not; break;
2515 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2516 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2517 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2518 case tok::kw___real: Opc = UnaryOperator::Real; break;
2519 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2520 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2521 }
2522 return Opc;
2523}
2524
2525// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002526Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002527 ExprTy *LHS, ExprTy *RHS) {
2528 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2529 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2530
Steve Naroff87d58b42007-09-16 03:34:24 +00002531 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2532 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002533
2534 QualType ResultTy; // Result type of the binary operator.
2535 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2536
2537 switch (Opc) {
2538 default:
2539 assert(0 && "Unknown binary expr!");
2540 case BinaryOperator::Assign:
2541 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2542 break;
2543 case BinaryOperator::Mul:
2544 case BinaryOperator::Div:
2545 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2546 break;
2547 case BinaryOperator::Rem:
2548 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2549 break;
2550 case BinaryOperator::Add:
2551 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2552 break;
2553 case BinaryOperator::Sub:
2554 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2555 break;
2556 case BinaryOperator::Shl:
2557 case BinaryOperator::Shr:
2558 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2559 break;
2560 case BinaryOperator::LE:
2561 case BinaryOperator::LT:
2562 case BinaryOperator::GE:
2563 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002564 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002565 break;
2566 case BinaryOperator::EQ:
2567 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002568 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002569 break;
2570 case BinaryOperator::And:
2571 case BinaryOperator::Xor:
2572 case BinaryOperator::Or:
2573 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2574 break;
2575 case BinaryOperator::LAnd:
2576 case BinaryOperator::LOr:
2577 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2578 break;
2579 case BinaryOperator::MulAssign:
2580 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002581 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002582 if (!CompTy.isNull())
2583 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2584 break;
2585 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002586 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002587 if (!CompTy.isNull())
2588 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2589 break;
2590 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002591 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002592 if (!CompTy.isNull())
2593 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2594 break;
2595 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002596 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002597 if (!CompTy.isNull())
2598 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2599 break;
2600 case BinaryOperator::ShlAssign:
2601 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002602 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002603 if (!CompTy.isNull())
2604 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2605 break;
2606 case BinaryOperator::AndAssign:
2607 case BinaryOperator::XorAssign:
2608 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002609 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002610 if (!CompTy.isNull())
2611 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2612 break;
2613 case BinaryOperator::Comma:
2614 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2615 break;
2616 }
2617 if (ResultTy.isNull())
2618 return true;
2619 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002620 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002621 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002622 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002623}
2624
2625// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002626Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002627 ExprTy *input) {
2628 Expr *Input = (Expr*)input;
2629 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2630 QualType resultType;
2631 switch (Opc) {
2632 default:
2633 assert(0 && "Unimplemented unary expr!");
2634 case UnaryOperator::PreInc:
2635 case UnaryOperator::PreDec:
2636 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2637 break;
2638 case UnaryOperator::AddrOf:
2639 resultType = CheckAddressOfOperand(Input, OpLoc);
2640 break;
2641 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002642 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002643 resultType = CheckIndirectionOperand(Input, OpLoc);
2644 break;
2645 case UnaryOperator::Plus:
2646 case UnaryOperator::Minus:
2647 UsualUnaryConversions(Input);
2648 resultType = Input->getType();
2649 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2650 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2651 resultType.getAsString());
2652 break;
2653 case UnaryOperator::Not: // bitwise complement
2654 UsualUnaryConversions(Input);
2655 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002656 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2657 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2658 // C99 does not support '~' for complex conjugation.
2659 Diag(OpLoc, diag::ext_integer_complement_complex,
2660 resultType.getAsString(), Input->getSourceRange());
2661 else if (!resultType->isIntegerType())
2662 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2663 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002664 break;
2665 case UnaryOperator::LNot: // logical negation
2666 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2667 DefaultFunctionArrayConversion(Input);
2668 resultType = Input->getType();
2669 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2670 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2671 resultType.getAsString());
2672 // LNot always has type int. C99 6.5.3.3p5.
2673 resultType = Context.IntTy;
2674 break;
2675 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002676 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2677 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002678 break;
2679 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002680 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2681 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002682 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002683 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002684 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002685 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002686 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002687 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002688 resultType = Input->getType();
2689 break;
2690 }
2691 if (resultType.isNull())
2692 return true;
2693 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2694}
2695
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002696/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2697Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002698 SourceLocation LabLoc,
2699 IdentifierInfo *LabelII) {
2700 // Look up the record for this label identifier.
2701 LabelStmt *&LabelDecl = LabelMap[LabelII];
2702
Daniel Dunbar879788d2008-08-04 16:51:22 +00002703 // If we haven't seen this label yet, create a forward reference. It
2704 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002705 if (LabelDecl == 0)
2706 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2707
2708 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002709 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2710 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002711}
2712
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002713Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002714 SourceLocation RPLoc) { // "({..})"
2715 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2716 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2717 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2718
2719 // FIXME: there are a variety of strange constraints to enforce here, for
2720 // example, it is not possible to goto into a stmt expression apparently.
2721 // More semantic analysis is needed.
2722
2723 // FIXME: the last statement in the compount stmt has its value used. We
2724 // should not warn about it being unused.
2725
2726 // If there are sub stmts in the compound stmt, take the type of the last one
2727 // as the type of the stmtexpr.
2728 QualType Ty = Context.VoidTy;
2729
Chris Lattner200964f2008-07-26 19:51:01 +00002730 if (!Compound->body_empty()) {
2731 Stmt *LastStmt = Compound->body_back();
2732 // If LastStmt is a label, skip down through into the body.
2733 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2734 LastStmt = Label->getSubStmt();
2735
2736 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002737 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002738 }
Chris Lattner4b009652007-07-25 00:24:17 +00002739
2740 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2741}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002742
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002743Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002744 SourceLocation TypeLoc,
2745 TypeTy *argty,
2746 OffsetOfComponent *CompPtr,
2747 unsigned NumComponents,
2748 SourceLocation RPLoc) {
2749 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2750 assert(!ArgTy.isNull() && "Missing type argument!");
2751
2752 // We must have at least one component that refers to the type, and the first
2753 // one is known to be a field designator. Verify that the ArgTy represents
2754 // a struct/union/class.
2755 if (!ArgTy->isRecordType())
2756 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2757
2758 // Otherwise, create a compound literal expression as the base, and
2759 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002760 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002761
Chris Lattnerb37522e2007-08-31 21:49:13 +00002762 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2763 // GCC extension, diagnose them.
2764 if (NumComponents != 1)
2765 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2766 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2767
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002768 for (unsigned i = 0; i != NumComponents; ++i) {
2769 const OffsetOfComponent &OC = CompPtr[i];
2770 if (OC.isBrackets) {
2771 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002772 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002773 if (!AT) {
2774 delete Res;
2775 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2776 Res->getType().getAsString());
2777 }
2778
Chris Lattner2af6a802007-08-30 17:59:59 +00002779 // FIXME: C++: Verify that operator[] isn't overloaded.
2780
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002781 // C99 6.5.2.1p1
2782 Expr *Idx = static_cast<Expr*>(OC.U.E);
2783 if (!Idx->getType()->isIntegerType())
2784 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2785 Idx->getSourceRange());
2786
2787 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2788 continue;
2789 }
2790
2791 const RecordType *RC = Res->getType()->getAsRecordType();
2792 if (!RC) {
2793 delete Res;
2794 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2795 Res->getType().getAsString());
2796 }
2797
2798 // Get the decl corresponding to this.
2799 RecordDecl *RD = RC->getDecl();
2800 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2801 if (!MemberDecl)
2802 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2803 OC.U.IdentInfo->getName(),
2804 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002805
2806 // FIXME: C++: Verify that MemberDecl isn't a static field.
2807 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002808 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2809 // matter here.
2810 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002811 }
2812
2813 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2814 BuiltinLoc);
2815}
2816
2817
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002818Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002819 TypeTy *arg1, TypeTy *arg2,
2820 SourceLocation RPLoc) {
2821 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2822 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2823
2824 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2825
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002826 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002827}
2828
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002829Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002830 ExprTy *expr1, ExprTy *expr2,
2831 SourceLocation RPLoc) {
2832 Expr *CondExpr = static_cast<Expr*>(cond);
2833 Expr *LHSExpr = static_cast<Expr*>(expr1);
2834 Expr *RHSExpr = static_cast<Expr*>(expr2);
2835
2836 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2837
2838 // The conditional expression is required to be a constant expression.
2839 llvm::APSInt condEval(32);
2840 SourceLocation ExpLoc;
2841 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2842 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2843 CondExpr->getSourceRange());
2844
2845 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2846 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2847 RHSExpr->getType();
2848 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2849}
2850
Steve Naroff52a81c02008-09-03 18:15:37 +00002851//===----------------------------------------------------------------------===//
2852// Clang Extensions.
2853//===----------------------------------------------------------------------===//
2854
2855/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00002856void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002857 // Analyze block parameters.
2858 BlockSemaInfo *BSI = new BlockSemaInfo();
2859
2860 // Add BSI to CurBlock.
2861 BSI->PrevBlockInfo = CurBlock;
2862 CurBlock = BSI;
2863
2864 BSI->ReturnType = 0;
2865 BSI->TheScope = BlockScope;
2866
Steve Naroff52059382008-10-10 01:28:17 +00002867 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2868 PushDeclContext(BSI->TheDecl);
2869}
2870
2871void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002872 // Analyze arguments to block.
2873 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2874 "Not a function declarator!");
2875 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2876
Steve Naroff52059382008-10-10 01:28:17 +00002877 CurBlock->hasPrototype = FTI.hasPrototype;
2878 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00002879
2880 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2881 // no arguments, not a function that takes a single void argument.
2882 if (FTI.hasPrototype &&
2883 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2884 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2885 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2886 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00002887 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00002888 } else if (FTI.hasPrototype) {
2889 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00002890 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2891 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00002892 }
Steve Naroff52059382008-10-10 01:28:17 +00002893 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2894
2895 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2896 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2897 // If this has an identifier, add it to the scope stack.
2898 if ((*AI)->getIdentifier())
2899 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00002900}
2901
2902/// ActOnBlockError - If there is an error parsing a block, this callback
2903/// is invoked to pop the information about the block from the action impl.
2904void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2905 // Ensure that CurBlock is deleted.
2906 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2907
2908 // Pop off CurBlock, handle nested blocks.
2909 CurBlock = CurBlock->PrevBlockInfo;
2910
2911 // FIXME: Delete the ParmVarDecl objects as well???
2912
2913}
2914
2915/// ActOnBlockStmtExpr - This is called when the body of a block statement
2916/// literal was successfully completed. ^(int x){...}
2917Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2918 Scope *CurScope) {
2919 // Ensure that CurBlock is deleted.
2920 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2921 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2922
Steve Naroff52059382008-10-10 01:28:17 +00002923 PopDeclContext();
2924
Steve Naroff52a81c02008-09-03 18:15:37 +00002925 // Pop off CurBlock, handle nested blocks.
2926 CurBlock = CurBlock->PrevBlockInfo;
2927
2928 QualType RetTy = Context.VoidTy;
2929 if (BSI->ReturnType)
2930 RetTy = QualType(BSI->ReturnType, 0);
2931
2932 llvm::SmallVector<QualType, 8> ArgTypes;
2933 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2934 ArgTypes.push_back(BSI->Params[i]->getType());
2935
2936 QualType BlockTy;
2937 if (!BSI->hasPrototype)
2938 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2939 else
2940 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2941 BSI->isVariadic);
2942
2943 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00002944
Steve Naroff95029d92008-10-08 18:44:00 +00002945 BSI->TheDecl->setBody(Body.take());
2946 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00002947}
2948
Nate Begemanbd881ef2008-01-30 20:50:20 +00002949/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002950/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002951/// The number of arguments has already been validated to match the number of
2952/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002953static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2954 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002955 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002956 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002957 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2958 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002959
2960 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002961 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002962 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002963 return true;
2964}
2965
2966Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2967 SourceLocation *CommaLocs,
2968 SourceLocation BuiltinLoc,
2969 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002970 // __builtin_overload requires at least 2 arguments
2971 if (NumArgs < 2)
2972 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2973 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002974
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002975 // The first argument is required to be a constant expression. It tells us
2976 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002977 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002978 Expr *NParamsExpr = Args[0];
2979 llvm::APSInt constEval(32);
2980 SourceLocation ExpLoc;
2981 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2982 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2983 NParamsExpr->getSourceRange());
2984
2985 // Verify that the number of parameters is > 0
2986 unsigned NumParams = constEval.getZExtValue();
2987 if (NumParams == 0)
2988 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2989 NParamsExpr->getSourceRange());
2990 // Verify that we have at least 1 + NumParams arguments to the builtin.
2991 if ((NumParams + 1) > NumArgs)
2992 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2993 SourceRange(BuiltinLoc, RParenLoc));
2994
2995 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002996 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002997 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002998 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2999 // UsualUnaryConversions will convert the function DeclRefExpr into a
3000 // pointer to function.
3001 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003002 const FunctionTypeProto *FnType = 0;
3003 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3004 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003005
3006 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3007 // parameters, and the number of parameters must match the value passed to
3008 // the builtin.
3009 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003010 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3011 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003012
3013 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003014 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003015 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003016 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003017 if (OE)
3018 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3019 OE->getFn()->getSourceRange());
3020 // Remember our match, and continue processing the remaining arguments
3021 // to catch any errors.
3022 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3023 BuiltinLoc, RParenLoc);
3024 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003025 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003026 // Return the newly created OverloadExpr node, if we succeded in matching
3027 // exactly one of the candidate functions.
3028 if (OE)
3029 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003030
3031 // If we didn't find a matching function Expr in the __builtin_overload list
3032 // the return an error.
3033 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003034 for (unsigned i = 0; i != NumParams; ++i) {
3035 if (i != 0) typeNames += ", ";
3036 typeNames += Args[i+1]->getType().getAsString();
3037 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003038
3039 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3040 SourceRange(BuiltinLoc, RParenLoc));
3041}
3042
Anders Carlsson36760332007-10-15 20:28:48 +00003043Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3044 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003045 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003046 Expr *E = static_cast<Expr*>(expr);
3047 QualType T = QualType::getFromOpaquePtr(type);
3048
3049 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003050
3051 // Get the va_list type
3052 QualType VaListType = Context.getBuiltinVaListType();
3053 // Deal with implicit array decay; for example, on x86-64,
3054 // va_list is an array, but it's supposed to decay to
3055 // a pointer for va_arg.
3056 if (VaListType->isArrayType())
3057 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003058 // Make sure the input expression also decays appropriately.
3059 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003060
3061 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003062 return Diag(E->getLocStart(),
3063 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3064 E->getType().getAsString(),
3065 E->getSourceRange());
3066
3067 // FIXME: Warn if a non-POD type is passed in.
3068
3069 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3070}
3071
Chris Lattner005ed752008-01-04 18:04:52 +00003072bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3073 SourceLocation Loc,
3074 QualType DstType, QualType SrcType,
3075 Expr *SrcExpr, const char *Flavor) {
3076 // Decode the result (notice that AST's are still created for extensions).
3077 bool isInvalid = false;
3078 unsigned DiagKind;
3079 switch (ConvTy) {
3080 default: assert(0 && "Unknown conversion type");
3081 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003082 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003083 DiagKind = diag::ext_typecheck_convert_pointer_int;
3084 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003085 case IntToPointer:
3086 DiagKind = diag::ext_typecheck_convert_int_pointer;
3087 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003088 case IncompatiblePointer:
3089 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3090 break;
3091 case FunctionVoidPointer:
3092 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3093 break;
3094 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003095 // If the qualifiers lost were because we were applying the
3096 // (deprecated) C++ conversion from a string literal to a char*
3097 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3098 // Ideally, this check would be performed in
3099 // CheckPointerTypesForAssignment. However, that would require a
3100 // bit of refactoring (so that the second argument is an
3101 // expression, rather than a type), which should be done as part
3102 // of a larger effort to fix CheckPointerTypesForAssignment for
3103 // C++ semantics.
3104 if (getLangOptions().CPlusPlus &&
3105 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3106 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003107 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3108 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003109 case IntToBlockPointer:
3110 DiagKind = diag::err_int_to_block_pointer;
3111 break;
3112 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003113 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003114 break;
3115 case BlockVoidPointer:
3116 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3117 break;
Steve Naroff19608432008-10-14 22:18:38 +00003118 case IncompatibleObjCQualifiedId:
3119 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3120 // it can give a more specific diagnostic.
3121 DiagKind = diag::warn_incompatible_qualified_id;
3122 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003123 case Incompatible:
3124 DiagKind = diag::err_typecheck_convert_incompatible;
3125 isInvalid = true;
3126 break;
3127 }
3128
3129 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3130 SrcExpr->getSourceRange());
3131 return isInvalid;
3132}