blob: 017e19df6c1e3f0b3e909ff46904ca32c081096a [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;
293
294 // Get an array type for the string, according to C99 6.4.5. This includes
295 // the nul terminator character as well as the string length for pascal
296 // strings.
297 StrTy = Context.getConstantArrayType(StrTy,
298 llvm::APInt(32, Literal.GetStringLength()+1),
299 ArrayType::Normal, 0);
300
Chris Lattner4b009652007-07-25 00:24:17 +0000301 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
302 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000303 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000304 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000305 StringToks[NumStringToks-1].getLocation());
306}
307
Steve Naroffd6163f32008-09-05 22:11:13 +0000308/// DeclDefinedWithinScope - Return true if the specified decl is defined at or
309/// within the 'Within' scope. The current Scope is CurScope.
310///
311/// NOTE: This method is extremely inefficient (linear scan), this should not be
312/// used in common cases.
313///
314static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within,
315 Scope *CurScope) {
316 while (1) {
317 assert(CurScope && "CurScope not nested within 'Within'?");
318
319 // Check this scope for the decl.
320 if (CurScope->isDeclScope(D)) return true;
321
322 if (CurScope == Within) return false;
323 CurScope = CurScope->getParent();
324 }
325}
Chris Lattner4b009652007-07-25 00:24:17 +0000326
Steve Naroff0acc9c92007-09-15 18:49:24 +0000327/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000328/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000329/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000330Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000331 IdentifierInfo &II,
332 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000333 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000334 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000335
336 // If this reference is in an Objective-C method, then ivar lookup happens as
337 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000338 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000339 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000340 // There are two cases to handle here. 1) scoped lookup could have failed,
341 // in which case we should look for an ivar. 2) scoped lookup could have
342 // found a decl, but that decl is outside the current method (i.e. a global
343 // variable). In these two cases, we do a lookup for an ivar with this
344 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000345 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000346 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000347 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000348 // FIXME: This should use a new expr for a direct reference, don't turn
349 // this into Self->ivar, just return a BareIVarExpr or something.
350 IdentifierInfo &II = Context.Idents.get("self");
351 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
352 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
353 static_cast<Expr*>(SelfExpr.Val), true, true);
354 }
355 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000356 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000357 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000358 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000359 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000360 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000361 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000362 }
Steve Naroff4d1b93d2008-09-10 18:33:00 +0000363 // If we are parsing a block, check the block parameter list.
364 if (CurBlock) {
365 for (unsigned i = 0, e = CurBlock->Params.size(); i != e; ++i)
366 if (CurBlock->Params[i]->getIdentifier() == &II)
367 D = CurBlock->Params[i];
368 }
Chris Lattner4b009652007-07-25 00:24:17 +0000369 if (D == 0) {
370 // Otherwise, this could be an implicitly declared function reference (legal
371 // in C90, extension in C99).
372 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000373 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000374 D = ImplicitlyDefineFunction(Loc, II, S);
375 else {
376 // If this name wasn't predeclared and if this is not a function call,
377 // diagnose the problem.
378 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
379 }
380 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000381
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000382 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
383 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
384 if (MD->isStatic())
385 // "invalid use of member 'x' in static member function"
386 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
387 FD->getName());
388 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
389 // "invalid use of nonstatic data member 'x'"
390 return Diag(Loc, diag::err_invalid_non_static_member_use,
391 FD->getName());
392
393 if (FD->isInvalidDecl())
394 return true;
395
396 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
397 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
398 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
399 true, FD, Loc, FD->getType());
400 }
401
402 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
403 }
Chris Lattner4b009652007-07-25 00:24:17 +0000404 if (isa<TypedefDecl>(D))
405 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000406 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000407 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000408 if (isa<NamespaceDecl>(D))
409 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000410
Steve Naroffd6163f32008-09-05 22:11:13 +0000411 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
412 ValueDecl *VD = cast<ValueDecl>(D);
413
414 // check if referencing an identifier with __attribute__((deprecated)).
415 if (VD->getAttr<DeprecatedAttr>())
416 Diag(Loc, diag::warn_deprecated, VD->getName());
417
418 // Only create DeclRefExpr's for valid Decl's.
419 if (VD->isInvalidDecl())
420 return true;
421
422 // If this reference is not in a block or if the referenced variable is
423 // within the block, create a normal DeclRefExpr.
424 //
425 // FIXME: This will create BlockDeclRefExprs for global variables,
426 // function references, enums constants, etc which is suboptimal :) and breaks
427 // things like "integer constant expression" tests.
428 //
429 if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S))
430 return new DeclRefExpr(VD, VD->getType(), Loc);
431
432 // If we are in a block and the variable is outside the current block,
433 // bind the variable reference with a BlockDeclRefExpr.
434
435 // If the variable is in the byref set, bind it directly, otherwise it will be
436 // bound by-copy, thus we make it const within the closure.
437 if (!CurBlock->ByRefVars.count(VD))
438 VD->getType().addConst();
439
440 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000441}
442
Chris Lattner69909292008-08-10 01:53:14 +0000443Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000444 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000445 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000446
447 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000448 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000449 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
450 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
451 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000452 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000453
454 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000455 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000456 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000457
Chris Lattner7e637512008-01-12 08:14:25 +0000458 // Pre-defined identifiers are of type char[x], where x is the length of the
459 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000460 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000461 if (getCurFunctionDecl())
462 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000463 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000464 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000465
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000466 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000467 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000468 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000469 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000470}
471
Steve Naroff87d58b42007-09-16 03:34:24 +0000472Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000473 llvm::SmallString<16> CharBuffer;
474 CharBuffer.resize(Tok.getLength());
475 const char *ThisTokBegin = &CharBuffer[0];
476 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
477
478 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
479 Tok.getLocation(), PP);
480 if (Literal.hadError())
481 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000482
483 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
484
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000485 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
486 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000487}
488
Steve Naroff87d58b42007-09-16 03:34:24 +0000489Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000490 // fast path for a single digit (which is quite common). A single digit
491 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
492 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000493 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000494
Chris Lattner8cd0e932008-03-05 18:54:05 +0000495 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000496 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000497 Context.IntTy,
498 Tok.getLocation()));
499 }
500 llvm::SmallString<512> IntegerBuffer;
501 IntegerBuffer.resize(Tok.getLength());
502 const char *ThisTokBegin = &IntegerBuffer[0];
503
504 // Get the spelling of the token, which eliminates trigraphs, etc.
505 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
506 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
507 Tok.getLocation(), PP);
508 if (Literal.hadError)
509 return ExprResult(true);
510
Chris Lattner1de66eb2007-08-26 03:42:43 +0000511 Expr *Res;
512
513 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000514 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000515 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000516 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000517 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000518 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000519 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000520 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000521
522 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
523
Ted Kremenekddedbe22007-11-29 00:56:49 +0000524 // isExact will be set by GetFloatValue().
525 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000526 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000527 Ty, Tok.getLocation());
528
Chris Lattner1de66eb2007-08-26 03:42:43 +0000529 } else if (!Literal.isIntegerLiteral()) {
530 return ExprResult(true);
531 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000532 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000533
Neil Booth7421e9c2007-08-29 22:00:19 +0000534 // long long is a C99 feature.
535 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000536 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000537 Diag(Tok.getLocation(), diag::ext_longlong);
538
Chris Lattner4b009652007-07-25 00:24:17 +0000539 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000540 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000541
542 if (Literal.GetIntegerValue(ResultVal)) {
543 // If this value didn't fit into uintmax_t, warn and force to ull.
544 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000545 Ty = Context.UnsignedLongLongTy;
546 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000547 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000548 } else {
549 // If this value fits into a ULL, try to figure out what else it fits into
550 // according to the rules of C99 6.4.4.1p5.
551
552 // Octal, Hexadecimal, and integers with a U suffix are allowed to
553 // be an unsigned int.
554 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
555
556 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000557 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000558 if (!Literal.isLong && !Literal.isLongLong) {
559 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000560 unsigned IntSize = Context.Target.getIntWidth();
561
Chris Lattner4b009652007-07-25 00:24:17 +0000562 // Does it fit in a unsigned int?
563 if (ResultVal.isIntN(IntSize)) {
564 // Does it fit in a signed int?
565 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000566 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000567 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000568 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000569 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000570 }
Chris Lattner4b009652007-07-25 00:24:17 +0000571 }
572
573 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000574 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000575 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000576
577 // Does it fit in a unsigned long?
578 if (ResultVal.isIntN(LongSize)) {
579 // Does it fit in a signed long?
580 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000581 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000582 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000583 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000584 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000585 }
Chris Lattner4b009652007-07-25 00:24:17 +0000586 }
587
588 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000589 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000590 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000591
592 // Does it fit in a unsigned long long?
593 if (ResultVal.isIntN(LongLongSize)) {
594 // Does it fit in a signed long long?
595 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000596 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000597 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000598 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000599 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
601 }
602
603 // If we still couldn't decide a type, we probably have something that
604 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000605 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000606 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000607 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000608 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000609 }
Chris Lattnere4068872008-05-09 05:59:00 +0000610
611 if (ResultVal.getBitWidth() != Width)
612 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000613 }
614
Chris Lattner48d7f382008-04-02 04:24:33 +0000615 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000616 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000617
618 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
619 if (Literal.isImaginary)
620 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
621
622 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000623}
624
Steve Naroff87d58b42007-09-16 03:34:24 +0000625Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000626 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000627 Expr *E = (Expr *)Val;
628 assert((E != 0) && "ActOnParenExpr() missing expr");
629 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000630}
631
632/// The UsualUnaryConversions() function is *not* called by this routine.
633/// See C99 6.3.2.1p[2-4] for more details.
634QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000635 SourceLocation OpLoc,
636 const SourceRange &ExprRange,
637 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000638 // C99 6.5.3.4p1:
639 if (isa<FunctionType>(exprType) && isSizeof)
640 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000641 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000642 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000643 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
644 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000645 else if (exprType->isIncompleteType()) {
646 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
647 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000648 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000649 return QualType(); // error
650 }
651 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
652 return Context.getSizeType();
653}
654
655Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000656ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000657 SourceLocation LPLoc, TypeTy *Ty,
658 SourceLocation RPLoc) {
659 // If error parsing type, ignore.
660 if (Ty == 0) return true;
661
662 // Verify that this is a valid expression.
663 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
664
Chris Lattnerf814d882008-07-25 21:45:37 +0000665 QualType resultType =
666 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000667
668 if (resultType.isNull())
669 return true;
670 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
671}
672
Chris Lattner5110ad52007-08-24 21:41:10 +0000673QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000674 DefaultFunctionArrayConversion(V);
675
Chris Lattnera16e42d2007-08-26 05:39:26 +0000676 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000677 if (const ComplexType *CT = V->getType()->getAsComplexType())
678 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000679
680 // Otherwise they pass through real integer and floating point types here.
681 if (V->getType()->isArithmeticType())
682 return V->getType();
683
684 // Reject anything else.
685 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
686 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000687}
688
689
Chris Lattner4b009652007-07-25 00:24:17 +0000690
Steve Naroff87d58b42007-09-16 03:34:24 +0000691Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000692 tok::TokenKind Kind,
693 ExprTy *Input) {
694 UnaryOperator::Opcode Opc;
695 switch (Kind) {
696 default: assert(0 && "Unknown unary op!");
697 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
698 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
699 }
700 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
701 if (result.isNull())
702 return true;
703 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
704}
705
706Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000707ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000708 ExprTy *Idx, SourceLocation RLoc) {
709 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
710
711 // Perform default conversions.
712 DefaultFunctionArrayConversion(LHSExp);
713 DefaultFunctionArrayConversion(RHSExp);
714
715 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
716
717 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000718 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000719 // in the subscript position. As a result, we need to derive the array base
720 // and index from the expression types.
721 Expr *BaseExpr, *IndexExpr;
722 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000723 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000724 BaseExpr = LHSExp;
725 IndexExpr = RHSExp;
726 // FIXME: need to deal with const...
727 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000728 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000729 // Handle the uncommon case of "123[Ptr]".
730 BaseExpr = RHSExp;
731 IndexExpr = LHSExp;
732 // FIXME: need to deal with const...
733 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000734 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
735 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000736 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000737
738 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000739 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
740 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000741 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000742 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000743 // FIXME: need to deal with const...
744 ResultType = VTy->getElementType();
745 } else {
746 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
747 RHSExp->getSourceRange());
748 }
749 // C99 6.5.2.1p1
750 if (!IndexExpr->getType()->isIntegerType())
751 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
752 IndexExpr->getSourceRange());
753
754 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
755 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000756 // void (*)(int)) and pointers to incomplete types. Functions are not
757 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000758 if (!ResultType->isObjectType())
759 return Diag(BaseExpr->getLocStart(),
760 diag::err_typecheck_subscript_not_object,
761 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
762
763 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
764}
765
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000766QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000767CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000768 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000769 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000770
771 // This flag determines whether or not the component is to be treated as a
772 // special name, or a regular GLSL-style component access.
773 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000774
775 // The vector accessor can't exceed the number of elements.
776 const char *compStr = CompName.getName();
777 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000778 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000779 baseType.getAsString(), SourceRange(CompLoc));
780 return QualType();
781 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000782
783 // Check that we've found one of the special components, or that the component
784 // names must come from the same set.
785 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
786 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
787 SpecialComponent = true;
788 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000789 do
790 compStr++;
791 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
792 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
793 do
794 compStr++;
795 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
796 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
797 do
798 compStr++;
799 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
800 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000801
Nate Begemanc8e51f82008-05-09 06:41:27 +0000802 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000803 // We didn't get to the end of the string. This means the component names
804 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000805 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000806 std::string(compStr,compStr+1), SourceRange(CompLoc));
807 return QualType();
808 }
809 // Each component accessor can't exceed the vector type.
810 compStr = CompName.getName();
811 while (*compStr) {
812 if (vecType->isAccessorWithinNumElements(*compStr))
813 compStr++;
814 else
815 break;
816 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000817 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000818 // We didn't get to the end of the string. This means a component accessor
819 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000820 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000821 baseType.getAsString(), SourceRange(CompLoc));
822 return QualType();
823 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000824
825 // If we have a special component name, verify that the current vector length
826 // is an even number, since all special component names return exactly half
827 // the elements.
828 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
829 return QualType();
830 }
831
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000832 // The component accessor looks fine - now we need to compute the actual type.
833 // The vector type is implied by the component accessor. For example,
834 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000835 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
836 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
837 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000838 if (CompSize == 1)
839 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000840
Nate Begemanaf6ed502008-04-18 23:10:10 +0000841 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000842 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000843 // diagostics look bad. We want extended vector types to appear built-in.
844 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
845 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
846 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000847 }
848 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000849}
850
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000851/// constructSetterName - Return the setter name for the given
852/// identifier, i.e. "set" + Name where the initial character of Name
853/// has been capitalized.
854// FIXME: Merge with same routine in Parser. But where should this
855// live?
856static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
857 const IdentifierInfo *Name) {
858 unsigned N = Name->getLength();
859 char *SelectorName = new char[3 + N];
860 memcpy(SelectorName, "set", 3);
861 memcpy(&SelectorName[3], Name->getName(), N);
862 SelectorName[3] = toupper(SelectorName[3]);
863
864 IdentifierInfo *Setter =
865 &Idents.get(SelectorName, &SelectorName[3 + N]);
866 delete[] SelectorName;
867 return Setter;
868}
869
Chris Lattner4b009652007-07-25 00:24:17 +0000870Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000871ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000872 tok::TokenKind OpKind, SourceLocation MemberLoc,
873 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000874 Expr *BaseExpr = static_cast<Expr *>(Base);
875 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000876
877 // Perform default conversions.
878 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000879
Steve Naroff2cb66382007-07-26 03:11:44 +0000880 QualType BaseType = BaseExpr->getType();
881 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000882
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000883 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
884 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000885 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000886 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000887 BaseType = PT->getPointeeType();
888 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000889 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
890 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000891 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000892
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000893 // Handle field access to simple records. This also handles access to fields
894 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000895 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000896 RecordDecl *RDecl = RTy->getDecl();
897 if (RTy->isIncompleteType())
898 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
899 BaseExpr->getSourceRange());
900 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000901 FieldDecl *MemberDecl = RDecl->getMember(&Member);
902 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000903 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
904 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000905
906 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000907 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000908 QualType MemberType = MemberDecl->getType();
909 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000910 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000911 MemberType = MemberType.getQualifiedType(combinedQualifiers);
912
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000913 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000914 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000915 }
916
Chris Lattnere9d71612008-07-21 04:59:05 +0000917 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
918 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000919 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
920 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000921 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000922 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000923 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000924 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000925 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000926 }
927
Chris Lattnere9d71612008-07-21 04:59:05 +0000928 // Handle Objective-C property access, which is "Obj.property" where Obj is a
929 // pointer to a (potentially qualified) interface type.
930 const PointerType *PTy;
931 const ObjCInterfaceType *IFTy;
932 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
933 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
934 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000935
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000936 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000937 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
938 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
939
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000940 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000941 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
942 E = IFTy->qual_end(); I != E; ++I)
943 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
944 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000945
946 // If that failed, look for an "implicit" property by seeing if the nullary
947 // selector is implemented.
948
949 // FIXME: The logic for looking up nullary and unary selectors should be
950 // shared with the code in ActOnInstanceMessage.
951
952 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
953 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
954
955 // If this reference is in an @implementation, check for 'private' methods.
956 if (!Getter)
957 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
958 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
959 if (ObjCImplementationDecl *ImpDecl =
960 ObjCImplementations[ClassDecl->getIdentifier()])
961 Getter = ImpDecl->getInstanceMethod(Sel);
962
963 if (Getter) {
964 // If we found a getter then this may be a valid dot-reference, we
965 // need to also look for the matching setter.
966 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
967 &Member);
968 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
969 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
970
971 if (!Setter) {
972 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
973 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
974 if (ObjCImplementationDecl *ImpDecl =
975 ObjCImplementations[ClassDecl->getIdentifier()])
976 Setter = ImpDecl->getInstanceMethod(SetterSel);
977 }
978
979 // FIXME: There are some issues here. First, we are not
980 // diagnosing accesses to read-only properties because we do not
981 // know if this is a getter or setter yet. Second, we are
982 // checking that the type of the setter matches the type we
983 // expect.
984 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
985 MemberLoc, BaseExpr);
986 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000987 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000988
989 // Handle 'field access' to vectors, such as 'V.xx'.
990 if (BaseType->isExtVectorType() && OpKind == tok::period) {
991 // Component access limited to variables (reject vec4.rg.g).
992 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
993 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000994 return Diag(MemberLoc, diag::err_ext_vector_component_access,
995 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000996 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
997 if (ret.isNull())
998 return true;
999 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1000 }
1001
Chris Lattner7d5a8762008-07-21 05:35:34 +00001002 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1003 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001004}
1005
Steve Naroff87d58b42007-09-16 03:34:24 +00001006/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001007/// This provides the location of the left/right parens and a list of comma
1008/// locations.
1009Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001010ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001011 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001012 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1013 Expr *Fn = static_cast<Expr *>(fn);
1014 Expr **Args = reinterpret_cast<Expr**>(args);
1015 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001016 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001017
1018 // Promote the function operand.
1019 UsualUnaryConversions(Fn);
1020
1021 // If we're directly calling a function, get the declaration for
1022 // that function.
1023 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1024 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1025 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1026
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001027 // Make the call expr early, before semantic checks. This guarantees cleanup
1028 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001029 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001030 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001031 const FunctionType *FuncT;
1032 if (!Fn->getType()->isBlockPointerType()) {
1033 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1034 // have type pointer to function".
1035 const PointerType *PT = Fn->getType()->getAsPointerType();
1036 if (PT == 0)
1037 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1038 Fn->getSourceRange());
1039 FuncT = PT->getPointeeType()->getAsFunctionType();
1040 } else { // This is a block call.
1041 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1042 getAsFunctionType();
1043 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001044 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001045 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1046 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001047
1048 // We know the result type of the call, set it.
1049 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001050
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001051 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001052 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1053 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001054 unsigned NumArgsInProto = Proto->getNumArgs();
1055 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001056
Chris Lattner3e254fb2008-04-08 04:40:51 +00001057 // If too few arguments are available (and we don't have default
1058 // arguments for the remaining parameters), don't make the call.
1059 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001060 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001061 // Use default arguments for missing arguments
1062 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001063 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001064 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001065 return Diag(RParenLoc,
1066 !Fn->getType()->isBlockPointerType()
1067 ? diag::err_typecheck_call_too_few_args
1068 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001069 Fn->getSourceRange());
1070 }
1071
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001072 // If too many are passed and not variadic, error on the extras and drop
1073 // them.
1074 if (NumArgs > NumArgsInProto) {
1075 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001076 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001077 !Fn->getType()->isBlockPointerType()
1078 ? diag::err_typecheck_call_too_many_args
1079 : diag::err_typecheck_block_too_many_args,
1080 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001081 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001082 Args[NumArgs-1]->getLocEnd()));
1083 // This deletes the extra arguments.
1084 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001085 }
1086 NumArgsToCheck = NumArgsInProto;
1087 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001088
Chris Lattner4b009652007-07-25 00:24:17 +00001089 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001090 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001091 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001092
1093 Expr *Arg;
1094 if (i < NumArgs)
1095 Arg = Args[i];
1096 else
1097 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001098 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001099
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001100 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001101 AssignConvertType ConvTy =
1102 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001103 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001104
Chris Lattner005ed752008-01-04 18:04:52 +00001105 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1106 ArgType, Arg, "passing"))
1107 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001108 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001109
1110 // If this is a variadic call, handle args passed through "...".
1111 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001112 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001113 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1114 Expr *Arg = Args[i];
1115 DefaultArgumentPromotion(Arg);
1116 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001117 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001118 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001119 } else {
1120 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1121
Steve Naroffdb65e052007-08-28 23:30:39 +00001122 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001123 for (unsigned i = 0; i != NumArgs; i++) {
1124 Expr *Arg = Args[i];
1125 DefaultArgumentPromotion(Arg);
1126 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001127 }
Chris Lattner4b009652007-07-25 00:24:17 +00001128 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001129
Chris Lattner2e64c072007-08-10 20:18:51 +00001130 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001131 if (FDecl)
1132 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001133
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001134 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001135}
1136
1137Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001138ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001139 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001140 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001141 QualType literalType = QualType::getFromOpaquePtr(Ty);
1142 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001143 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001144 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001145
Eli Friedman8c2173d2008-05-20 05:22:08 +00001146 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001147 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001148 return Diag(LParenLoc,
1149 diag::err_variable_object_no_init,
1150 SourceRange(LParenLoc,
1151 literalExpr->getSourceRange().getEnd()));
1152 } else if (literalType->isIncompleteType()) {
1153 return Diag(LParenLoc,
1154 diag::err_typecheck_decl_incomplete_type,
1155 literalType.getAsString(),
1156 SourceRange(LParenLoc,
1157 literalExpr->getSourceRange().getEnd()));
1158 }
1159
Steve Narofff0b23542008-01-10 22:15:12 +00001160 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001161 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001162
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001163 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001164 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001165 if (CheckForConstantInitializer(literalExpr, literalType))
1166 return true;
1167 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001168 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001169}
1170
1171Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001172ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001173 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001174 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001175
Steve Naroff0acc9c92007-09-15 18:49:24 +00001176 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001177 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001178
Chris Lattner48d7f382008-04-02 04:24:33 +00001179 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1180 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1181 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001182}
1183
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001184/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001185bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001186 UsualUnaryConversions(castExpr);
1187
1188 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1189 // type needs to be scalar.
1190 if (castType->isVoidType()) {
1191 // Cast to void allows any expr type.
1192 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1193 // GCC struct/union extension: allow cast to self.
1194 if (Context.getCanonicalType(castType) !=
1195 Context.getCanonicalType(castExpr->getType()) ||
1196 (!castType->isStructureType() && !castType->isUnionType())) {
1197 // Reject any other conversions to non-scalar types.
1198 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1199 castType.getAsString(), castExpr->getSourceRange());
1200 }
1201
1202 // accept this, but emit an ext-warn.
1203 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1204 castType.getAsString(), castExpr->getSourceRange());
1205 } else if (!castExpr->getType()->isScalarType() &&
1206 !castExpr->getType()->isVectorType()) {
1207 return Diag(castExpr->getLocStart(),
1208 diag::err_typecheck_expect_scalar_operand,
1209 castExpr->getType().getAsString(),castExpr->getSourceRange());
1210 } else if (castExpr->getType()->isVectorType()) {
1211 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1212 return true;
1213 } else if (castType->isVectorType()) {
1214 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1215 return true;
1216 }
1217 return false;
1218}
1219
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001220bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001221 assert(VectorTy->isVectorType() && "Not a vector type!");
1222
1223 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001224 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001225 return Diag(R.getBegin(),
1226 Ty->isVectorType() ?
1227 diag::err_invalid_conversion_between_vectors :
1228 diag::err_invalid_conversion_between_vector_and_integer,
1229 VectorTy.getAsString().c_str(),
1230 Ty.getAsString().c_str(), R);
1231 } else
1232 return Diag(R.getBegin(),
1233 diag::err_invalid_conversion_between_vector_and_scalar,
1234 VectorTy.getAsString().c_str(),
1235 Ty.getAsString().c_str(), R);
1236
1237 return false;
1238}
1239
Chris Lattner4b009652007-07-25 00:24:17 +00001240Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001241ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001242 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001243 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001244
1245 Expr *castExpr = static_cast<Expr*>(Op);
1246 QualType castType = QualType::getFromOpaquePtr(Ty);
1247
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001248 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1249 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001250 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001251}
1252
Chris Lattner98a425c2007-11-26 01:40:58 +00001253/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1254/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001255inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1256 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1257 UsualUnaryConversions(cond);
1258 UsualUnaryConversions(lex);
1259 UsualUnaryConversions(rex);
1260 QualType condT = cond->getType();
1261 QualType lexT = lex->getType();
1262 QualType rexT = rex->getType();
1263
1264 // first, check the condition.
1265 if (!condT->isScalarType()) { // C99 6.5.15p2
1266 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1267 condT.getAsString());
1268 return QualType();
1269 }
Chris Lattner992ae932008-01-06 22:42:25 +00001270
1271 // Now check the two expressions.
1272
1273 // If both operands have arithmetic type, do the usual arithmetic conversions
1274 // to find a common type: C99 6.5.15p3,5.
1275 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001276 UsualArithmeticConversions(lex, rex);
1277 return lex->getType();
1278 }
Chris Lattner992ae932008-01-06 22:42:25 +00001279
1280 // If both operands are the same structure or union type, the result is that
1281 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001282 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001283 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001284 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001285 // "If both the operands have structure or union type, the result has
1286 // that type." This implies that CV qualifiers are dropped.
1287 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001288 }
Chris Lattner992ae932008-01-06 22:42:25 +00001289
1290 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001291 // The following || allows only one side to be void (a GCC-ism).
1292 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001293 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001294 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1295 rex->getSourceRange());
1296 if (!rexT->isVoidType())
1297 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001298 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001299 ImpCastExprToType(lex, Context.VoidTy);
1300 ImpCastExprToType(rex, Context.VoidTy);
1301 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001302 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001303 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1304 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001305 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1306 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001307 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001308 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001309 return lexT;
1310 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001311 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1312 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001313 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001314 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001315 return rexT;
1316 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001317 // Handle the case where both operands are pointers before we handle null
1318 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001319 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1320 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1321 // get the "pointed to" types
1322 QualType lhptee = LHSPT->getPointeeType();
1323 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001324
Chris Lattner71225142007-07-31 21:27:01 +00001325 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1326 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001327 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001328 // Figure out necessary qualifiers (C99 6.5.15p6)
1329 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001330 QualType destType = Context.getPointerType(destPointee);
1331 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1332 ImpCastExprToType(rex, destType); // promote to void*
1333 return destType;
1334 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001335 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001336 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001337 QualType destType = Context.getPointerType(destPointee);
1338 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1339 ImpCastExprToType(rex, destType); // promote to void*
1340 return destType;
1341 }
Chris Lattner4b009652007-07-25 00:24:17 +00001342
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001343 QualType compositeType = lexT;
1344
1345 // If either type is an Objective-C object type then check
1346 // compatibility according to Objective-C.
1347 if (Context.isObjCObjectPointerType(lexT) ||
1348 Context.isObjCObjectPointerType(rexT)) {
1349 // If both operands are interfaces and either operand can be
1350 // assigned to the other, use that type as the composite
1351 // type. This allows
1352 // xxx ? (A*) a : (B*) b
1353 // where B is a subclass of A.
1354 //
1355 // Additionally, as for assignment, if either type is 'id'
1356 // allow silent coercion. Finally, if the types are
1357 // incompatible then make sure to use 'id' as the composite
1358 // type so the result is acceptable for sending messages to.
1359
1360 // FIXME: This code should not be localized to here. Also this
1361 // should use a compatible check instead of abusing the
1362 // canAssignObjCInterfaces code.
1363 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1364 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1365 if (LHSIface && RHSIface &&
1366 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1367 compositeType = lexT;
1368 } else if (LHSIface && RHSIface &&
1369 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1370 compositeType = rexT;
1371 } else if (Context.isObjCIdType(lhptee) ||
1372 Context.isObjCIdType(rhptee)) {
1373 // FIXME: This code looks wrong, because isObjCIdType checks
1374 // the struct but getObjCIdType returns the pointer to
1375 // struct. This is horrible and should be fixed.
1376 compositeType = Context.getObjCIdType();
1377 } else {
1378 QualType incompatTy = Context.getObjCIdType();
1379 ImpCastExprToType(lex, incompatTy);
1380 ImpCastExprToType(rex, incompatTy);
1381 return incompatTy;
1382 }
1383 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1384 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001385 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001386 lexT.getAsString(), rexT.getAsString(),
1387 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001388 // In this situation, we assume void* type. No especially good
1389 // reason, but this is what gcc does, and we do have to pick
1390 // to get a consistent AST.
1391 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001392 ImpCastExprToType(lex, incompatTy);
1393 ImpCastExprToType(rex, incompatTy);
1394 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001395 }
1396 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001397 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1398 // differently qualified versions of compatible types, the result type is
1399 // a pointer to an appropriately qualified version of the *composite*
1400 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001401 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001402 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001403 ImpCastExprToType(lex, compositeType);
1404 ImpCastExprToType(rex, compositeType);
1405 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001406 }
Chris Lattner4b009652007-07-25 00:24:17 +00001407 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001408 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1409 // evaluates to "struct objc_object *" (and is handled above when comparing
1410 // id with statically typed objects).
1411 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1412 // GCC allows qualified id and any Objective-C type to devolve to
1413 // id. Currently localizing to here until clear this should be
1414 // part of ObjCQualifiedIdTypesAreCompatible.
1415 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1416 (lexT->isObjCQualifiedIdType() &&
1417 Context.isObjCObjectPointerType(rexT)) ||
1418 (rexT->isObjCQualifiedIdType() &&
1419 Context.isObjCObjectPointerType(lexT))) {
1420 // FIXME: This is not the correct composite type. This only
1421 // happens to work because id can more or less be used anywhere,
1422 // however this may change the type of method sends.
1423 // FIXME: gcc adds some type-checking of the arguments and emits
1424 // (confusing) incompatible comparison warnings in some
1425 // cases. Investigate.
1426 QualType compositeType = Context.getObjCIdType();
1427 ImpCastExprToType(lex, compositeType);
1428 ImpCastExprToType(rex, compositeType);
1429 return compositeType;
1430 }
1431 }
1432
Steve Naroff3eac7692008-09-10 19:17:48 +00001433 // Selection between block pointer types is ok as long as they are the same.
1434 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1435 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1436 return lexT;
1437
Chris Lattner992ae932008-01-06 22:42:25 +00001438 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001439 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1440 lexT.getAsString(), rexT.getAsString(),
1441 lex->getSourceRange(), rex->getSourceRange());
1442 return QualType();
1443}
1444
Steve Naroff87d58b42007-09-16 03:34:24 +00001445/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001446/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001447Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001448 SourceLocation ColonLoc,
1449 ExprTy *Cond, ExprTy *LHS,
1450 ExprTy *RHS) {
1451 Expr *CondExpr = (Expr *) Cond;
1452 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001453
1454 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1455 // was the condition.
1456 bool isLHSNull = LHSExpr == 0;
1457 if (isLHSNull)
1458 LHSExpr = CondExpr;
1459
Chris Lattner4b009652007-07-25 00:24:17 +00001460 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1461 RHSExpr, QuestionLoc);
1462 if (result.isNull())
1463 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001464 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1465 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001466}
1467
Chris Lattner4b009652007-07-25 00:24:17 +00001468
1469// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1470// being closely modeled after the C99 spec:-). The odd characteristic of this
1471// routine is it effectively iqnores the qualifiers on the top level pointee.
1472// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1473// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001474Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001475Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1476 QualType lhptee, rhptee;
1477
1478 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001479 lhptee = lhsType->getAsPointerType()->getPointeeType();
1480 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001481
1482 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001483 lhptee = Context.getCanonicalType(lhptee);
1484 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001485
Chris Lattner005ed752008-01-04 18:04:52 +00001486 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001487
1488 // C99 6.5.16.1p1: This following citation is common to constraints
1489 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1490 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001491 // FIXME: Handle ASQualType
1492 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1493 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001494 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001495
1496 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1497 // incomplete type and the other is a pointer to a qualified or unqualified
1498 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001499 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001500 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001501 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001502
1503 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001504 assert(rhptee->isFunctionType());
1505 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001506 }
1507
1508 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001509 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001510 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001511
1512 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001513 assert(lhptee->isFunctionType());
1514 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001515 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001516
1517 // Check for ObjC interfaces
1518 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1519 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1520 if (LHSIface && RHSIface &&
1521 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1522 return ConvTy;
1523
1524 // ID acts sort of like void* for ObjC interfaces
1525 if (LHSIface && Context.isObjCIdType(rhptee))
1526 return ConvTy;
1527 if (RHSIface && Context.isObjCIdType(lhptee))
1528 return ConvTy;
1529
Chris Lattner4b009652007-07-25 00:24:17 +00001530 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1531 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001532 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1533 rhptee.getUnqualifiedType()))
1534 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001535 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001536}
1537
Steve Naroff3454b6c2008-09-04 15:10:53 +00001538/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1539/// block pointer types are compatible or whether a block and normal pointer
1540/// are compatible. It is more restrict than comparing two function pointer
1541// types.
1542Sema::AssignConvertType
1543Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1544 QualType rhsType) {
1545 QualType lhptee, rhptee;
1546
1547 // get the "pointed to" type (ignoring qualifiers at the top level)
1548 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1549 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1550
1551 // make sure we operate on the canonical type
1552 lhptee = Context.getCanonicalType(lhptee);
1553 rhptee = Context.getCanonicalType(rhptee);
1554
1555 AssignConvertType ConvTy = Compatible;
1556
1557 // For blocks we enforce that qualifiers are identical.
1558 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1559 ConvTy = CompatiblePointerDiscardsQualifiers;
1560
1561 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1562 return IncompatibleBlockPointer;
1563 return ConvTy;
1564}
1565
Chris Lattner4b009652007-07-25 00:24:17 +00001566/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1567/// has code to accommodate several GCC extensions when type checking
1568/// pointers. Here are some objectionable examples that GCC considers warnings:
1569///
1570/// int a, *pint;
1571/// short *pshort;
1572/// struct foo *pfoo;
1573///
1574/// pint = pshort; // warning: assignment from incompatible pointer type
1575/// a = pint; // warning: assignment makes integer from pointer without a cast
1576/// pint = a; // warning: assignment makes pointer from integer without a cast
1577/// pint = pfoo; // warning: assignment from incompatible pointer type
1578///
1579/// As a result, the code for dealing with pointers is more complex than the
1580/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001581///
Chris Lattner005ed752008-01-04 18:04:52 +00001582Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001583Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001584 // Get canonical types. We're not formatting these types, just comparing
1585 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001586 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1587 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001588
1589 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001590 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001591
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001592 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001593 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001594 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001595 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001596 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001597
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001598 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1599 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001600 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001601 // Relax integer conversions like we do for pointers below.
1602 if (rhsType->isIntegerType())
1603 return IntToPointer;
1604 if (lhsType->isIntegerType())
1605 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001606 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001607 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001608
Nate Begemanc5f0f652008-07-14 18:02:46 +00001609 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001610 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001611 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1612 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001613 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001614
Nate Begemanc5f0f652008-07-14 18:02:46 +00001615 // If we are allowing lax vector conversions, and LHS and RHS are both
1616 // vectors, the total size only needs to be the same. This is a bitcast;
1617 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001618 if (getLangOptions().LaxVectorConversions &&
1619 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001620 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1621 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001622 }
1623 return Incompatible;
1624 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001625
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001626 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001627 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001628
Chris Lattner390564e2008-04-07 06:49:41 +00001629 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001630 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001631 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001632
Chris Lattner390564e2008-04-07 06:49:41 +00001633 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001634 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001635
Steve Naroffd6163f32008-09-05 22:11:13 +00001636 if (rhsType->getAsBlockPointerType())
1637 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001638 return BlockVoidPointer;
1639
1640 return Incompatible;
1641 }
1642
1643 if (isa<BlockPointerType>(lhsType)) {
1644 if (rhsType->isIntegerType())
1645 return IntToPointer;
1646
1647 if (rhsType->isBlockPointerType())
1648 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1649
1650 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1651 if (RHSPT->getPointeeType()->isVoidType())
1652 return BlockVoidPointer;
1653 }
Chris Lattner1853da22008-01-04 23:18:45 +00001654 return Incompatible;
1655 }
1656
Chris Lattner390564e2008-04-07 06:49:41 +00001657 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001658 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001659 if (lhsType == Context.BoolTy)
1660 return Compatible;
1661
1662 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001663 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001664
Chris Lattner390564e2008-04-07 06:49:41 +00001665 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001666 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001667
1668 if (isa<BlockPointerType>(lhsType) &&
1669 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1670 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001671 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001672 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001673
Chris Lattner1853da22008-01-04 23:18:45 +00001674 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001675 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001676 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001677 }
1678 return Incompatible;
1679}
1680
Chris Lattner005ed752008-01-04 18:04:52 +00001681Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001682Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001683 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1684 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001685 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1686 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001687 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001688 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001689 return Compatible;
1690 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001691
1692 // We don't allow conversion of non-null-pointer constants to integers.
1693 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1694 return IntToBlockPointer;
1695
Chris Lattner5f505bf2007-10-16 02:55:40 +00001696 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001697 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001698 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001699 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001700 //
1701 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1702 // are better understood.
1703 if (!lhsType->isReferenceType())
1704 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001705
Chris Lattner005ed752008-01-04 18:04:52 +00001706 Sema::AssignConvertType result =
1707 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001708
1709 // C99 6.5.16.1p2: The value of the right operand is converted to the
1710 // type of the assignment expression.
1711 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001712 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001713 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001714}
1715
Chris Lattner005ed752008-01-04 18:04:52 +00001716Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001717Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1718 return CheckAssignmentConstraints(lhsType, rhsType);
1719}
1720
Chris Lattner2c8bff72007-12-12 05:47:28 +00001721QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001722 Diag(loc, diag::err_typecheck_invalid_operands,
1723 lex->getType().getAsString(), rex->getType().getAsString(),
1724 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001725 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001726}
1727
1728inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1729 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001730 // For conversion purposes, we ignore any qualifiers.
1731 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001732 QualType lhsType =
1733 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1734 QualType rhsType =
1735 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001736
Nate Begemanc5f0f652008-07-14 18:02:46 +00001737 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001738 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001739 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001740
Nate Begemanc5f0f652008-07-14 18:02:46 +00001741 // Handle the case of a vector & extvector type of the same size and element
1742 // type. It would be nice if we only had one vector type someday.
1743 if (getLangOptions().LaxVectorConversions)
1744 if (const VectorType *LV = lhsType->getAsVectorType())
1745 if (const VectorType *RV = rhsType->getAsVectorType())
1746 if (LV->getElementType() == RV->getElementType() &&
1747 LV->getNumElements() == RV->getNumElements())
1748 return lhsType->isExtVectorType() ? lhsType : rhsType;
1749
1750 // If the lhs is an extended vector and the rhs is a scalar of the same type
1751 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001752 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001753 QualType eltType = V->getElementType();
1754
1755 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1756 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1757 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001758 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001759 return lhsType;
1760 }
1761 }
1762
Nate Begemanc5f0f652008-07-14 18:02:46 +00001763 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001764 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001765 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001766 QualType eltType = V->getElementType();
1767
1768 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1769 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1770 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001771 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001772 return rhsType;
1773 }
1774 }
1775
Chris Lattner4b009652007-07-25 00:24:17 +00001776 // You cannot convert between vector values of different size.
1777 Diag(loc, diag::err_typecheck_vector_not_convertable,
1778 lex->getType().getAsString(), rex->getType().getAsString(),
1779 lex->getSourceRange(), rex->getSourceRange());
1780 return QualType();
1781}
1782
1783inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001784 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001785{
1786 QualType lhsType = lex->getType(), rhsType = rex->getType();
1787
1788 if (lhsType->isVectorType() || rhsType->isVectorType())
1789 return CheckVectorOperands(loc, lex, rex);
1790
Steve Naroff8f708362007-08-24 19:07:16 +00001791 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001792
Chris Lattner4b009652007-07-25 00:24:17 +00001793 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001794 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001795 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001796}
1797
1798inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001799 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001800{
1801 QualType lhsType = lex->getType(), rhsType = rex->getType();
1802
Steve Naroff8f708362007-08-24 19:07:16 +00001803 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001804
Chris Lattner4b009652007-07-25 00:24:17 +00001805 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001806 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001807 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001808}
1809
1810inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001811 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001812{
1813 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1814 return CheckVectorOperands(loc, lex, rex);
1815
Steve Naroff8f708362007-08-24 19:07:16 +00001816 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001817
Chris Lattner4b009652007-07-25 00:24:17 +00001818 // handle the common case first (both operands are arithmetic).
1819 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001820 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001821
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001822 // Put any potential pointer into PExp
1823 Expr* PExp = lex, *IExp = rex;
1824 if (IExp->getType()->isPointerType())
1825 std::swap(PExp, IExp);
1826
1827 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1828 if (IExp->getType()->isIntegerType()) {
1829 // Check for arithmetic on pointers to incomplete types
1830 if (!PTy->getPointeeType()->isObjectType()) {
1831 if (PTy->getPointeeType()->isVoidType()) {
1832 Diag(loc, diag::ext_gnu_void_ptr,
1833 lex->getSourceRange(), rex->getSourceRange());
1834 } else {
1835 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1836 lex->getType().getAsString(), lex->getSourceRange());
1837 return QualType();
1838 }
1839 }
1840 return PExp->getType();
1841 }
1842 }
1843
Chris Lattner2c8bff72007-12-12 05:47:28 +00001844 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001845}
1846
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001847// C99 6.5.6
1848QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1849 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001850 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1851 return CheckVectorOperands(loc, lex, rex);
1852
Steve Naroff8f708362007-08-24 19:07:16 +00001853 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001854
Chris Lattnerf6da2912007-12-09 21:53:25 +00001855 // Enforce type constraints: C99 6.5.6p3.
1856
1857 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001858 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001859 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001860
1861 // Either ptr - int or ptr - ptr.
1862 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001863 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001864
Chris Lattnerf6da2912007-12-09 21:53:25 +00001865 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001866 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001867 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001868 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001869 Diag(loc, diag::ext_gnu_void_ptr,
1870 lex->getSourceRange(), rex->getSourceRange());
1871 } else {
1872 Diag(loc, diag::err_typecheck_sub_ptr_object,
1873 lex->getType().getAsString(), lex->getSourceRange());
1874 return QualType();
1875 }
1876 }
1877
1878 // The result type of a pointer-int computation is the pointer type.
1879 if (rex->getType()->isIntegerType())
1880 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001881
Chris Lattnerf6da2912007-12-09 21:53:25 +00001882 // Handle pointer-pointer subtractions.
1883 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001884 QualType rpointee = RHSPTy->getPointeeType();
1885
Chris Lattnerf6da2912007-12-09 21:53:25 +00001886 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001887 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001888 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001889 if (rpointee->isVoidType()) {
1890 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001891 Diag(loc, diag::ext_gnu_void_ptr,
1892 lex->getSourceRange(), rex->getSourceRange());
1893 } else {
1894 Diag(loc, diag::err_typecheck_sub_ptr_object,
1895 rex->getType().getAsString(), rex->getSourceRange());
1896 return QualType();
1897 }
1898 }
1899
1900 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00001901 if (!Context.typesAreCompatible(
1902 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1903 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001904 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1905 lex->getType().getAsString(), rex->getType().getAsString(),
1906 lex->getSourceRange(), rex->getSourceRange());
1907 return QualType();
1908 }
1909
1910 return Context.getPointerDiffType();
1911 }
1912 }
1913
Chris Lattner2c8bff72007-12-12 05:47:28 +00001914 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001915}
1916
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001917// C99 6.5.7
1918QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1919 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001920 // C99 6.5.7p2: Each of the operands shall have integer type.
1921 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1922 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001923
Chris Lattner2c8bff72007-12-12 05:47:28 +00001924 // Shifts don't perform usual arithmetic conversions, they just do integer
1925 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001926 if (!isCompAssign)
1927 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001928 UsualUnaryConversions(rex);
1929
1930 // "The type of the result is that of the promoted left operand."
1931 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001932}
1933
Eli Friedman0d9549b2008-08-22 00:56:42 +00001934static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1935 ASTContext& Context) {
1936 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1937 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1938 // ID acts sort of like void* for ObjC interfaces
1939 if (LHSIface && Context.isObjCIdType(RHS))
1940 return true;
1941 if (RHSIface && Context.isObjCIdType(LHS))
1942 return true;
1943 if (!LHSIface || !RHSIface)
1944 return false;
1945 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1946 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1947}
1948
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001949// C99 6.5.8
1950QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1951 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001952 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1953 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1954
Chris Lattner254f3bc2007-08-26 01:18:55 +00001955 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001956 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1957 UsualArithmeticConversions(lex, rex);
1958 else {
1959 UsualUnaryConversions(lex);
1960 UsualUnaryConversions(rex);
1961 }
Chris Lattner4b009652007-07-25 00:24:17 +00001962 QualType lType = lex->getType();
1963 QualType rType = rex->getType();
1964
Ted Kremenek486509e2007-10-29 17:13:39 +00001965 // For non-floating point types, check for self-comparisons of the form
1966 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1967 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001968 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001969 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1970 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001971 if (DRL->getDecl() == DRR->getDecl())
1972 Diag(loc, diag::warn_selfcomparison);
1973 }
1974
Chris Lattner254f3bc2007-08-26 01:18:55 +00001975 if (isRelational) {
1976 if (lType->isRealType() && rType->isRealType())
1977 return Context.IntTy;
1978 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001979 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001980 if (lType->isFloatingType()) {
1981 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001982 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001983 }
1984
Chris Lattner254f3bc2007-08-26 01:18:55 +00001985 if (lType->isArithmeticType() && rType->isArithmeticType())
1986 return Context.IntTy;
1987 }
Chris Lattner4b009652007-07-25 00:24:17 +00001988
Chris Lattner22be8422007-08-26 01:10:14 +00001989 bool LHSIsNull = lex->isNullPointerConstant(Context);
1990 bool RHSIsNull = rex->isNullPointerConstant(Context);
1991
Chris Lattner254f3bc2007-08-26 01:18:55 +00001992 // All of the following pointer related warnings are GCC extensions, except
1993 // when handling null pointer constants. One day, we can consider making them
1994 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001995 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001996 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001997 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001998 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001999 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002000
Steve Naroff3b435622007-11-13 14:57:38 +00002001 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002002 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2003 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002004 RCanPointeeTy.getUnqualifiedType()) &&
2005 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002006 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2007 lType.getAsString(), rType.getAsString(),
2008 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002009 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002010 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002011 return Context.IntTy;
2012 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002013 // Handle block pointer types.
2014 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2015 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2016 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2017
2018 if (!LHSIsNull && !RHSIsNull &&
2019 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2020 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2021 lType.getAsString(), rType.getAsString(),
2022 lex->getSourceRange(), rex->getSourceRange());
2023 }
2024 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2025 return Context.IntTy;
2026 }
2027
Steve Naroff936c4362008-06-03 14:04:54 +00002028 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2029 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2030 ImpCastExprToType(rex, lType);
2031 return Context.IntTy;
2032 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002033 }
Steve Naroff936c4362008-06-03 14:04:54 +00002034 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2035 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002036 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002037 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2038 lType.getAsString(), rType.getAsString(),
2039 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002040 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002041 return Context.IntTy;
2042 }
Steve Naroff936c4362008-06-03 14:04:54 +00002043 if (lType->isIntegerType() &&
2044 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002045 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002046 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2047 lType.getAsString(), rType.getAsString(),
2048 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002049 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002050 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002051 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002052 // Handle block pointers.
2053 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2054 if (!RHSIsNull)
2055 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2056 lType.getAsString(), rType.getAsString(),
2057 lex->getSourceRange(), rex->getSourceRange());
2058 ImpCastExprToType(rex, lType); // promote the integer to pointer
2059 return Context.IntTy;
2060 }
2061 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2062 if (!LHSIsNull)
2063 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2064 lType.getAsString(), rType.getAsString(),
2065 lex->getSourceRange(), rex->getSourceRange());
2066 ImpCastExprToType(lex, rType); // promote the integer to pointer
2067 return Context.IntTy;
2068 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002069 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002070}
2071
Nate Begemanc5f0f652008-07-14 18:02:46 +00002072/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2073/// operates on extended vector types. Instead of producing an IntTy result,
2074/// like a scalar comparison, a vector comparison produces a vector of integer
2075/// types.
2076QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2077 SourceLocation loc,
2078 bool isRelational) {
2079 // Check to make sure we're operating on vectors of the same type and width,
2080 // Allowing one side to be a scalar of element type.
2081 QualType vType = CheckVectorOperands(loc, lex, rex);
2082 if (vType.isNull())
2083 return vType;
2084
2085 QualType lType = lex->getType();
2086 QualType rType = rex->getType();
2087
2088 // For non-floating point types, check for self-comparisons of the form
2089 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2090 // often indicate logic errors in the program.
2091 if (!lType->isFloatingType()) {
2092 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2093 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2094 if (DRL->getDecl() == DRR->getDecl())
2095 Diag(loc, diag::warn_selfcomparison);
2096 }
2097
2098 // Check for comparisons of floating point operands using != and ==.
2099 if (!isRelational && lType->isFloatingType()) {
2100 assert (rType->isFloatingType());
2101 CheckFloatComparison(loc,lex,rex);
2102 }
2103
2104 // Return the type for the comparison, which is the same as vector type for
2105 // integer vectors, or an integer type of identical size and number of
2106 // elements for floating point vectors.
2107 if (lType->isIntegerType())
2108 return lType;
2109
2110 const VectorType *VTy = lType->getAsVectorType();
2111
2112 // FIXME: need to deal with non-32b int / non-64b long long
2113 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2114 if (TypeSize == 32) {
2115 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2116 }
2117 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2118 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2119}
2120
Chris Lattner4b009652007-07-25 00:24:17 +00002121inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002122 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002123{
2124 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2125 return CheckVectorOperands(loc, lex, rex);
2126
Steve Naroff8f708362007-08-24 19:07:16 +00002127 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002128
2129 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002130 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002131 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002132}
2133
2134inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2135 Expr *&lex, Expr *&rex, SourceLocation loc)
2136{
2137 UsualUnaryConversions(lex);
2138 UsualUnaryConversions(rex);
2139
Eli Friedmanbea3f842008-05-13 20:16:47 +00002140 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002141 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002142 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002143}
2144
2145inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002146 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002147{
2148 QualType lhsType = lex->getType();
2149 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002150 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002151
2152 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002153 case Expr::MLV_Valid:
2154 break;
2155 case Expr::MLV_ConstQualified:
2156 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2157 return QualType();
2158 case Expr::MLV_ArrayType:
2159 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2160 lhsType.getAsString(), lex->getSourceRange());
2161 return QualType();
2162 case Expr::MLV_NotObjectType:
2163 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2164 lhsType.getAsString(), lex->getSourceRange());
2165 return QualType();
2166 case Expr::MLV_InvalidExpression:
2167 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2168 lex->getSourceRange());
2169 return QualType();
2170 case Expr::MLV_IncompleteType:
2171 case Expr::MLV_IncompleteVoidType:
2172 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2173 lhsType.getAsString(), lex->getSourceRange());
2174 return QualType();
2175 case Expr::MLV_DuplicateVectorComponents:
2176 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2177 lex->getSourceRange());
2178 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002179 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002180
Chris Lattner005ed752008-01-04 18:04:52 +00002181 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002182 if (compoundType.isNull()) {
2183 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002184 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002185
2186 // If the RHS is a unary plus or minus, check to see if they = and + are
2187 // right next to each other. If so, the user may have typo'd "x =+ 4"
2188 // instead of "x += 4".
2189 Expr *RHSCheck = rex;
2190 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2191 RHSCheck = ICE->getSubExpr();
2192 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2193 if ((UO->getOpcode() == UnaryOperator::Plus ||
2194 UO->getOpcode() == UnaryOperator::Minus) &&
2195 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2196 // Only if the two operators are exactly adjacent.
2197 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2198 Diag(loc, diag::warn_not_compound_assign,
2199 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2200 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2201 }
2202 } else {
2203 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002204 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002205 }
Chris Lattner005ed752008-01-04 18:04:52 +00002206
2207 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2208 rex, "assigning"))
2209 return QualType();
2210
Chris Lattner4b009652007-07-25 00:24:17 +00002211 // C99 6.5.16p3: The type of an assignment expression is the type of the
2212 // left operand unless the left operand has qualified type, in which case
2213 // it is the unqualified version of the type of the left operand.
2214 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2215 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002216 // C++ 5.17p1: the type of the assignment expression is that of its left
2217 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002218 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002219}
2220
2221inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2222 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002223
2224 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2225 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002226 return rex->getType();
2227}
2228
2229/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2230/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2231QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2232 QualType resType = op->getType();
2233 assert(!resType.isNull() && "no type for increment/decrement expression");
2234
Steve Naroffd30e1932007-08-24 17:20:07 +00002235 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002236 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002237 if (pt->getPointeeType()->isVoidType()) {
2238 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2239 } else if (!pt->getPointeeType()->isObjectType()) {
2240 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002241 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2242 resType.getAsString(), op->getSourceRange());
2243 return QualType();
2244 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002245 } else if (!resType->isRealType()) {
2246 if (resType->isComplexType())
2247 // C99 does not support ++/-- on complex types.
2248 Diag(OpLoc, diag::ext_integer_increment_complex,
2249 resType.getAsString(), op->getSourceRange());
2250 else {
2251 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2252 resType.getAsString(), op->getSourceRange());
2253 return QualType();
2254 }
Chris Lattner4b009652007-07-25 00:24:17 +00002255 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002256 // At this point, we know we have a real, complex or pointer type.
2257 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002258 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002259 if (mlval != Expr::MLV_Valid) {
2260 // FIXME: emit a more precise diagnostic...
2261 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2262 op->getSourceRange());
2263 return QualType();
2264 }
2265 return resType;
2266}
2267
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002268/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002269/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002270/// where the declaration is needed for type checking. We only need to
2271/// handle cases when the expression references a function designator
2272/// or is an lvalue. Here are some examples:
2273/// - &(x) => x
2274/// - &*****f => f for f a function designator.
2275/// - &s.xx => s
2276/// - &s.zz[1].yy -> s, if zz is an array
2277/// - *(x + 1) -> x, if x is an array
2278/// - &"123"[2] -> 0
2279/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00002280static ValueDecl *getPrimaryDecl(Expr *E) {
2281 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002282 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002283 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002284 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002285 // Fields cannot be declared with a 'register' storage class.
2286 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002287 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002288 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002289 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002290 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002291 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002292
Chris Lattner48d7f382008-04-02 04:24:33 +00002293 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00002294 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002295 return 0;
2296 else
2297 return VD;
2298 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002299 case Stmt::UnaryOperatorClass: {
2300 UnaryOperator *UO = cast<UnaryOperator>(E);
2301
2302 switch(UO->getOpcode()) {
2303 case UnaryOperator::Deref: {
2304 // *(X + 1) refers to X if X is not a pointer.
2305 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2306 if (!VD || VD->getType()->isPointerType())
2307 return 0;
2308 return VD;
2309 }
2310 case UnaryOperator::Real:
2311 case UnaryOperator::Imag:
2312 case UnaryOperator::Extension:
2313 return getPrimaryDecl(UO->getSubExpr());
2314 default:
2315 return 0;
2316 }
2317 }
2318 case Stmt::BinaryOperatorClass: {
2319 BinaryOperator *BO = cast<BinaryOperator>(E);
2320
2321 // Handle cases involving pointer arithmetic. The result of an
2322 // Assign or AddAssign is not an lvalue so they can be ignored.
2323
2324 // (x + n) or (n + x) => x
2325 if (BO->getOpcode() == BinaryOperator::Add) {
2326 if (BO->getLHS()->getType()->isPointerType()) {
2327 return getPrimaryDecl(BO->getLHS());
2328 } else if (BO->getRHS()->getType()->isPointerType()) {
2329 return getPrimaryDecl(BO->getRHS());
2330 }
2331 }
2332
2333 return 0;
2334 }
Chris Lattner4b009652007-07-25 00:24:17 +00002335 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002336 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002337 case Stmt::ImplicitCastExprClass:
2338 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002339 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002340 default:
2341 return 0;
2342 }
2343}
2344
2345/// CheckAddressOfOperand - The operand of & must be either a function
2346/// designator or an lvalue designating an object. If it is an lvalue, the
2347/// object cannot be declared with storage class register or be a bit field.
2348/// Note: The usual conversions are *not* applied to the operand of the &
2349/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2350QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002351 if (getLangOptions().C99) {
2352 // Implement C99-only parts of addressof rules.
2353 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2354 if (uOp->getOpcode() == UnaryOperator::Deref)
2355 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2356 // (assuming the deref expression is valid).
2357 return uOp->getSubExpr()->getType();
2358 }
2359 // Technically, there should be a check for array subscript
2360 // expressions here, but the result of one is always an lvalue anyway.
2361 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002362 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002363 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002364
2365 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002366 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2367 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002368 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2369 op->getSourceRange());
2370 return QualType();
2371 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002372 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2373 if (MemExpr->getMemberDecl()->isBitField()) {
2374 Diag(OpLoc, diag::err_typecheck_address_of,
2375 std::string("bit-field"), op->getSourceRange());
2376 return QualType();
2377 }
2378 // Check for Apple extension for accessing vector components.
2379 } else if (isa<ArraySubscriptExpr>(op) &&
2380 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2381 Diag(OpLoc, diag::err_typecheck_address_of,
2382 std::string("vector"), op->getSourceRange());
2383 return QualType();
2384 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002385 // We have an lvalue with a decl. Make sure the decl is not declared
2386 // with the register storage-class specifier.
2387 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2388 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002389 Diag(OpLoc, diag::err_typecheck_address_of,
2390 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002391 return QualType();
2392 }
2393 } else
2394 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002395 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002396
Chris Lattner4b009652007-07-25 00:24:17 +00002397 // If the operand has type "type", the result has type "pointer to type".
2398 return Context.getPointerType(op->getType());
2399}
2400
2401QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2402 UsualUnaryConversions(op);
2403 QualType qType = op->getType();
2404
Chris Lattner7931f4a2007-07-31 16:53:04 +00002405 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002406 // Note that per both C89 and C99, this is always legal, even
2407 // if ptype is an incomplete type or void.
2408 // It would be possible to warn about dereferencing a
2409 // void pointer, but it's completely well-defined,
2410 // and such a warning is unlikely to catch any mistakes.
2411 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002412 }
2413 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2414 qType.getAsString(), op->getSourceRange());
2415 return QualType();
2416}
2417
2418static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2419 tok::TokenKind Kind) {
2420 BinaryOperator::Opcode Opc;
2421 switch (Kind) {
2422 default: assert(0 && "Unknown binop!");
2423 case tok::star: Opc = BinaryOperator::Mul; break;
2424 case tok::slash: Opc = BinaryOperator::Div; break;
2425 case tok::percent: Opc = BinaryOperator::Rem; break;
2426 case tok::plus: Opc = BinaryOperator::Add; break;
2427 case tok::minus: Opc = BinaryOperator::Sub; break;
2428 case tok::lessless: Opc = BinaryOperator::Shl; break;
2429 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2430 case tok::lessequal: Opc = BinaryOperator::LE; break;
2431 case tok::less: Opc = BinaryOperator::LT; break;
2432 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2433 case tok::greater: Opc = BinaryOperator::GT; break;
2434 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2435 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2436 case tok::amp: Opc = BinaryOperator::And; break;
2437 case tok::caret: Opc = BinaryOperator::Xor; break;
2438 case tok::pipe: Opc = BinaryOperator::Or; break;
2439 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2440 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2441 case tok::equal: Opc = BinaryOperator::Assign; break;
2442 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2443 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2444 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2445 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2446 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2447 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2448 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2449 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2450 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2451 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2452 case tok::comma: Opc = BinaryOperator::Comma; break;
2453 }
2454 return Opc;
2455}
2456
2457static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2458 tok::TokenKind Kind) {
2459 UnaryOperator::Opcode Opc;
2460 switch (Kind) {
2461 default: assert(0 && "Unknown unary op!");
2462 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2463 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2464 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2465 case tok::star: Opc = UnaryOperator::Deref; break;
2466 case tok::plus: Opc = UnaryOperator::Plus; break;
2467 case tok::minus: Opc = UnaryOperator::Minus; break;
2468 case tok::tilde: Opc = UnaryOperator::Not; break;
2469 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2470 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2471 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2472 case tok::kw___real: Opc = UnaryOperator::Real; break;
2473 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2474 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2475 }
2476 return Opc;
2477}
2478
2479// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002480Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002481 ExprTy *LHS, ExprTy *RHS) {
2482 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2483 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2484
Steve Naroff87d58b42007-09-16 03:34:24 +00002485 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2486 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002487
2488 QualType ResultTy; // Result type of the binary operator.
2489 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2490
2491 switch (Opc) {
2492 default:
2493 assert(0 && "Unknown binary expr!");
2494 case BinaryOperator::Assign:
2495 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2496 break;
2497 case BinaryOperator::Mul:
2498 case BinaryOperator::Div:
2499 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2500 break;
2501 case BinaryOperator::Rem:
2502 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2503 break;
2504 case BinaryOperator::Add:
2505 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2506 break;
2507 case BinaryOperator::Sub:
2508 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2509 break;
2510 case BinaryOperator::Shl:
2511 case BinaryOperator::Shr:
2512 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2513 break;
2514 case BinaryOperator::LE:
2515 case BinaryOperator::LT:
2516 case BinaryOperator::GE:
2517 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002518 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002519 break;
2520 case BinaryOperator::EQ:
2521 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002522 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002523 break;
2524 case BinaryOperator::And:
2525 case BinaryOperator::Xor:
2526 case BinaryOperator::Or:
2527 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2528 break;
2529 case BinaryOperator::LAnd:
2530 case BinaryOperator::LOr:
2531 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2532 break;
2533 case BinaryOperator::MulAssign:
2534 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002535 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002536 if (!CompTy.isNull())
2537 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2538 break;
2539 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002540 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002541 if (!CompTy.isNull())
2542 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2543 break;
2544 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002545 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002546 if (!CompTy.isNull())
2547 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2548 break;
2549 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002550 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002551 if (!CompTy.isNull())
2552 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2553 break;
2554 case BinaryOperator::ShlAssign:
2555 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002556 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002557 if (!CompTy.isNull())
2558 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2559 break;
2560 case BinaryOperator::AndAssign:
2561 case BinaryOperator::XorAssign:
2562 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002563 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002564 if (!CompTy.isNull())
2565 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2566 break;
2567 case BinaryOperator::Comma:
2568 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2569 break;
2570 }
2571 if (ResultTy.isNull())
2572 return true;
2573 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002574 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002575 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002576 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002577}
2578
2579// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002580Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002581 ExprTy *input) {
2582 Expr *Input = (Expr*)input;
2583 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2584 QualType resultType;
2585 switch (Opc) {
2586 default:
2587 assert(0 && "Unimplemented unary expr!");
2588 case UnaryOperator::PreInc:
2589 case UnaryOperator::PreDec:
2590 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2591 break;
2592 case UnaryOperator::AddrOf:
2593 resultType = CheckAddressOfOperand(Input, OpLoc);
2594 break;
2595 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002596 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002597 resultType = CheckIndirectionOperand(Input, OpLoc);
2598 break;
2599 case UnaryOperator::Plus:
2600 case UnaryOperator::Minus:
2601 UsualUnaryConversions(Input);
2602 resultType = Input->getType();
2603 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2604 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2605 resultType.getAsString());
2606 break;
2607 case UnaryOperator::Not: // bitwise complement
2608 UsualUnaryConversions(Input);
2609 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002610 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2611 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2612 // C99 does not support '~' for complex conjugation.
2613 Diag(OpLoc, diag::ext_integer_complement_complex,
2614 resultType.getAsString(), Input->getSourceRange());
2615 else if (!resultType->isIntegerType())
2616 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2617 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002618 break;
2619 case UnaryOperator::LNot: // logical negation
2620 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2621 DefaultFunctionArrayConversion(Input);
2622 resultType = Input->getType();
2623 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2624 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2625 resultType.getAsString());
2626 // LNot always has type int. C99 6.5.3.3p5.
2627 resultType = Context.IntTy;
2628 break;
2629 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002630 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2631 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002632 break;
2633 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002634 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2635 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002636 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002637 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002638 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002639 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002640 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002641 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002642 resultType = Input->getType();
2643 break;
2644 }
2645 if (resultType.isNull())
2646 return true;
2647 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2648}
2649
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002650/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2651Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002652 SourceLocation LabLoc,
2653 IdentifierInfo *LabelII) {
2654 // Look up the record for this label identifier.
2655 LabelStmt *&LabelDecl = LabelMap[LabelII];
2656
Daniel Dunbar879788d2008-08-04 16:51:22 +00002657 // If we haven't seen this label yet, create a forward reference. It
2658 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002659 if (LabelDecl == 0)
2660 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2661
2662 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002663 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2664 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002665}
2666
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002667Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002668 SourceLocation RPLoc) { // "({..})"
2669 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2670 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2671 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2672
2673 // FIXME: there are a variety of strange constraints to enforce here, for
2674 // example, it is not possible to goto into a stmt expression apparently.
2675 // More semantic analysis is needed.
2676
2677 // FIXME: the last statement in the compount stmt has its value used. We
2678 // should not warn about it being unused.
2679
2680 // If there are sub stmts in the compound stmt, take the type of the last one
2681 // as the type of the stmtexpr.
2682 QualType Ty = Context.VoidTy;
2683
Chris Lattner200964f2008-07-26 19:51:01 +00002684 if (!Compound->body_empty()) {
2685 Stmt *LastStmt = Compound->body_back();
2686 // If LastStmt is a label, skip down through into the body.
2687 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2688 LastStmt = Label->getSubStmt();
2689
2690 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002691 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002692 }
Chris Lattner4b009652007-07-25 00:24:17 +00002693
2694 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2695}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002696
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002697Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002698 SourceLocation TypeLoc,
2699 TypeTy *argty,
2700 OffsetOfComponent *CompPtr,
2701 unsigned NumComponents,
2702 SourceLocation RPLoc) {
2703 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2704 assert(!ArgTy.isNull() && "Missing type argument!");
2705
2706 // We must have at least one component that refers to the type, and the first
2707 // one is known to be a field designator. Verify that the ArgTy represents
2708 // a struct/union/class.
2709 if (!ArgTy->isRecordType())
2710 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2711
2712 // Otherwise, create a compound literal expression as the base, and
2713 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002714 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002715
Chris Lattnerb37522e2007-08-31 21:49:13 +00002716 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2717 // GCC extension, diagnose them.
2718 if (NumComponents != 1)
2719 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2720 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2721
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002722 for (unsigned i = 0; i != NumComponents; ++i) {
2723 const OffsetOfComponent &OC = CompPtr[i];
2724 if (OC.isBrackets) {
2725 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002726 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002727 if (!AT) {
2728 delete Res;
2729 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2730 Res->getType().getAsString());
2731 }
2732
Chris Lattner2af6a802007-08-30 17:59:59 +00002733 // FIXME: C++: Verify that operator[] isn't overloaded.
2734
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002735 // C99 6.5.2.1p1
2736 Expr *Idx = static_cast<Expr*>(OC.U.E);
2737 if (!Idx->getType()->isIntegerType())
2738 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2739 Idx->getSourceRange());
2740
2741 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2742 continue;
2743 }
2744
2745 const RecordType *RC = Res->getType()->getAsRecordType();
2746 if (!RC) {
2747 delete Res;
2748 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2749 Res->getType().getAsString());
2750 }
2751
2752 // Get the decl corresponding to this.
2753 RecordDecl *RD = RC->getDecl();
2754 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2755 if (!MemberDecl)
2756 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2757 OC.U.IdentInfo->getName(),
2758 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002759
2760 // FIXME: C++: Verify that MemberDecl isn't a static field.
2761 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002762 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2763 // matter here.
2764 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002765 }
2766
2767 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2768 BuiltinLoc);
2769}
2770
2771
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002772Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002773 TypeTy *arg1, TypeTy *arg2,
2774 SourceLocation RPLoc) {
2775 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2776 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2777
2778 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2779
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002780 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002781}
2782
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002783Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002784 ExprTy *expr1, ExprTy *expr2,
2785 SourceLocation RPLoc) {
2786 Expr *CondExpr = static_cast<Expr*>(cond);
2787 Expr *LHSExpr = static_cast<Expr*>(expr1);
2788 Expr *RHSExpr = static_cast<Expr*>(expr2);
2789
2790 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2791
2792 // The conditional expression is required to be a constant expression.
2793 llvm::APSInt condEval(32);
2794 SourceLocation ExpLoc;
2795 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2796 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2797 CondExpr->getSourceRange());
2798
2799 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2800 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2801 RHSExpr->getType();
2802 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2803}
2804
Steve Naroff52a81c02008-09-03 18:15:37 +00002805//===----------------------------------------------------------------------===//
2806// Clang Extensions.
2807//===----------------------------------------------------------------------===//
2808
2809/// ActOnBlockStart - This callback is invoked when a block literal is started.
2810void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2811 Declarator &ParamInfo) {
2812 // Analyze block parameters.
2813 BlockSemaInfo *BSI = new BlockSemaInfo();
2814
2815 // Add BSI to CurBlock.
2816 BSI->PrevBlockInfo = CurBlock;
2817 CurBlock = BSI;
2818
2819 BSI->ReturnType = 0;
2820 BSI->TheScope = BlockScope;
2821
2822 // Analyze arguments to block.
2823 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2824 "Not a function declarator!");
2825 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2826
2827 BSI->hasPrototype = FTI.hasPrototype;
2828 BSI->isVariadic = true;
2829
2830 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2831 // no arguments, not a function that takes a single void argument.
2832 if (FTI.hasPrototype &&
2833 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2834 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2835 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2836 // empty arg list, don't push any params.
2837 BSI->isVariadic = false;
2838 } else if (FTI.hasPrototype) {
2839 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2840 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2841 BSI->isVariadic = FTI.isVariadic;
2842 }
2843}
2844
2845/// ActOnBlockError - If there is an error parsing a block, this callback
2846/// is invoked to pop the information about the block from the action impl.
2847void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2848 // Ensure that CurBlock is deleted.
2849 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2850
2851 // Pop off CurBlock, handle nested blocks.
2852 CurBlock = CurBlock->PrevBlockInfo;
2853
2854 // FIXME: Delete the ParmVarDecl objects as well???
2855
2856}
2857
2858/// ActOnBlockStmtExpr - This is called when the body of a block statement
2859/// literal was successfully completed. ^(int x){...}
2860Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2861 Scope *CurScope) {
2862 // Ensure that CurBlock is deleted.
2863 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2864 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2865
2866 // Pop off CurBlock, handle nested blocks.
2867 CurBlock = CurBlock->PrevBlockInfo;
2868
2869 QualType RetTy = Context.VoidTy;
2870 if (BSI->ReturnType)
2871 RetTy = QualType(BSI->ReturnType, 0);
2872
2873 llvm::SmallVector<QualType, 8> ArgTypes;
2874 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2875 ArgTypes.push_back(BSI->Params[i]->getType());
2876
2877 QualType BlockTy;
2878 if (!BSI->hasPrototype)
2879 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2880 else
2881 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2882 BSI->isVariadic);
2883
2884 BlockTy = Context.getBlockPointerType(BlockTy);
2885 return new BlockStmtExpr(CaretLoc, BlockTy,
2886 &BSI->Params[0], BSI->Params.size(), Body.take());
2887}
2888
2889/// ActOnBlockExprExpr - This is called when the body of a block
2890/// expression literal was successfully completed. ^(int x)[foo bar: x]
2891Sema::ExprResult Sema::ActOnBlockExprExpr(SourceLocation CaretLoc, ExprTy *body,
2892 Scope *CurScope) {
2893 // Ensure that CurBlock is deleted.
2894 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2895 llvm::OwningPtr<Expr> Body(static_cast<Expr*>(body));
2896
2897 // Pop off CurBlock, handle nested blocks.
2898 CurBlock = CurBlock->PrevBlockInfo;
2899
2900 if (BSI->ReturnType) {
2901 Diag(CaretLoc, diag::err_return_in_block_expression);
2902 return true;
2903 }
2904
2905 QualType RetTy = Body->getType();
2906
2907 llvm::SmallVector<QualType, 8> ArgTypes;
2908 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2909 ArgTypes.push_back(BSI->Params[i]->getType());
2910
2911 QualType BlockTy;
2912 if (!BSI->hasPrototype)
2913 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2914 else
2915 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2916 BSI->isVariadic);
2917
2918 BlockTy = Context.getBlockPointerType(BlockTy);
2919 return new BlockExprExpr(CaretLoc, BlockTy,
2920 &BSI->Params[0], BSI->Params.size(), Body.take());
2921}
2922
Nate Begemanbd881ef2008-01-30 20:50:20 +00002923/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002924/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002925/// The number of arguments has already been validated to match the number of
2926/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002927static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2928 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002929 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002930 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002931 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2932 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002933
2934 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002935 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002936 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002937 return true;
2938}
2939
2940Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2941 SourceLocation *CommaLocs,
2942 SourceLocation BuiltinLoc,
2943 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002944 // __builtin_overload requires at least 2 arguments
2945 if (NumArgs < 2)
2946 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2947 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002948
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002949 // The first argument is required to be a constant expression. It tells us
2950 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002951 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002952 Expr *NParamsExpr = Args[0];
2953 llvm::APSInt constEval(32);
2954 SourceLocation ExpLoc;
2955 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2956 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2957 NParamsExpr->getSourceRange());
2958
2959 // Verify that the number of parameters is > 0
2960 unsigned NumParams = constEval.getZExtValue();
2961 if (NumParams == 0)
2962 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2963 NParamsExpr->getSourceRange());
2964 // Verify that we have at least 1 + NumParams arguments to the builtin.
2965 if ((NumParams + 1) > NumArgs)
2966 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2967 SourceRange(BuiltinLoc, RParenLoc));
2968
2969 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002970 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002971 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002972 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2973 // UsualUnaryConversions will convert the function DeclRefExpr into a
2974 // pointer to function.
2975 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002976 const FunctionTypeProto *FnType = 0;
2977 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2978 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002979
2980 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2981 // parameters, and the number of parameters must match the value passed to
2982 // the builtin.
2983 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002984 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2985 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002986
2987 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002988 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002989 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002990 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002991 if (OE)
2992 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2993 OE->getFn()->getSourceRange());
2994 // Remember our match, and continue processing the remaining arguments
2995 // to catch any errors.
2996 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2997 BuiltinLoc, RParenLoc);
2998 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002999 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003000 // Return the newly created OverloadExpr node, if we succeded in matching
3001 // exactly one of the candidate functions.
3002 if (OE)
3003 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003004
3005 // If we didn't find a matching function Expr in the __builtin_overload list
3006 // the return an error.
3007 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003008 for (unsigned i = 0; i != NumParams; ++i) {
3009 if (i != 0) typeNames += ", ";
3010 typeNames += Args[i+1]->getType().getAsString();
3011 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003012
3013 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3014 SourceRange(BuiltinLoc, RParenLoc));
3015}
3016
Anders Carlsson36760332007-10-15 20:28:48 +00003017Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3018 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003019 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003020 Expr *E = static_cast<Expr*>(expr);
3021 QualType T = QualType::getFromOpaquePtr(type);
3022
3023 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003024
3025 // Get the va_list type
3026 QualType VaListType = Context.getBuiltinVaListType();
3027 // Deal with implicit array decay; for example, on x86-64,
3028 // va_list is an array, but it's supposed to decay to
3029 // a pointer for va_arg.
3030 if (VaListType->isArrayType())
3031 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003032 // Make sure the input expression also decays appropriately.
3033 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003034
3035 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003036 return Diag(E->getLocStart(),
3037 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3038 E->getType().getAsString(),
3039 E->getSourceRange());
3040
3041 // FIXME: Warn if a non-POD type is passed in.
3042
3043 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3044}
3045
Chris Lattner005ed752008-01-04 18:04:52 +00003046bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3047 SourceLocation Loc,
3048 QualType DstType, QualType SrcType,
3049 Expr *SrcExpr, const char *Flavor) {
3050 // Decode the result (notice that AST's are still created for extensions).
3051 bool isInvalid = false;
3052 unsigned DiagKind;
3053 switch (ConvTy) {
3054 default: assert(0 && "Unknown conversion type");
3055 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003056 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003057 DiagKind = diag::ext_typecheck_convert_pointer_int;
3058 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003059 case IntToPointer:
3060 DiagKind = diag::ext_typecheck_convert_int_pointer;
3061 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003062 case IncompatiblePointer:
3063 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3064 break;
3065 case FunctionVoidPointer:
3066 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3067 break;
3068 case CompatiblePointerDiscardsQualifiers:
3069 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3070 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003071 case IntToBlockPointer:
3072 DiagKind = diag::err_int_to_block_pointer;
3073 break;
3074 case IncompatibleBlockPointer:
3075 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
3076 break;
3077 case BlockVoidPointer:
3078 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3079 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003080 case Incompatible:
3081 DiagKind = diag::err_typecheck_convert_incompatible;
3082 isInvalid = true;
3083 break;
3084 }
3085
3086 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3087 SrcExpr->getSourceRange());
3088 return isInvalid;
3089}