blob: 8a297ac1d7bd7e7a9c6b8a475cc6d6e4db2103c1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Chris Lattnere7a2e912008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattnere7a2e912008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39 Ty = E->getType();
40 }
41 if (Ty->isFunctionType())
42 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000043 else if (Ty->isArrayType()) {
44 // In C90 mode, arrays only promote to pointers if the array expression is
45 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46 // type 'array of type' is converted to an expression that has type 'pointer
47 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
48 // that has type 'array of type' ...". The relevant change is "an lvalue"
49 // (C90) to "an expression" (C99).
Chris Lattner28be73f2008-07-26 21:30:36 +000050 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000051 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
52 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000053}
54
55/// UsualUnaryConversions - Performs various conversions that are common to most
56/// operators (C99 6.3). The conversions of array and function types are
57/// sometimes surpressed. For example, the array->pointer conversion doesn't
58/// apply if the array is an argument to the sizeof or address (&) operators.
59/// In these instances, this routine should *not* be called.
60Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
61 QualType Ty = Expr->getType();
62 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
63
64 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
65 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
66 Ty = Expr->getType();
67 }
68 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
69 ImpCastExprToType(Expr, Context.IntTy);
70 else
71 DefaultFunctionArrayConversion(Expr);
72
73 return Expr;
74}
75
Chris Lattner05faf172008-07-25 22:25:12 +000076/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
77/// do not have a prototype. Arguments that have type float are promoted to
78/// double. All other argument types are converted by UsualUnaryConversions().
79void Sema::DefaultArgumentPromotion(Expr *&Expr) {
80 QualType Ty = Expr->getType();
81 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
82
83 // If this is a 'float' (CVR qualified or typedef) promote to double.
84 if (const BuiltinType *BT = Ty->getAsBuiltinType())
85 if (BT->getKind() == BuiltinType::Float)
86 return ImpCastExprToType(Expr, Context.DoubleTy);
87
88 UsualUnaryConversions(Expr);
89}
90
Chris Lattnere7a2e912008-07-25 21:10:04 +000091/// UsualArithmeticConversions - Performs various conversions that are common to
92/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
93/// routine returns the first non-arithmetic type found. The client is
94/// responsible for emitting appropriate error diagnostics.
95/// FIXME: verify the conversion rules for "complex int" are consistent with
96/// GCC.
97QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
98 bool isCompAssign) {
99 if (!isCompAssign) {
100 UsualUnaryConversions(lhsExpr);
101 UsualUnaryConversions(rhsExpr);
102 }
103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 // At this point, we have two different arithmetic types.
120
121 // Handle complex types first (C99 6.3.1.8p1).
122 if (lhs->isComplexType() || rhs->isComplexType()) {
123 // if we have an integer operand, the result is the complex type.
124 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
125 // convert the rhs to the lhs complex type.
126 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
127 return lhs;
128 }
129 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
130 // convert the lhs to the rhs complex type.
131 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
132 return rhs;
133 }
134 // This handles complex/complex, complex/float, or float/complex.
135 // When both operands are complex, the shorter operand is converted to the
136 // type of the longer, and that is the type of the result. This corresponds
137 // to what is done when combining two real floating-point operands.
138 // The fun begins when size promotion occur across type domains.
139 // From H&S 6.3.4: When one operand is complex and the other is a real
140 // floating-point type, the less precise type is converted, within it's
141 // real or complex domain, to the precision of the other type. For example,
142 // when combining a "long double" with a "double _Complex", the
143 // "double _Complex" is promoted to "long double _Complex".
144 int result = Context.getFloatingTypeOrder(lhs, rhs);
145
146 if (result > 0) { // The left side is bigger, convert rhs.
147 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
148 if (!isCompAssign)
149 ImpCastExprToType(rhsExpr, rhs);
150 } else if (result < 0) { // The right side is bigger, convert lhs.
151 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
152 if (!isCompAssign)
153 ImpCastExprToType(lhsExpr, lhs);
154 }
155 // At this point, lhs and rhs have the same rank/size. Now, make sure the
156 // domains match. This is a requirement for our implementation, C99
157 // does not require this promotion.
158 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
159 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
160 if (!isCompAssign)
161 ImpCastExprToType(lhsExpr, rhs);
162 return rhs;
163 } else { // handle "_Complex double, double".
164 if (!isCompAssign)
165 ImpCastExprToType(rhsExpr, lhs);
166 return lhs;
167 }
168 }
169 return lhs; // The domain/size match exactly.
170 }
171 // Now handle "real" floating types (i.e. float, double, long double).
172 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
173 // if we have an integer operand, the result is the real floating type.
174 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
175 // convert rhs to the lhs floating point type.
176 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
177 return lhs;
178 }
179 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
180 // convert lhs to the rhs floating point type.
181 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
182 return rhs;
183 }
184 // We have two real floating types, float/complex combos were handled above.
185 // Convert the smaller operand to the bigger result.
186 int result = Context.getFloatingTypeOrder(lhs, rhs);
187
188 if (result > 0) { // convert the rhs
189 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
190 return lhs;
191 }
192 if (result < 0) { // convert the lhs
193 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
194 return rhs;
195 }
196 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
197 }
198 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
199 // Handle GCC complex int extension.
200 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
201 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
202
203 if (lhsComplexInt && rhsComplexInt) {
204 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
205 rhsComplexInt->getElementType()) >= 0) {
206 // convert the rhs
207 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
208 return lhs;
209 }
210 if (!isCompAssign)
211 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
212 return rhs;
213 } else if (lhsComplexInt && rhs->isIntegerType()) {
214 // convert the rhs to the lhs complex type.
215 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
216 return lhs;
217 } else if (rhsComplexInt && lhs->isIntegerType()) {
218 // convert the lhs to the rhs complex type.
219 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
220 return rhs;
221 }
222 }
223 // Finally, we have two differing integer types.
224 // The rules for this case are in C99 6.3.1.8
225 int compare = Context.getIntegerTypeOrder(lhs, rhs);
226 bool lhsSigned = lhs->isSignedIntegerType(),
227 rhsSigned = rhs->isSignedIntegerType();
228 QualType destType;
229 if (lhsSigned == rhsSigned) {
230 // Same signedness; use the higher-ranked type
231 destType = compare >= 0 ? lhs : rhs;
232 } else if (compare != (lhsSigned ? 1 : -1)) {
233 // The unsigned type has greater than or equal rank to the
234 // signed type, so use the unsigned type
235 destType = lhsSigned ? rhs : lhs;
236 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
237 // The two types are different widths; if we are here, that
238 // means the signed type is larger than the unsigned type, so
239 // use the signed type.
240 destType = lhsSigned ? lhs : rhs;
241 } else {
242 // The signed type is higher-ranked than the unsigned type,
243 // but isn't actually any bigger (like unsigned int and long
244 // on most 32-bit systems). Use the unsigned type corresponding
245 // to the signed type.
246 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
247 }
248 if (!isCompAssign) {
249 ImpCastExprToType(lhsExpr, destType);
250 ImpCastExprToType(rhsExpr, destType);
251 }
252 return destType;
253}
254
255//===----------------------------------------------------------------------===//
256// Semantic Analysis for various Expression Types
257//===----------------------------------------------------------------------===//
258
259
Steve Narofff69936d2007-09-16 03:34:24 +0000260/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000261/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
262/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
263/// multiple tokens. However, the common case is that StringToks points to one
264/// string.
265///
266Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000267Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 assert(NumStringToks && "Must have at least one string!");
269
270 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
271 if (Literal.hadError)
272 return ExprResult(true);
273
274 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
275 for (unsigned i = 0; i != NumStringToks; ++i)
276 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000277
278 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000279 if (Literal.Pascal && Literal.GetStringLength() > 256)
280 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
281 SourceRange(StringToks[0].getLocation(),
282 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000283
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000284 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000285 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000286 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
287
288 // Get an array type for the string, according to C99 6.4.5. This includes
289 // the nul terminator character as well as the string length for pascal
290 // strings.
291 StrTy = Context.getConstantArrayType(StrTy,
292 llvm::APInt(32, Literal.GetStringLength()+1),
293 ArrayType::Normal, 0);
294
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
296 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000297 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000298 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 StringToks[NumStringToks-1].getLocation());
300}
301
Steve Naroffdd972f22008-09-05 22:11:13 +0000302/// DeclDefinedWithinScope - Return true if the specified decl is defined at or
303/// within the 'Within' scope. The current Scope is CurScope.
304///
305/// NOTE: This method is extremely inefficient (linear scan), this should not be
306/// used in common cases.
307///
308static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within,
309 Scope *CurScope) {
310 while (1) {
311 assert(CurScope && "CurScope not nested within 'Within'?");
312
313 // Check this scope for the decl.
314 if (CurScope->isDeclScope(D)) return true;
315
316 if (CurScope == Within) return false;
317 CurScope = CurScope->getParent();
318 }
319}
Reid Spencer5f016e22007-07-11 17:01:13 +0000320
Steve Naroff08d92e42007-09-15 18:49:24 +0000321/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000322/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000323/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000324Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 IdentifierInfo &II,
326 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000327 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000328 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000329
330 // If this reference is in an Objective-C method, then ivar lookup happens as
331 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000332 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000333 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000334 // There are two cases to handle here. 1) scoped lookup could have failed,
335 // in which case we should look for an ivar. 2) scoped lookup could have
336 // found a decl, but that decl is outside the current method (i.e. a global
337 // variable). In these two cases, we do a lookup for an ivar with this
338 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000339 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000340 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000341 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000342 // FIXME: This should use a new expr for a direct reference, don't turn
343 // this into Self->ivar, just return a BareIVarExpr or something.
344 IdentifierInfo &II = Context.Idents.get("self");
345 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
346 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
347 static_cast<Expr*>(SelfExpr.Val), true, true);
348 }
349 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000350 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000351 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000352 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000353 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000354 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000355 }
Chris Lattner8a934232008-03-31 00:36:02 +0000356 }
357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 if (D == 0) {
359 // Otherwise, this could be an implicitly declared function reference (legal
360 // in C90, extension in C99).
361 if (HasTrailingLParen &&
Chris Lattner8a934232008-03-31 00:36:02 +0000362 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 D = ImplicitlyDefineFunction(Loc, II, S);
364 else {
365 // If this name wasn't predeclared and if this is not a function call,
366 // diagnose the problem.
367 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
368 }
369 }
Chris Lattner8a934232008-03-31 00:36:02 +0000370
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000371 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
372 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
373 if (MD->isStatic())
374 // "invalid use of member 'x' in static member function"
375 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
376 FD->getName());
377 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
378 // "invalid use of nonstatic data member 'x'"
379 return Diag(Loc, diag::err_invalid_non_static_member_use,
380 FD->getName());
381
382 if (FD->isInvalidDecl())
383 return true;
384
385 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
386 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
387 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
388 true, FD, Loc, FD->getType());
389 }
390
391 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
392 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 if (isa<TypedefDecl>(D))
394 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000395 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000396 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000397 if (isa<NamespaceDecl>(D))
398 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000399
Steve Naroffdd972f22008-09-05 22:11:13 +0000400 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
401 ValueDecl *VD = cast<ValueDecl>(D);
402
403 // check if referencing an identifier with __attribute__((deprecated)).
404 if (VD->getAttr<DeprecatedAttr>())
405 Diag(Loc, diag::warn_deprecated, VD->getName());
406
407 // Only create DeclRefExpr's for valid Decl's.
408 if (VD->isInvalidDecl())
409 return true;
410
411 // If this reference is not in a block or if the referenced variable is
412 // within the block, create a normal DeclRefExpr.
413 //
414 // FIXME: This will create BlockDeclRefExprs for global variables,
415 // function references, enums constants, etc which is suboptimal :) and breaks
416 // things like "integer constant expression" tests.
417 //
418 if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S))
419 return new DeclRefExpr(VD, VD->getType(), Loc);
420
421 // If we are in a block and the variable is outside the current block,
422 // bind the variable reference with a BlockDeclRefExpr.
423
424 // If the variable is in the byref set, bind it directly, otherwise it will be
425 // bound by-copy, thus we make it const within the closure.
426 if (!CurBlock->ByRefVars.count(VD))
427 VD->getType().addConst();
428
429 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000430}
431
Chris Lattnerd9f69102008-08-10 01:53:14 +0000432Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000433 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000434 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000435
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000437 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000438 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
439 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
440 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000442
443 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000444 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000445 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000446
Chris Lattnerfa28b302008-01-12 08:14:25 +0000447 // Pre-defined identifiers are of type char[x], where x is the length of the
448 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000449 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000450 if (getCurFunctionDecl())
451 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000452 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000453 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000454
Chris Lattner8f978d52008-01-12 19:32:28 +0000455 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000456 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000457 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000458 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000459}
460
Steve Narofff69936d2007-09-16 03:34:24 +0000461Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 llvm::SmallString<16> CharBuffer;
463 CharBuffer.resize(Tok.getLength());
464 const char *ThisTokBegin = &CharBuffer[0];
465 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
466
467 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
468 Tok.getLocation(), PP);
469 if (Literal.hadError())
470 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000471
472 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
473
Chris Lattnerc250aae2008-06-07 22:35:38 +0000474 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
475 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000476}
477
Steve Narofff69936d2007-09-16 03:34:24 +0000478Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 // fast path for a single digit (which is quite common). A single digit
480 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
481 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000482 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000483
Chris Lattner98be4942008-03-05 18:54:05 +0000484 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000485 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 Context.IntTy,
487 Tok.getLocation()));
488 }
489 llvm::SmallString<512> IntegerBuffer;
490 IntegerBuffer.resize(Tok.getLength());
491 const char *ThisTokBegin = &IntegerBuffer[0];
492
493 // Get the spelling of the token, which eliminates trigraphs, etc.
494 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
495 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
496 Tok.getLocation(), PP);
497 if (Literal.hadError)
498 return ExprResult(true);
499
Chris Lattner5d661452007-08-26 03:42:43 +0000500 Expr *Res;
501
502 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000503 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000504 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000505 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000506 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000507 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000508 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000509 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000510
511 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
512
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000513 // isExact will be set by GetFloatValue().
514 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000515 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000516 Ty, Tok.getLocation());
517
Chris Lattner5d661452007-08-26 03:42:43 +0000518 } else if (!Literal.isIntegerLiteral()) {
519 return ExprResult(true);
520 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000521 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522
Neil Boothb9449512007-08-29 22:00:19 +0000523 // long long is a C99 feature.
524 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000525 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000526 Diag(Tok.getLocation(), diag::ext_longlong);
527
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000529 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000530
531 if (Literal.GetIntegerValue(ResultVal)) {
532 // If this value didn't fit into uintmax_t, warn and force to ull.
533 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000534 Ty = Context.UnsignedLongLongTy;
535 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000536 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 } else {
538 // If this value fits into a ULL, try to figure out what else it fits into
539 // according to the rules of C99 6.4.4.1p5.
540
541 // Octal, Hexadecimal, and integers with a U suffix are allowed to
542 // be an unsigned int.
543 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
544
545 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000546 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000547 if (!Literal.isLong && !Literal.isLongLong) {
548 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000549 unsigned IntSize = Context.Target.getIntWidth();
550
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 // Does it fit in a unsigned int?
552 if (ResultVal.isIntN(IntSize)) {
553 // Does it fit in a signed int?
554 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000555 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000557 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000558 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 }
561
562 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000563 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000564 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000565
566 // Does it fit in a unsigned long?
567 if (ResultVal.isIntN(LongSize)) {
568 // Does it fit in a signed long?
569 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000570 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000572 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000573 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 }
576
577 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000578 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000579 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000580
581 // Does it fit in a unsigned long long?
582 if (ResultVal.isIntN(LongLongSize)) {
583 // Does it fit in a signed long long?
584 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000585 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000587 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000588 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 }
590 }
591
592 // If we still couldn't decide a type, we probably have something that
593 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000594 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000596 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000597 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000599
600 if (ResultVal.getBitWidth() != Width)
601 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 }
603
Chris Lattnerf0467b32008-04-02 04:24:33 +0000604 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 }
Chris Lattner5d661452007-08-26 03:42:43 +0000606
607 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
608 if (Literal.isImaginary)
609 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
610
611 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000612}
613
Steve Narofff69936d2007-09-16 03:34:24 +0000614Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000616 Expr *E = (Expr *)Val;
617 assert((E != 0) && "ActOnParenExpr() missing expr");
618 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000619}
620
621/// The UsualUnaryConversions() function is *not* called by this routine.
622/// See C99 6.3.2.1p[2-4] for more details.
623QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000624 SourceLocation OpLoc,
625 const SourceRange &ExprRange,
626 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 // C99 6.5.3.4p1:
628 if (isa<FunctionType>(exprType) && isSizeof)
629 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000630 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000632 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
633 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 else if (exprType->isIncompleteType()) {
635 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
636 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000637 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 return QualType(); // error
639 }
640 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
641 return Context.getSizeType();
642}
643
644Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000645ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 SourceLocation LPLoc, TypeTy *Ty,
647 SourceLocation RPLoc) {
648 // If error parsing type, ignore.
649 if (Ty == 0) return true;
650
651 // Verify that this is a valid expression.
652 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
653
Chris Lattnerbb280a42008-07-25 21:45:37 +0000654 QualType resultType =
655 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000656
657 if (resultType.isNull())
658 return true;
659 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
660}
661
Chris Lattner5d794252007-08-24 21:41:10 +0000662QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000663 DefaultFunctionArrayConversion(V);
664
Chris Lattnercc26ed72007-08-26 05:39:26 +0000665 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000666 if (const ComplexType *CT = V->getType()->getAsComplexType())
667 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000668
669 // Otherwise they pass through real integer and floating point types here.
670 if (V->getType()->isArithmeticType())
671 return V->getType();
672
673 // Reject anything else.
674 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
675 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000676}
677
678
Reid Spencer5f016e22007-07-11 17:01:13 +0000679
Steve Narofff69936d2007-09-16 03:34:24 +0000680Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 tok::TokenKind Kind,
682 ExprTy *Input) {
683 UnaryOperator::Opcode Opc;
684 switch (Kind) {
685 default: assert(0 && "Unknown unary op!");
686 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
687 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
688 }
689 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
690 if (result.isNull())
691 return true;
692 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
693}
694
695Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000696ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000698 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000699
700 // Perform default conversions.
701 DefaultFunctionArrayConversion(LHSExp);
702 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000703
Chris Lattner12d9ff62007-07-16 00:14:47 +0000704 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000705
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000707 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 // in the subscript position. As a result, we need to derive the array base
709 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000710 Expr *BaseExpr, *IndexExpr;
711 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000712 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000713 BaseExpr = LHSExp;
714 IndexExpr = RHSExp;
715 // FIXME: need to deal with const...
716 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000717 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000718 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000719 BaseExpr = RHSExp;
720 IndexExpr = LHSExp;
721 // FIXME: need to deal with const...
722 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000723 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
724 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000725 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000726
727 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000728 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
729 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000730 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000731 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000732 // FIXME: need to deal with const...
733 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000735 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
736 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 }
738 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000739 if (!IndexExpr->getType()->isIntegerType())
740 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
741 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000742
Chris Lattner12d9ff62007-07-16 00:14:47 +0000743 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
744 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000745 // void (*)(int)) and pointers to incomplete types. Functions are not
746 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000747 if (!ResultType->isObjectType())
748 return Diag(BaseExpr->getLocStart(),
749 diag::err_typecheck_subscript_not_object,
750 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
751
752 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000753}
754
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000755QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000756CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000757 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000758 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000759
760 // This flag determines whether or not the component is to be treated as a
761 // special name, or a regular GLSL-style component access.
762 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000763
764 // The vector accessor can't exceed the number of elements.
765 const char *compStr = CompName.getName();
766 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000767 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000768 baseType.getAsString(), SourceRange(CompLoc));
769 return QualType();
770 }
Nate Begeman8a997642008-05-09 06:41:27 +0000771
772 // Check that we've found one of the special components, or that the component
773 // names must come from the same set.
774 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
775 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
776 SpecialComponent = true;
777 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000778 do
779 compStr++;
780 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
781 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
782 do
783 compStr++;
784 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
785 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
786 do
787 compStr++;
788 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
789 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000790
Nate Begeman8a997642008-05-09 06:41:27 +0000791 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000792 // We didn't get to the end of the string. This means the component names
793 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000794 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000795 std::string(compStr,compStr+1), SourceRange(CompLoc));
796 return QualType();
797 }
798 // Each component accessor can't exceed the vector type.
799 compStr = CompName.getName();
800 while (*compStr) {
801 if (vecType->isAccessorWithinNumElements(*compStr))
802 compStr++;
803 else
804 break;
805 }
Nate Begeman8a997642008-05-09 06:41:27 +0000806 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000807 // We didn't get to the end of the string. This means a component accessor
808 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000809 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000810 baseType.getAsString(), SourceRange(CompLoc));
811 return QualType();
812 }
Nate Begeman8a997642008-05-09 06:41:27 +0000813
814 // If we have a special component name, verify that the current vector length
815 // is an even number, since all special component names return exactly half
816 // the elements.
817 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
818 return QualType();
819 }
820
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000821 // The component accessor looks fine - now we need to compute the actual type.
822 // The vector type is implied by the component accessor. For example,
823 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000824 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
825 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
826 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000827 if (CompSize == 1)
828 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000829
Nate Begeman213541a2008-04-18 23:10:10 +0000830 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000831 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000832 // diagostics look bad. We want extended vector types to appear built-in.
833 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
834 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
835 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000836 }
837 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000838}
839
Daniel Dunbar2307d312008-09-03 01:05:41 +0000840/// constructSetterName - Return the setter name for the given
841/// identifier, i.e. "set" + Name where the initial character of Name
842/// has been capitalized.
843// FIXME: Merge with same routine in Parser. But where should this
844// live?
845static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
846 const IdentifierInfo *Name) {
847 unsigned N = Name->getLength();
848 char *SelectorName = new char[3 + N];
849 memcpy(SelectorName, "set", 3);
850 memcpy(&SelectorName[3], Name->getName(), N);
851 SelectorName[3] = toupper(SelectorName[3]);
852
853 IdentifierInfo *Setter =
854 &Idents.get(SelectorName, &SelectorName[3 + N]);
855 delete[] SelectorName;
856 return Setter;
857}
858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000860ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000861 tok::TokenKind OpKind, SourceLocation MemberLoc,
862 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000863 Expr *BaseExpr = static_cast<Expr *>(Base);
864 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000865
866 // Perform default conversions.
867 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000868
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000869 QualType BaseType = BaseExpr->getType();
870 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000871
Chris Lattner68a057b2008-07-21 04:36:39 +0000872 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
873 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000875 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000876 BaseType = PT->getPointeeType();
877 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000878 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
879 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000881
Chris Lattner68a057b2008-07-21 04:36:39 +0000882 // Handle field access to simple records. This also handles access to fields
883 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000884 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000885 RecordDecl *RDecl = RTy->getDecl();
886 if (RTy->isIncompleteType())
887 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
888 BaseExpr->getSourceRange());
889 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000890 FieldDecl *MemberDecl = RDecl->getMember(&Member);
891 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000892 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
893 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000894
895 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000896 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000897 QualType MemberType = MemberDecl->getType();
898 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000899 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000900 MemberType = MemberType.getQualifiedType(combinedQualifiers);
901
Chris Lattner68a057b2008-07-21 04:36:39 +0000902 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000903 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000904 }
905
Chris Lattnera38e6b12008-07-21 04:59:05 +0000906 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
907 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000908 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
909 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000910 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000911 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000912 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000913 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000914 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000915 }
916
Chris Lattnera38e6b12008-07-21 04:59:05 +0000917 // Handle Objective-C property access, which is "Obj.property" where Obj is a
918 // pointer to a (potentially qualified) interface type.
919 const PointerType *PTy;
920 const ObjCInterfaceType *IFTy;
921 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
922 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
923 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000924
Daniel Dunbar2307d312008-09-03 01:05:41 +0000925 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000926 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
927 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
928
Daniel Dunbar2307d312008-09-03 01:05:41 +0000929 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000930 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
931 E = IFTy->qual_end(); I != E; ++I)
932 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
933 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000934
935 // If that failed, look for an "implicit" property by seeing if the nullary
936 // selector is implemented.
937
938 // FIXME: The logic for looking up nullary and unary selectors should be
939 // shared with the code in ActOnInstanceMessage.
940
941 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
942 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
943
944 // If this reference is in an @implementation, check for 'private' methods.
945 if (!Getter)
946 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
947 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
948 if (ObjCImplementationDecl *ImpDecl =
949 ObjCImplementations[ClassDecl->getIdentifier()])
950 Getter = ImpDecl->getInstanceMethod(Sel);
951
952 if (Getter) {
953 // If we found a getter then this may be a valid dot-reference, we
954 // need to also look for the matching setter.
955 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
956 &Member);
957 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
958 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
959
960 if (!Setter) {
961 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
962 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
963 if (ObjCImplementationDecl *ImpDecl =
964 ObjCImplementations[ClassDecl->getIdentifier()])
965 Setter = ImpDecl->getInstanceMethod(SetterSel);
966 }
967
968 // FIXME: There are some issues here. First, we are not
969 // diagnosing accesses to read-only properties because we do not
970 // know if this is a getter or setter yet. Second, we are
971 // checking that the type of the setter matches the type we
972 // expect.
973 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
974 MemberLoc, BaseExpr);
975 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000976 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000977
978 // Handle 'field access' to vectors, such as 'V.xx'.
979 if (BaseType->isExtVectorType() && OpKind == tok::period) {
980 // Component access limited to variables (reject vec4.rg.g).
981 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
982 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +0000983 return Diag(MemberLoc, diag::err_ext_vector_component_access,
984 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000985 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
986 if (ret.isNull())
987 return true;
988 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
989 }
990
Chris Lattner2a01b722008-07-21 05:35:34 +0000991 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
992 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000993}
994
Steve Narofff69936d2007-09-16 03:34:24 +0000995/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000996/// This provides the location of the left/right parens and a list of comma
997/// locations.
998Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000999ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001000 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001002 Expr *Fn = static_cast<Expr *>(fn);
1003 Expr **Args = reinterpret_cast<Expr**>(args);
1004 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001005 FunctionDecl *FDecl = NULL;
Chris Lattner04421082008-04-08 04:40:51 +00001006
1007 // Promote the function operand.
1008 UsualUnaryConversions(Fn);
1009
1010 // If we're directly calling a function, get the declaration for
1011 // that function.
1012 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1013 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1014 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1015
Chris Lattner925e60d2007-12-28 05:29:59 +00001016 // Make the call expr early, before semantic checks. This guarantees cleanup
1017 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001018 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001019 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001020 const FunctionType *FuncT;
1021 if (!Fn->getType()->isBlockPointerType()) {
1022 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1023 // have type pointer to function".
1024 const PointerType *PT = Fn->getType()->getAsPointerType();
1025 if (PT == 0)
1026 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1027 Fn->getSourceRange());
1028 FuncT = PT->getPointeeType()->getAsFunctionType();
1029 } else { // This is a block call.
1030 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1031 getAsFunctionType();
1032 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001033 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001034 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1035 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001036
1037 // We know the result type of the call, set it.
1038 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001039
Chris Lattner925e60d2007-12-28 05:29:59 +00001040 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001041 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1042 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001043 unsigned NumArgsInProto = Proto->getNumArgs();
1044 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001045
Chris Lattner04421082008-04-08 04:40:51 +00001046 // If too few arguments are available (and we don't have default
1047 // arguments for the remaining parameters), don't make the call.
1048 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001049 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001050 // Use default arguments for missing arguments
1051 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001052 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001053 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001054 return Diag(RParenLoc,
1055 !Fn->getType()->isBlockPointerType()
1056 ? diag::err_typecheck_call_too_few_args
1057 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001058 Fn->getSourceRange());
1059 }
1060
Chris Lattner925e60d2007-12-28 05:29:59 +00001061 // If too many are passed and not variadic, error on the extras and drop
1062 // them.
1063 if (NumArgs > NumArgsInProto) {
1064 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001065 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001066 !Fn->getType()->isBlockPointerType()
1067 ? diag::err_typecheck_call_too_many_args
1068 : diag::err_typecheck_block_too_many_args,
1069 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001070 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001071 Args[NumArgs-1]->getLocEnd()));
1072 // This deletes the extra arguments.
1073 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 }
1075 NumArgsToCheck = NumArgsInProto;
1076 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001077
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001079 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001080 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001081
1082 Expr *Arg;
1083 if (i < NumArgs)
1084 Arg = Args[i];
1085 else
1086 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001087 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001088
Chris Lattner925e60d2007-12-28 05:29:59 +00001089 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001090 AssignConvertType ConvTy =
1091 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001092 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001093
Chris Lattner5cf216b2008-01-04 18:04:52 +00001094 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1095 ArgType, Arg, "passing"))
1096 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001098
1099 // If this is a variadic call, handle args passed through "...".
1100 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001101 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001102 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1103 Expr *Arg = Args[i];
1104 DefaultArgumentPromotion(Arg);
1105 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001106 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001107 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001108 } else {
1109 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1110
Steve Naroffb291ab62007-08-28 23:30:39 +00001111 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001112 for (unsigned i = 0; i != NumArgs; i++) {
1113 Expr *Arg = Args[i];
1114 DefaultArgumentPromotion(Arg);
1115 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001116 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001118
Chris Lattner59907c42007-08-10 20:18:51 +00001119 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001120 if (FDecl)
1121 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001122
Chris Lattner925e60d2007-12-28 05:29:59 +00001123 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001124}
1125
1126Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001127ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001128 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001129 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001130 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001131 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001132 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001133 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001134
Eli Friedman6223c222008-05-20 05:22:08 +00001135 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001136 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001137 return Diag(LParenLoc,
1138 diag::err_variable_object_no_init,
1139 SourceRange(LParenLoc,
1140 literalExpr->getSourceRange().getEnd()));
1141 } else if (literalType->isIncompleteType()) {
1142 return Diag(LParenLoc,
1143 diag::err_typecheck_decl_incomplete_type,
1144 literalType.getAsString(),
1145 SourceRange(LParenLoc,
1146 literalExpr->getSourceRange().getEnd()));
1147 }
1148
Steve Naroffd0091aa2008-01-10 22:15:12 +00001149 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001150 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001151
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001152 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001153 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001154 if (CheckForConstantInitializer(literalExpr, literalType))
1155 return true;
1156 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001157 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001158}
1159
1160Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001161ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001162 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001163 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001164
Steve Naroff08d92e42007-09-15 18:49:24 +00001165 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001166 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001167
Chris Lattnerf0467b32008-04-02 04:24:33 +00001168 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1169 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1170 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001171}
1172
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001173/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001174bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001175 UsualUnaryConversions(castExpr);
1176
1177 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1178 // type needs to be scalar.
1179 if (castType->isVoidType()) {
1180 // Cast to void allows any expr type.
1181 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1182 // GCC struct/union extension: allow cast to self.
1183 if (Context.getCanonicalType(castType) !=
1184 Context.getCanonicalType(castExpr->getType()) ||
1185 (!castType->isStructureType() && !castType->isUnionType())) {
1186 // Reject any other conversions to non-scalar types.
1187 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1188 castType.getAsString(), castExpr->getSourceRange());
1189 }
1190
1191 // accept this, but emit an ext-warn.
1192 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1193 castType.getAsString(), castExpr->getSourceRange());
1194 } else if (!castExpr->getType()->isScalarType() &&
1195 !castExpr->getType()->isVectorType()) {
1196 return Diag(castExpr->getLocStart(),
1197 diag::err_typecheck_expect_scalar_operand,
1198 castExpr->getType().getAsString(),castExpr->getSourceRange());
1199 } else if (castExpr->getType()->isVectorType()) {
1200 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1201 return true;
1202 } else if (castType->isVectorType()) {
1203 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1204 return true;
1205 }
1206 return false;
1207}
1208
Chris Lattnerfe23e212007-12-20 00:44:32 +00001209bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001210 assert(VectorTy->isVectorType() && "Not a vector type!");
1211
1212 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001213 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001214 return Diag(R.getBegin(),
1215 Ty->isVectorType() ?
1216 diag::err_invalid_conversion_between_vectors :
1217 diag::err_invalid_conversion_between_vector_and_integer,
1218 VectorTy.getAsString().c_str(),
1219 Ty.getAsString().c_str(), R);
1220 } else
1221 return Diag(R.getBegin(),
1222 diag::err_invalid_conversion_between_vector_and_scalar,
1223 VectorTy.getAsString().c_str(),
1224 Ty.getAsString().c_str(), R);
1225
1226 return false;
1227}
1228
Steve Naroff4aa88f82007-07-19 01:06:55 +00001229Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001230ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001232 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001233
1234 Expr *castExpr = static_cast<Expr*>(Op);
1235 QualType castType = QualType::getFromOpaquePtr(Ty);
1236
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001237 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1238 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001239 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240}
1241
Chris Lattnera21ddb32007-11-26 01:40:58 +00001242/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1243/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001244inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001245 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001246 UsualUnaryConversions(cond);
1247 UsualUnaryConversions(lex);
1248 UsualUnaryConversions(rex);
1249 QualType condT = cond->getType();
1250 QualType lexT = lex->getType();
1251 QualType rexT = rex->getType();
1252
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001254 if (!condT->isScalarType()) { // C99 6.5.15p2
1255 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1256 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 return QualType();
1258 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001259
1260 // Now check the two expressions.
1261
1262 // If both operands have arithmetic type, do the usual arithmetic conversions
1263 // to find a common type: C99 6.5.15p3,5.
1264 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001265 UsualArithmeticConversions(lex, rex);
1266 return lex->getType();
1267 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001268
1269 // If both operands are the same structure or union type, the result is that
1270 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001271 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001272 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001273 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001274 // "If both the operands have structure or union type, the result has
1275 // that type." This implies that CV qualifiers are dropped.
1276 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001278
1279 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001280 // The following || allows only one side to be void (a GCC-ism).
1281 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001282 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001283 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1284 rex->getSourceRange());
1285 if (!rexT->isVoidType())
1286 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001287 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001288 ImpCastExprToType(lex, Context.VoidTy);
1289 ImpCastExprToType(rex, Context.VoidTy);
1290 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001291 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001292 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1293 // the type of the other operand."
1294 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001295 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001296 return lexT;
1297 }
1298 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001299 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001300 return rexT;
1301 }
Daniel Dunbar40727a42008-09-03 17:53:25 +00001302 // Allow any Objective-C types to devolve to id type.
1303 // FIXME: This seems to match gcc behavior, although that is very
1304 // arguably incorrect. For example, (xxx ? (id<P>) : (id<P>)) has
1305 // type id, which seems broken.
1306 if (Context.isObjCObjectPointerType(lexT) &&
1307 Context.isObjCObjectPointerType(rexT)) {
1308 // FIXME: This is not the correct composite type. This only
1309 // happens to work because id can more or less be used anywhere,
1310 // however this may change the type of method sends.
1311 // FIXME: gcc adds some type-checking of the arguments and emits
1312 // (confusing) incompatible comparison warnings in some
1313 // cases. Investigate.
1314 QualType compositeType = Context.getObjCIdType();
1315 ImpCastExprToType(lex, compositeType);
1316 ImpCastExprToType(rex, compositeType);
1317 return compositeType;
1318 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001319 // Handle the case where both operands are pointers before we handle null
1320 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001321 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1322 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1323 // get the "pointed to" types
1324 QualType lhptee = LHSPT->getPointeeType();
1325 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001327 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1328 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001329 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001330 // Figure out necessary qualifiers (C99 6.5.15p6)
1331 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001332 QualType destType = Context.getPointerType(destPointee);
1333 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1334 ImpCastExprToType(rex, destType); // promote to void*
1335 return destType;
1336 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001337 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001338 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001339 QualType destType = Context.getPointerType(destPointee);
1340 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1341 ImpCastExprToType(rex, destType); // promote to void*
1342 return destType;
1343 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001344
Steve Naroffec0550f2007-10-15 20:41:53 +00001345 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1346 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001347 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001348 lexT.getAsString(), rexT.getAsString(),
1349 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara56f7462008-08-26 00:41:39 +00001350 // In this situation, assume a conservative type; in general
1351 // we assume void* type. No especially good reason, but this
1352 // is what gcc does, and we do have to pick to get a
1353 // consistent AST. However, if either type is an Objective-C
1354 // object type then use id.
1355 QualType incompatTy;
1356 if (Context.isObjCObjectPointerType(lexT) ||
1357 Context.isObjCObjectPointerType(rexT)) {
1358 incompatTy = Context.getObjCIdType();
1359 } else {
1360 incompatTy = Context.getPointerType(Context.VoidTy);
1361 }
1362 ImpCastExprToType(lex, incompatTy);
1363 ImpCastExprToType(rex, incompatTy);
1364 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001365 }
1366 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001367 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1368 // differently qualified versions of compatible types, the result type is
1369 // a pointer to an appropriately qualified version of the *composite*
1370 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001371 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001372 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001373 QualType compositeType = lexT;
1374 ImpCastExprToType(lex, compositeType);
1375 ImpCastExprToType(rex, compositeType);
1376 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 }
1378 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001379 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001381 lexT.getAsString(), rexT.getAsString(),
1382 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 return QualType();
1384}
1385
Steve Narofff69936d2007-09-16 03:34:24 +00001386/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001387/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001388Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 SourceLocation ColonLoc,
1390 ExprTy *Cond, ExprTy *LHS,
1391 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001392 Expr *CondExpr = (Expr *) Cond;
1393 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001394
1395 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1396 // was the condition.
1397 bool isLHSNull = LHSExpr == 0;
1398 if (isLHSNull)
1399 LHSExpr = CondExpr;
1400
Chris Lattner26824902007-07-16 21:39:03 +00001401 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1402 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 if (result.isNull())
1404 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001405 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1406 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001407}
1408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409
1410// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1411// being closely modeled after the C99 spec:-). The odd characteristic of this
1412// routine is it effectively iqnores the qualifiers on the top level pointee.
1413// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1414// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001415Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001416Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1417 QualType lhptee, rhptee;
1418
1419 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001420 lhptee = lhsType->getAsPointerType()->getPointeeType();
1421 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001422
1423 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001424 lhptee = Context.getCanonicalType(lhptee);
1425 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426
Chris Lattner5cf216b2008-01-04 18:04:52 +00001427 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001428
1429 // C99 6.5.16.1p1: This following citation is common to constraints
1430 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1431 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001432 // FIXME: Handle ASQualType
1433 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1434 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001435 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001436
1437 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1438 // incomplete type and the other is a pointer to a qualified or unqualified
1439 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001440 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001441 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001442 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001443
1444 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001445 assert(rhptee->isFunctionType());
1446 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001447 }
1448
1449 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001450 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001451 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001452
1453 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001454 assert(lhptee->isFunctionType());
1455 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001456 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001457
1458 // Check for ObjC interfaces
1459 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1460 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1461 if (LHSIface && RHSIface &&
1462 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1463 return ConvTy;
1464
1465 // ID acts sort of like void* for ObjC interfaces
1466 if (LHSIface && Context.isObjCIdType(rhptee))
1467 return ConvTy;
1468 if (RHSIface && Context.isObjCIdType(lhptee))
1469 return ConvTy;
1470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1472 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001473 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1474 rhptee.getUnqualifiedType()))
1475 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001476 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001477}
1478
Steve Naroff1c7d0672008-09-04 15:10:53 +00001479/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1480/// block pointer types are compatible or whether a block and normal pointer
1481/// are compatible. It is more restrict than comparing two function pointer
1482// types.
1483Sema::AssignConvertType
1484Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1485 QualType rhsType) {
1486 QualType lhptee, rhptee;
1487
1488 // get the "pointed to" type (ignoring qualifiers at the top level)
1489 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1490 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1491
1492 // make sure we operate on the canonical type
1493 lhptee = Context.getCanonicalType(lhptee);
1494 rhptee = Context.getCanonicalType(rhptee);
1495
1496 AssignConvertType ConvTy = Compatible;
1497
1498 // For blocks we enforce that qualifiers are identical.
1499 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1500 ConvTy = CompatiblePointerDiscardsQualifiers;
1501
1502 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1503 return IncompatibleBlockPointer;
1504 return ConvTy;
1505}
1506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1508/// has code to accommodate several GCC extensions when type checking
1509/// pointers. Here are some objectionable examples that GCC considers warnings:
1510///
1511/// int a, *pint;
1512/// short *pshort;
1513/// struct foo *pfoo;
1514///
1515/// pint = pshort; // warning: assignment from incompatible pointer type
1516/// a = pint; // warning: assignment makes integer from pointer without a cast
1517/// pint = a; // warning: assignment makes pointer from integer without a cast
1518/// pint = pfoo; // warning: assignment from incompatible pointer type
1519///
1520/// As a result, the code for dealing with pointers is more complex than the
1521/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001522///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001523Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001524Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001525 // Get canonical types. We're not formatting these types, just comparing
1526 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001527 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1528 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001529
1530 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001531 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001532
Anders Carlsson793680e2007-10-12 23:56:29 +00001533 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001534 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001535 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001536 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001537 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001538
Chris Lattnereca7be62008-04-07 05:30:13 +00001539 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1540 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001541 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001542 // Relax integer conversions like we do for pointers below.
1543 if (rhsType->isIntegerType())
1544 return IntToPointer;
1545 if (lhsType->isIntegerType())
1546 return PointerToInt;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001547 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001548 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001549
Nate Begemanbe2341d2008-07-14 18:02:46 +00001550 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001551 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001552 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1553 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001554 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001555
Nate Begemanbe2341d2008-07-14 18:02:46 +00001556 // If we are allowing lax vector conversions, and LHS and RHS are both
1557 // vectors, the total size only needs to be the same. This is a bitcast;
1558 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001559 if (getLangOptions().LaxVectorConversions &&
1560 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001561 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1562 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001563 }
1564 return Incompatible;
1565 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001566
Chris Lattnere8b3e962008-01-04 23:32:24 +00001567 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001569
Chris Lattner78eca282008-04-07 06:49:41 +00001570 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001572 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001573
Chris Lattner78eca282008-04-07 06:49:41 +00001574 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001576
Steve Naroffdd972f22008-09-05 22:11:13 +00001577 if (rhsType->getAsBlockPointerType())
1578 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001579 return BlockVoidPointer;
1580
1581 return Incompatible;
1582 }
1583
1584 if (isa<BlockPointerType>(lhsType)) {
1585 if (rhsType->isIntegerType())
1586 return IntToPointer;
1587
1588 if (rhsType->isBlockPointerType())
1589 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1590
1591 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1592 if (RHSPT->getPointeeType()->isVoidType())
1593 return BlockVoidPointer;
1594 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001595 return Incompatible;
1596 }
1597
Chris Lattner78eca282008-04-07 06:49:41 +00001598 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001600 if (lhsType == Context.BoolTy)
1601 return Compatible;
1602
1603 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001604 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001605
Chris Lattner78eca282008-04-07 06:49:41 +00001606 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001608
1609 if (isa<BlockPointerType>(lhsType) &&
1610 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1611 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001612 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001613 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001614
Chris Lattnerfc144e22008-01-04 23:18:45 +00001615 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001616 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 }
1619 return Incompatible;
1620}
1621
Chris Lattner5cf216b2008-01-04 18:04:52 +00001622Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001623Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001624 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1625 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001626 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1627 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001628 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001629 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001630 return Compatible;
1631 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001632
1633 // We don't allow conversion of non-null-pointer constants to integers.
1634 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1635 return IntToBlockPointer;
1636
Chris Lattner943140e2007-10-16 02:55:40 +00001637 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001638 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001639 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001640 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001641 //
1642 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1643 // are better understood.
1644 if (!lhsType->isReferenceType())
1645 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001646
Chris Lattner5cf216b2008-01-04 18:04:52 +00001647 Sema::AssignConvertType result =
1648 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001649
1650 // C99 6.5.16.1p2: The value of the right operand is converted to the
1651 // type of the assignment expression.
1652 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001653 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001654 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001655}
1656
Chris Lattner5cf216b2008-01-04 18:04:52 +00001657Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001658Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1659 return CheckAssignmentConstraints(lhsType, rhsType);
1660}
1661
Chris Lattnerca5eede2007-12-12 05:47:28 +00001662QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 Diag(loc, diag::err_typecheck_invalid_operands,
1664 lex->getType().getAsString(), rex->getType().getAsString(),
1665 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001666 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001667}
1668
Steve Naroff49b45262007-07-13 16:58:59 +00001669inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1670 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001671 // For conversion purposes, we ignore any qualifiers.
1672 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001673 QualType lhsType =
1674 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1675 QualType rhsType =
1676 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001677
Nate Begemanbe2341d2008-07-14 18:02:46 +00001678 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001679 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001681
Nate Begemanbe2341d2008-07-14 18:02:46 +00001682 // Handle the case of a vector & extvector type of the same size and element
1683 // type. It would be nice if we only had one vector type someday.
1684 if (getLangOptions().LaxVectorConversions)
1685 if (const VectorType *LV = lhsType->getAsVectorType())
1686 if (const VectorType *RV = rhsType->getAsVectorType())
1687 if (LV->getElementType() == RV->getElementType() &&
1688 LV->getNumElements() == RV->getNumElements())
1689 return lhsType->isExtVectorType() ? lhsType : rhsType;
1690
1691 // If the lhs is an extended vector and the rhs is a scalar of the same type
1692 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001693 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001694 QualType eltType = V->getElementType();
1695
1696 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1697 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1698 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001699 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001700 return lhsType;
1701 }
1702 }
1703
Nate Begemanbe2341d2008-07-14 18:02:46 +00001704 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001705 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001706 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001707 QualType eltType = V->getElementType();
1708
1709 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1710 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1711 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001712 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001713 return rhsType;
1714 }
1715 }
1716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // You cannot convert between vector values of different size.
1718 Diag(loc, diag::err_typecheck_vector_not_convertable,
1719 lex->getType().getAsString(), rex->getType().getAsString(),
1720 lex->getSourceRange(), rex->getSourceRange());
1721 return QualType();
1722}
1723
1724inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001725 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001726{
Steve Naroff90045e82007-07-13 23:32:42 +00001727 QualType lhsType = lex->getType(), rhsType = rex->getType();
1728
1729 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001731
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001732 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001733
Steve Naroffa4332e22007-07-17 00:58:39 +00001734 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001735 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001736 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001737}
1738
1739inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001740 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001741{
Steve Naroff90045e82007-07-13 23:32:42 +00001742 QualType lhsType = lex->getType(), rhsType = rex->getType();
1743
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001744 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001745
Steve Naroffa4332e22007-07-17 00:58:39 +00001746 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001747 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001748 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001749}
1750
1751inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001752 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001753{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001754 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001755 return CheckVectorOperands(loc, lex, rex);
1756
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001757 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001758
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001760 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001761 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001762
Eli Friedmand72d16e2008-05-18 18:08:51 +00001763 // Put any potential pointer into PExp
1764 Expr* PExp = lex, *IExp = rex;
1765 if (IExp->getType()->isPointerType())
1766 std::swap(PExp, IExp);
1767
1768 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1769 if (IExp->getType()->isIntegerType()) {
1770 // Check for arithmetic on pointers to incomplete types
1771 if (!PTy->getPointeeType()->isObjectType()) {
1772 if (PTy->getPointeeType()->isVoidType()) {
1773 Diag(loc, diag::ext_gnu_void_ptr,
1774 lex->getSourceRange(), rex->getSourceRange());
1775 } else {
1776 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1777 lex->getType().getAsString(), lex->getSourceRange());
1778 return QualType();
1779 }
1780 }
1781 return PExp->getType();
1782 }
1783 }
1784
Chris Lattnerca5eede2007-12-12 05:47:28 +00001785 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786}
1787
Chris Lattnereca7be62008-04-07 05:30:13 +00001788// C99 6.5.6
1789QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1790 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001791 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001793
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001794 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001795
Chris Lattner6e4ab612007-12-09 21:53:25 +00001796 // Enforce type constraints: C99 6.5.6p3.
1797
1798 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001799 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001800 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001801
1802 // Either ptr - int or ptr - ptr.
1803 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001804 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001805
Chris Lattner6e4ab612007-12-09 21:53:25 +00001806 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001807 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001808 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001809 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001810 Diag(loc, diag::ext_gnu_void_ptr,
1811 lex->getSourceRange(), rex->getSourceRange());
1812 } else {
1813 Diag(loc, diag::err_typecheck_sub_ptr_object,
1814 lex->getType().getAsString(), lex->getSourceRange());
1815 return QualType();
1816 }
1817 }
1818
1819 // The result type of a pointer-int computation is the pointer type.
1820 if (rex->getType()->isIntegerType())
1821 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001822
Chris Lattner6e4ab612007-12-09 21:53:25 +00001823 // Handle pointer-pointer subtractions.
1824 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001825 QualType rpointee = RHSPTy->getPointeeType();
1826
Chris Lattner6e4ab612007-12-09 21:53:25 +00001827 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001828 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001829 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001830 if (rpointee->isVoidType()) {
1831 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001832 Diag(loc, diag::ext_gnu_void_ptr,
1833 lex->getSourceRange(), rex->getSourceRange());
1834 } else {
1835 Diag(loc, diag::err_typecheck_sub_ptr_object,
1836 rex->getType().getAsString(), rex->getSourceRange());
1837 return QualType();
1838 }
1839 }
1840
1841 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001842 if (!Context.typesAreCompatible(
1843 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1844 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001845 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1846 lex->getType().getAsString(), rex->getType().getAsString(),
1847 lex->getSourceRange(), rex->getSourceRange());
1848 return QualType();
1849 }
1850
1851 return Context.getPointerDiffType();
1852 }
1853 }
1854
Chris Lattnerca5eede2007-12-12 05:47:28 +00001855 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001856}
1857
Chris Lattnereca7be62008-04-07 05:30:13 +00001858// C99 6.5.7
1859QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1860 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00001861 // C99 6.5.7p2: Each of the operands shall have integer type.
1862 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1863 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001864
Chris Lattnerca5eede2007-12-12 05:47:28 +00001865 // Shifts don't perform usual arithmetic conversions, they just do integer
1866 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001867 if (!isCompAssign)
1868 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001869 UsualUnaryConversions(rex);
1870
1871 // "The type of the result is that of the promoted left operand."
1872 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001873}
1874
Eli Friedman3d815e72008-08-22 00:56:42 +00001875static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1876 ASTContext& Context) {
1877 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1878 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1879 // ID acts sort of like void* for ObjC interfaces
1880 if (LHSIface && Context.isObjCIdType(RHS))
1881 return true;
1882 if (RHSIface && Context.isObjCIdType(LHS))
1883 return true;
1884 if (!LHSIface || !RHSIface)
1885 return false;
1886 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1887 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1888}
1889
Chris Lattnereca7be62008-04-07 05:30:13 +00001890// C99 6.5.8
1891QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1892 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001893 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1894 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1895
Chris Lattnera5937dd2007-08-26 01:18:55 +00001896 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001897 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1898 UsualArithmeticConversions(lex, rex);
1899 else {
1900 UsualUnaryConversions(lex);
1901 UsualUnaryConversions(rex);
1902 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001903 QualType lType = lex->getType();
1904 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001905
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001906 // For non-floating point types, check for self-comparisons of the form
1907 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1908 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001909 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001910 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1911 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001912 if (DRL->getDecl() == DRR->getDecl())
1913 Diag(loc, diag::warn_selfcomparison);
1914 }
1915
Chris Lattnera5937dd2007-08-26 01:18:55 +00001916 if (isRelational) {
1917 if (lType->isRealType() && rType->isRealType())
1918 return Context.IntTy;
1919 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001920 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001921 if (lType->isFloatingType()) {
1922 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001923 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001924 }
1925
Chris Lattnera5937dd2007-08-26 01:18:55 +00001926 if (lType->isArithmeticType() && rType->isArithmeticType())
1927 return Context.IntTy;
1928 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001929
Chris Lattnerd28f8152007-08-26 01:10:14 +00001930 bool LHSIsNull = lex->isNullPointerConstant(Context);
1931 bool RHSIsNull = rex->isNullPointerConstant(Context);
1932
Chris Lattnera5937dd2007-08-26 01:18:55 +00001933 // All of the following pointer related warnings are GCC extensions, except
1934 // when handling null pointer constants. One day, we can consider making them
1935 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001936 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001937 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00001938 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00001939 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00001940 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00001941
Steve Naroff66296cb2007-11-13 14:57:38 +00001942 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001943 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1944 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00001945 RCanPointeeTy.getUnqualifiedType()) &&
1946 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001947 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1948 lType.getAsString(), rType.getAsString(),
1949 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00001951 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001952 return Context.IntTy;
1953 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001954 // Handle block pointer types.
1955 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
1956 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
1957 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
1958
1959 if (!LHSIsNull && !RHSIsNull &&
1960 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
1961 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
1962 lType.getAsString(), rType.getAsString(),
1963 lex->getSourceRange(), rex->getSourceRange());
1964 }
1965 ImpCastExprToType(rex, lType); // promote the pointer to pointer
1966 return Context.IntTy;
1967 }
1968
Steve Naroff20373222008-06-03 14:04:54 +00001969 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1970 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1971 ImpCastExprToType(rex, lType);
1972 return Context.IntTy;
1973 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001974 }
Steve Naroff20373222008-06-03 14:04:54 +00001975 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1976 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001977 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001978 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1979 lType.getAsString(), rType.getAsString(),
1980 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001981 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001982 return Context.IntTy;
1983 }
Steve Naroff20373222008-06-03 14:04:54 +00001984 if (lType->isIntegerType() &&
1985 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001986 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001987 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1988 lType.getAsString(), rType.getAsString(),
1989 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001990 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001991 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 }
Steve Naroff39218df2008-09-04 16:56:14 +00001993 // Handle block pointers.
1994 if (lType->isBlockPointerType() && rType->isIntegerType()) {
1995 if (!RHSIsNull)
1996 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1997 lType.getAsString(), rType.getAsString(),
1998 lex->getSourceRange(), rex->getSourceRange());
1999 ImpCastExprToType(rex, lType); // promote the integer to pointer
2000 return Context.IntTy;
2001 }
2002 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2003 if (!LHSIsNull)
2004 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2005 lType.getAsString(), rType.getAsString(),
2006 lex->getSourceRange(), rex->getSourceRange());
2007 ImpCastExprToType(lex, rType); // promote the integer to pointer
2008 return Context.IntTy;
2009 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002010 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002011}
2012
Nate Begemanbe2341d2008-07-14 18:02:46 +00002013/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2014/// operates on extended vector types. Instead of producing an IntTy result,
2015/// like a scalar comparison, a vector comparison produces a vector of integer
2016/// types.
2017QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2018 SourceLocation loc,
2019 bool isRelational) {
2020 // Check to make sure we're operating on vectors of the same type and width,
2021 // Allowing one side to be a scalar of element type.
2022 QualType vType = CheckVectorOperands(loc, lex, rex);
2023 if (vType.isNull())
2024 return vType;
2025
2026 QualType lType = lex->getType();
2027 QualType rType = rex->getType();
2028
2029 // For non-floating point types, check for self-comparisons of the form
2030 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2031 // often indicate logic errors in the program.
2032 if (!lType->isFloatingType()) {
2033 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2034 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2035 if (DRL->getDecl() == DRR->getDecl())
2036 Diag(loc, diag::warn_selfcomparison);
2037 }
2038
2039 // Check for comparisons of floating point operands using != and ==.
2040 if (!isRelational && lType->isFloatingType()) {
2041 assert (rType->isFloatingType());
2042 CheckFloatComparison(loc,lex,rex);
2043 }
2044
2045 // Return the type for the comparison, which is the same as vector type for
2046 // integer vectors, or an integer type of identical size and number of
2047 // elements for floating point vectors.
2048 if (lType->isIntegerType())
2049 return lType;
2050
2051 const VectorType *VTy = lType->getAsVectorType();
2052
2053 // FIXME: need to deal with non-32b int / non-64b long long
2054 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2055 if (TypeSize == 32) {
2056 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2057 }
2058 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2059 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2060}
2061
Reid Spencer5f016e22007-07-11 17:01:13 +00002062inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002063 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002064{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002065 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002067
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002068 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069
Steve Naroffa4332e22007-07-17 00:58:39 +00002070 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002071 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002072 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002073}
2074
2075inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002076 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002077{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002078 UsualUnaryConversions(lex);
2079 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002080
Eli Friedman5773a6c2008-05-13 20:16:47 +00002081 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002083 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002084}
2085
2086inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002087 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002088{
2089 QualType lhsType = lex->getType();
2090 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002091 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002092
2093 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002094 case Expr::MLV_Valid:
2095 break;
2096 case Expr::MLV_ConstQualified:
2097 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2098 return QualType();
2099 case Expr::MLV_ArrayType:
2100 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2101 lhsType.getAsString(), lex->getSourceRange());
2102 return QualType();
2103 case Expr::MLV_NotObjectType:
2104 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2105 lhsType.getAsString(), lex->getSourceRange());
2106 return QualType();
2107 case Expr::MLV_InvalidExpression:
2108 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2109 lex->getSourceRange());
2110 return QualType();
2111 case Expr::MLV_IncompleteType:
2112 case Expr::MLV_IncompleteVoidType:
2113 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2114 lhsType.getAsString(), lex->getSourceRange());
2115 return QualType();
2116 case Expr::MLV_DuplicateVectorComponents:
2117 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2118 lex->getSourceRange());
2119 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002121
Chris Lattner5cf216b2008-01-04 18:04:52 +00002122 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002123 if (compoundType.isNull()) {
2124 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002125 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002126
2127 // If the RHS is a unary plus or minus, check to see if they = and + are
2128 // right next to each other. If so, the user may have typo'd "x =+ 4"
2129 // instead of "x += 4".
2130 Expr *RHSCheck = rex;
2131 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2132 RHSCheck = ICE->getSubExpr();
2133 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2134 if ((UO->getOpcode() == UnaryOperator::Plus ||
2135 UO->getOpcode() == UnaryOperator::Minus) &&
2136 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2137 // Only if the two operators are exactly adjacent.
2138 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2139 Diag(loc, diag::warn_not_compound_assign,
2140 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2141 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2142 }
2143 } else {
2144 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002145 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002146 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002147
2148 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2149 rex, "assigning"))
2150 return QualType();
2151
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 // C99 6.5.16p3: The type of an assignment expression is the type of the
2153 // left operand unless the left operand has qualified type, in which case
2154 // it is the unqualified version of the type of the left operand.
2155 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2156 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002157 // C++ 5.17p1: the type of the assignment expression is that of its left
2158 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002159 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002160}
2161
2162inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002163 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002164
2165 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2166 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002167 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002168}
2169
Steve Naroff49b45262007-07-13 16:58:59 +00002170/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2171/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002172QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002173 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002174 assert(!resType.isNull() && "no type for increment/decrement expression");
2175
Steve Naroff084f9ed2007-08-24 17:20:07 +00002176 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002177 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002178 if (pt->getPointeeType()->isVoidType()) {
2179 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2180 } else if (!pt->getPointeeType()->isObjectType()) {
2181 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2183 resType.getAsString(), op->getSourceRange());
2184 return QualType();
2185 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002186 } else if (!resType->isRealType()) {
2187 if (resType->isComplexType())
2188 // C99 does not support ++/-- on complex types.
2189 Diag(OpLoc, diag::ext_integer_increment_complex,
2190 resType.getAsString(), op->getSourceRange());
2191 else {
2192 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2193 resType.getAsString(), op->getSourceRange());
2194 return QualType();
2195 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002197 // At this point, we know we have a real, complex or pointer type.
2198 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002199 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 if (mlval != Expr::MLV_Valid) {
2201 // FIXME: emit a more precise diagnostic...
2202 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2203 op->getSourceRange());
2204 return QualType();
2205 }
2206 return resType;
2207}
2208
Anders Carlsson369dee42008-02-01 07:15:58 +00002209/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002210/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002211/// where the declaration is needed for type checking. We only need to
2212/// handle cases when the expression references a function designator
2213/// or is an lvalue. Here are some examples:
2214/// - &(x) => x
2215/// - &*****f => f for f a function designator.
2216/// - &s.xx => s
2217/// - &s.zz[1].yy -> s, if zz is an array
2218/// - *(x + 1) -> x, if x is an array
2219/// - &"123"[2] -> 0
2220/// - & __real__ x -> x
Chris Lattnerf0467b32008-04-02 04:24:33 +00002221static ValueDecl *getPrimaryDecl(Expr *E) {
2222 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002224 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002226 // Fields cannot be declared with a 'register' storage class.
2227 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002228 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002229 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002230 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002231 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002232 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002233
Chris Lattnerf0467b32008-04-02 04:24:33 +00002234 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002235 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002236 return 0;
2237 else
2238 return VD;
2239 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002240 case Stmt::UnaryOperatorClass: {
2241 UnaryOperator *UO = cast<UnaryOperator>(E);
2242
2243 switch(UO->getOpcode()) {
2244 case UnaryOperator::Deref: {
2245 // *(X + 1) refers to X if X is not a pointer.
2246 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2247 if (!VD || VD->getType()->isPointerType())
2248 return 0;
2249 return VD;
2250 }
2251 case UnaryOperator::Real:
2252 case UnaryOperator::Imag:
2253 case UnaryOperator::Extension:
2254 return getPrimaryDecl(UO->getSubExpr());
2255 default:
2256 return 0;
2257 }
2258 }
2259 case Stmt::BinaryOperatorClass: {
2260 BinaryOperator *BO = cast<BinaryOperator>(E);
2261
2262 // Handle cases involving pointer arithmetic. The result of an
2263 // Assign or AddAssign is not an lvalue so they can be ignored.
2264
2265 // (x + n) or (n + x) => x
2266 if (BO->getOpcode() == BinaryOperator::Add) {
2267 if (BO->getLHS()->getType()->isPointerType()) {
2268 return getPrimaryDecl(BO->getLHS());
2269 } else if (BO->getRHS()->getType()->isPointerType()) {
2270 return getPrimaryDecl(BO->getRHS());
2271 }
2272 }
2273
2274 return 0;
2275 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002276 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002277 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002278 case Stmt::ImplicitCastExprClass:
2279 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002280 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 default:
2282 return 0;
2283 }
2284}
2285
2286/// CheckAddressOfOperand - The operand of & must be either a function
2287/// designator or an lvalue designating an object. If it is an lvalue, the
2288/// object cannot be declared with storage class register or be a bit field.
2289/// Note: The usual conversions are *not* applied to the operand of the &
2290/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2291QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002292 if (getLangOptions().C99) {
2293 // Implement C99-only parts of addressof rules.
2294 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2295 if (uOp->getOpcode() == UnaryOperator::Deref)
2296 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2297 // (assuming the deref expression is valid).
2298 return uOp->getSubExpr()->getType();
2299 }
2300 // Technically, there should be a check for array subscript
2301 // expressions here, but the result of one is always an lvalue anyway.
2302 }
Anders Carlsson369dee42008-02-01 07:15:58 +00002303 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002304 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002305
2306 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002307 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2308 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2310 op->getSourceRange());
2311 return QualType();
2312 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002313 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2314 if (MemExpr->getMemberDecl()->isBitField()) {
2315 Diag(OpLoc, diag::err_typecheck_address_of,
2316 std::string("bit-field"), op->getSourceRange());
2317 return QualType();
2318 }
2319 // Check for Apple extension for accessing vector components.
2320 } else if (isa<ArraySubscriptExpr>(op) &&
2321 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2322 Diag(OpLoc, diag::err_typecheck_address_of,
2323 std::string("vector"), op->getSourceRange());
2324 return QualType();
2325 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 // We have an lvalue with a decl. Make sure the decl is not declared
2327 // with the register storage-class specifier.
2328 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2329 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002330 Diag(OpLoc, diag::err_typecheck_address_of,
2331 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 return QualType();
2333 }
2334 } else
2335 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002337
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 // If the operand has type "type", the result has type "pointer to type".
2339 return Context.getPointerType(op->getType());
2340}
2341
2342QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002343 UsualUnaryConversions(op);
2344 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002345
Chris Lattnerbefee482007-07-31 16:53:04 +00002346 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002347 // Note that per both C89 and C99, this is always legal, even
2348 // if ptype is an incomplete type or void.
2349 // It would be possible to warn about dereferencing a
2350 // void pointer, but it's completely well-defined,
2351 // and such a warning is unlikely to catch any mistakes.
2352 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 }
2354 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2355 qType.getAsString(), op->getSourceRange());
2356 return QualType();
2357}
2358
2359static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2360 tok::TokenKind Kind) {
2361 BinaryOperator::Opcode Opc;
2362 switch (Kind) {
2363 default: assert(0 && "Unknown binop!");
2364 case tok::star: Opc = BinaryOperator::Mul; break;
2365 case tok::slash: Opc = BinaryOperator::Div; break;
2366 case tok::percent: Opc = BinaryOperator::Rem; break;
2367 case tok::plus: Opc = BinaryOperator::Add; break;
2368 case tok::minus: Opc = BinaryOperator::Sub; break;
2369 case tok::lessless: Opc = BinaryOperator::Shl; break;
2370 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2371 case tok::lessequal: Opc = BinaryOperator::LE; break;
2372 case tok::less: Opc = BinaryOperator::LT; break;
2373 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2374 case tok::greater: Opc = BinaryOperator::GT; break;
2375 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2376 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2377 case tok::amp: Opc = BinaryOperator::And; break;
2378 case tok::caret: Opc = BinaryOperator::Xor; break;
2379 case tok::pipe: Opc = BinaryOperator::Or; break;
2380 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2381 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2382 case tok::equal: Opc = BinaryOperator::Assign; break;
2383 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2384 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2385 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2386 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2387 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2388 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2389 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2390 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2391 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2392 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2393 case tok::comma: Opc = BinaryOperator::Comma; break;
2394 }
2395 return Opc;
2396}
2397
2398static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2399 tok::TokenKind Kind) {
2400 UnaryOperator::Opcode Opc;
2401 switch (Kind) {
2402 default: assert(0 && "Unknown unary op!");
2403 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2404 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2405 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2406 case tok::star: Opc = UnaryOperator::Deref; break;
2407 case tok::plus: Opc = UnaryOperator::Plus; break;
2408 case tok::minus: Opc = UnaryOperator::Minus; break;
2409 case tok::tilde: Opc = UnaryOperator::Not; break;
2410 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2411 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2412 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2413 case tok::kw___real: Opc = UnaryOperator::Real; break;
2414 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2415 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2416 }
2417 return Opc;
2418}
2419
2420// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002421Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 ExprTy *LHS, ExprTy *RHS) {
2423 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2424 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2425
Steve Narofff69936d2007-09-16 03:34:24 +00002426 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2427 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002428
2429 QualType ResultTy; // Result type of the binary operator.
2430 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2431
2432 switch (Opc) {
2433 default:
2434 assert(0 && "Unknown binary expr!");
2435 case BinaryOperator::Assign:
2436 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2437 break;
2438 case BinaryOperator::Mul:
2439 case BinaryOperator::Div:
2440 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2441 break;
2442 case BinaryOperator::Rem:
2443 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2444 break;
2445 case BinaryOperator::Add:
2446 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2447 break;
2448 case BinaryOperator::Sub:
2449 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2450 break;
2451 case BinaryOperator::Shl:
2452 case BinaryOperator::Shr:
2453 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2454 break;
2455 case BinaryOperator::LE:
2456 case BinaryOperator::LT:
2457 case BinaryOperator::GE:
2458 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002459 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002460 break;
2461 case BinaryOperator::EQ:
2462 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002463 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 break;
2465 case BinaryOperator::And:
2466 case BinaryOperator::Xor:
2467 case BinaryOperator::Or:
2468 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2469 break;
2470 case BinaryOperator::LAnd:
2471 case BinaryOperator::LOr:
2472 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2473 break;
2474 case BinaryOperator::MulAssign:
2475 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002476 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 if (!CompTy.isNull())
2478 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2479 break;
2480 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002481 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 if (!CompTy.isNull())
2483 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2484 break;
2485 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002486 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 if (!CompTy.isNull())
2488 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2489 break;
2490 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002491 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 if (!CompTy.isNull())
2493 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2494 break;
2495 case BinaryOperator::ShlAssign:
2496 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002497 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 if (!CompTy.isNull())
2499 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2500 break;
2501 case BinaryOperator::AndAssign:
2502 case BinaryOperator::XorAssign:
2503 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002504 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 if (!CompTy.isNull())
2506 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2507 break;
2508 case BinaryOperator::Comma:
2509 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2510 break;
2511 }
2512 if (ResultTy.isNull())
2513 return true;
2514 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002515 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002517 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002518}
2519
2520// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002521Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002522 ExprTy *input) {
2523 Expr *Input = (Expr*)input;
2524 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2525 QualType resultType;
2526 switch (Opc) {
2527 default:
2528 assert(0 && "Unimplemented unary expr!");
2529 case UnaryOperator::PreInc:
2530 case UnaryOperator::PreDec:
2531 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2532 break;
2533 case UnaryOperator::AddrOf:
2534 resultType = CheckAddressOfOperand(Input, OpLoc);
2535 break;
2536 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002537 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 resultType = CheckIndirectionOperand(Input, OpLoc);
2539 break;
2540 case UnaryOperator::Plus:
2541 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002542 UsualUnaryConversions(Input);
2543 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002544 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2545 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2546 resultType.getAsString());
2547 break;
2548 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002549 UsualUnaryConversions(Input);
2550 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002551 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2552 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2553 // C99 does not support '~' for complex conjugation.
2554 Diag(OpLoc, diag::ext_integer_complement_complex,
2555 resultType.getAsString(), Input->getSourceRange());
2556 else if (!resultType->isIntegerType())
2557 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2558 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 break;
2560 case UnaryOperator::LNot: // logical negation
2561 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002562 DefaultFunctionArrayConversion(Input);
2563 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2565 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2566 resultType.getAsString());
2567 // LNot always has type int. C99 6.5.3.3p5.
2568 resultType = Context.IntTy;
2569 break;
2570 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002571 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2572 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 break;
2574 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002575 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2576 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002578 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002579 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002580 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002581 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 resultType = Input->getType();
2584 break;
2585 }
2586 if (resultType.isNull())
2587 return true;
2588 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2589}
2590
Steve Naroff1b273c42007-09-16 14:56:35 +00002591/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2592Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 SourceLocation LabLoc,
2594 IdentifierInfo *LabelII) {
2595 // Look up the record for this label identifier.
2596 LabelStmt *&LabelDecl = LabelMap[LabelII];
2597
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002598 // If we haven't seen this label yet, create a forward reference. It
2599 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 if (LabelDecl == 0)
2601 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2602
2603 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002604 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2605 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002606}
2607
Steve Naroff1b273c42007-09-16 14:56:35 +00002608Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002609 SourceLocation RPLoc) { // "({..})"
2610 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2611 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2612 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2613
2614 // FIXME: there are a variety of strange constraints to enforce here, for
2615 // example, it is not possible to goto into a stmt expression apparently.
2616 // More semantic analysis is needed.
2617
2618 // FIXME: the last statement in the compount stmt has its value used. We
2619 // should not warn about it being unused.
2620
2621 // If there are sub stmts in the compound stmt, take the type of the last one
2622 // as the type of the stmtexpr.
2623 QualType Ty = Context.VoidTy;
2624
Chris Lattner611b2ec2008-07-26 19:51:01 +00002625 if (!Compound->body_empty()) {
2626 Stmt *LastStmt = Compound->body_back();
2627 // If LastStmt is a label, skip down through into the body.
2628 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2629 LastStmt = Label->getSubStmt();
2630
2631 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002632 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002633 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002634
2635 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2636}
Steve Naroffd34e9152007-08-01 22:05:33 +00002637
Steve Naroff1b273c42007-09-16 14:56:35 +00002638Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002639 SourceLocation TypeLoc,
2640 TypeTy *argty,
2641 OffsetOfComponent *CompPtr,
2642 unsigned NumComponents,
2643 SourceLocation RPLoc) {
2644 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2645 assert(!ArgTy.isNull() && "Missing type argument!");
2646
2647 // We must have at least one component that refers to the type, and the first
2648 // one is known to be a field designator. Verify that the ArgTy represents
2649 // a struct/union/class.
2650 if (!ArgTy->isRecordType())
2651 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2652
2653 // Otherwise, create a compound literal expression as the base, and
2654 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002655 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002656
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002657 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2658 // GCC extension, diagnose them.
2659 if (NumComponents != 1)
2660 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2661 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2662
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002663 for (unsigned i = 0; i != NumComponents; ++i) {
2664 const OffsetOfComponent &OC = CompPtr[i];
2665 if (OC.isBrackets) {
2666 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002667 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002668 if (!AT) {
2669 delete Res;
2670 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2671 Res->getType().getAsString());
2672 }
2673
Chris Lattner704fe352007-08-30 17:59:59 +00002674 // FIXME: C++: Verify that operator[] isn't overloaded.
2675
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002676 // C99 6.5.2.1p1
2677 Expr *Idx = static_cast<Expr*>(OC.U.E);
2678 if (!Idx->getType()->isIntegerType())
2679 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2680 Idx->getSourceRange());
2681
2682 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2683 continue;
2684 }
2685
2686 const RecordType *RC = Res->getType()->getAsRecordType();
2687 if (!RC) {
2688 delete Res;
2689 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2690 Res->getType().getAsString());
2691 }
2692
2693 // Get the decl corresponding to this.
2694 RecordDecl *RD = RC->getDecl();
2695 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2696 if (!MemberDecl)
2697 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2698 OC.U.IdentInfo->getName(),
2699 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002700
2701 // FIXME: C++: Verify that MemberDecl isn't a static field.
2702 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002703 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2704 // matter here.
2705 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002706 }
2707
2708 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2709 BuiltinLoc);
2710}
2711
2712
Steve Naroff1b273c42007-09-16 14:56:35 +00002713Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002714 TypeTy *arg1, TypeTy *arg2,
2715 SourceLocation RPLoc) {
2716 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2717 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2718
2719 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2720
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002721 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002722}
2723
Steve Naroff1b273c42007-09-16 14:56:35 +00002724Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002725 ExprTy *expr1, ExprTy *expr2,
2726 SourceLocation RPLoc) {
2727 Expr *CondExpr = static_cast<Expr*>(cond);
2728 Expr *LHSExpr = static_cast<Expr*>(expr1);
2729 Expr *RHSExpr = static_cast<Expr*>(expr2);
2730
2731 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2732
2733 // The conditional expression is required to be a constant expression.
2734 llvm::APSInt condEval(32);
2735 SourceLocation ExpLoc;
2736 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2737 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2738 CondExpr->getSourceRange());
2739
2740 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2741 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2742 RHSExpr->getType();
2743 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2744}
2745
Steve Naroff4eb206b2008-09-03 18:15:37 +00002746//===----------------------------------------------------------------------===//
2747// Clang Extensions.
2748//===----------------------------------------------------------------------===//
2749
2750/// ActOnBlockStart - This callback is invoked when a block literal is started.
2751void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2752 Declarator &ParamInfo) {
2753 // Analyze block parameters.
2754 BlockSemaInfo *BSI = new BlockSemaInfo();
2755
2756 // Add BSI to CurBlock.
2757 BSI->PrevBlockInfo = CurBlock;
2758 CurBlock = BSI;
2759
2760 BSI->ReturnType = 0;
2761 BSI->TheScope = BlockScope;
2762
2763 // Analyze arguments to block.
2764 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2765 "Not a function declarator!");
2766 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2767
2768 BSI->hasPrototype = FTI.hasPrototype;
2769 BSI->isVariadic = true;
2770
2771 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2772 // no arguments, not a function that takes a single void argument.
2773 if (FTI.hasPrototype &&
2774 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2775 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2776 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2777 // empty arg list, don't push any params.
2778 BSI->isVariadic = false;
2779 } else if (FTI.hasPrototype) {
2780 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2781 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2782 BSI->isVariadic = FTI.isVariadic;
2783 }
2784}
2785
2786/// ActOnBlockError - If there is an error parsing a block, this callback
2787/// is invoked to pop the information about the block from the action impl.
2788void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2789 // Ensure that CurBlock is deleted.
2790 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2791
2792 // Pop off CurBlock, handle nested blocks.
2793 CurBlock = CurBlock->PrevBlockInfo;
2794
2795 // FIXME: Delete the ParmVarDecl objects as well???
2796
2797}
2798
2799/// ActOnBlockStmtExpr - This is called when the body of a block statement
2800/// literal was successfully completed. ^(int x){...}
2801Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2802 Scope *CurScope) {
2803 // Ensure that CurBlock is deleted.
2804 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2805 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2806
2807 // Pop off CurBlock, handle nested blocks.
2808 CurBlock = CurBlock->PrevBlockInfo;
2809
2810 QualType RetTy = Context.VoidTy;
2811 if (BSI->ReturnType)
2812 RetTy = QualType(BSI->ReturnType, 0);
2813
2814 llvm::SmallVector<QualType, 8> ArgTypes;
2815 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2816 ArgTypes.push_back(BSI->Params[i]->getType());
2817
2818 QualType BlockTy;
2819 if (!BSI->hasPrototype)
2820 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2821 else
2822 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2823 BSI->isVariadic);
2824
2825 BlockTy = Context.getBlockPointerType(BlockTy);
2826 return new BlockStmtExpr(CaretLoc, BlockTy,
2827 &BSI->Params[0], BSI->Params.size(), Body.take());
2828}
2829
2830/// ActOnBlockExprExpr - This is called when the body of a block
2831/// expression literal was successfully completed. ^(int x)[foo bar: x]
2832Sema::ExprResult Sema::ActOnBlockExprExpr(SourceLocation CaretLoc, ExprTy *body,
2833 Scope *CurScope) {
2834 // Ensure that CurBlock is deleted.
2835 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2836 llvm::OwningPtr<Expr> Body(static_cast<Expr*>(body));
2837
2838 // Pop off CurBlock, handle nested blocks.
2839 CurBlock = CurBlock->PrevBlockInfo;
2840
2841 if (BSI->ReturnType) {
2842 Diag(CaretLoc, diag::err_return_in_block_expression);
2843 return true;
2844 }
2845
2846 QualType RetTy = Body->getType();
2847
2848 llvm::SmallVector<QualType, 8> ArgTypes;
2849 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2850 ArgTypes.push_back(BSI->Params[i]->getType());
2851
2852 QualType BlockTy;
2853 if (!BSI->hasPrototype)
2854 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2855 else
2856 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2857 BSI->isVariadic);
2858
2859 BlockTy = Context.getBlockPointerType(BlockTy);
2860 return new BlockExprExpr(CaretLoc, BlockTy,
2861 &BSI->Params[0], BSI->Params.size(), Body.take());
2862}
2863
Nate Begeman67295d02008-01-30 20:50:20 +00002864/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00002865/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00002866/// The number of arguments has already been validated to match the number of
2867/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002868static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2869 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00002870 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00002871 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002872 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2873 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00002874
2875 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00002876 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00002877 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002878 return true;
2879}
2880
2881Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2882 SourceLocation *CommaLocs,
2883 SourceLocation BuiltinLoc,
2884 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002885 // __builtin_overload requires at least 2 arguments
2886 if (NumArgs < 2)
2887 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2888 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00002889
Nate Begemane2ce1d92008-01-17 17:46:27 +00002890 // The first argument is required to be a constant expression. It tells us
2891 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002892 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00002893 Expr *NParamsExpr = Args[0];
2894 llvm::APSInt constEval(32);
2895 SourceLocation ExpLoc;
2896 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2897 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2898 NParamsExpr->getSourceRange());
2899
2900 // Verify that the number of parameters is > 0
2901 unsigned NumParams = constEval.getZExtValue();
2902 if (NumParams == 0)
2903 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2904 NParamsExpr->getSourceRange());
2905 // Verify that we have at least 1 + NumParams arguments to the builtin.
2906 if ((NumParams + 1) > NumArgs)
2907 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2908 SourceRange(BuiltinLoc, RParenLoc));
2909
2910 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00002911 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002912 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002913 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2914 // UsualUnaryConversions will convert the function DeclRefExpr into a
2915 // pointer to function.
2916 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00002917 const FunctionTypeProto *FnType = 0;
2918 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2919 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00002920
2921 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2922 // parameters, and the number of parameters must match the value passed to
2923 // the builtin.
2924 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00002925 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2926 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00002927
2928 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00002929 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00002930 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002931 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002932 if (OE)
2933 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2934 OE->getFn()->getSourceRange());
2935 // Remember our match, and continue processing the remaining arguments
2936 // to catch any errors.
2937 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2938 BuiltinLoc, RParenLoc);
2939 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002940 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00002941 // Return the newly created OverloadExpr node, if we succeded in matching
2942 // exactly one of the candidate functions.
2943 if (OE)
2944 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002945
2946 // If we didn't find a matching function Expr in the __builtin_overload list
2947 // the return an error.
2948 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00002949 for (unsigned i = 0; i != NumParams; ++i) {
2950 if (i != 0) typeNames += ", ";
2951 typeNames += Args[i+1]->getType().getAsString();
2952 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002953
2954 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2955 SourceRange(BuiltinLoc, RParenLoc));
2956}
2957
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002958Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2959 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002960 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002961 Expr *E = static_cast<Expr*>(expr);
2962 QualType T = QualType::getFromOpaquePtr(type);
2963
2964 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00002965
2966 // Get the va_list type
2967 QualType VaListType = Context.getBuiltinVaListType();
2968 // Deal with implicit array decay; for example, on x86-64,
2969 // va_list is an array, but it's supposed to decay to
2970 // a pointer for va_arg.
2971 if (VaListType->isArrayType())
2972 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00002973 // Make sure the input expression also decays appropriately.
2974 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00002975
2976 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002977 return Diag(E->getLocStart(),
2978 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2979 E->getType().getAsString(),
2980 E->getSourceRange());
2981
2982 // FIXME: Warn if a non-POD type is passed in.
2983
2984 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2985}
2986
Chris Lattner5cf216b2008-01-04 18:04:52 +00002987bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2988 SourceLocation Loc,
2989 QualType DstType, QualType SrcType,
2990 Expr *SrcExpr, const char *Flavor) {
2991 // Decode the result (notice that AST's are still created for extensions).
2992 bool isInvalid = false;
2993 unsigned DiagKind;
2994 switch (ConvTy) {
2995 default: assert(0 && "Unknown conversion type");
2996 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002997 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00002998 DiagKind = diag::ext_typecheck_convert_pointer_int;
2999 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003000 case IntToPointer:
3001 DiagKind = diag::ext_typecheck_convert_int_pointer;
3002 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003003 case IncompatiblePointer:
3004 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3005 break;
3006 case FunctionVoidPointer:
3007 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3008 break;
3009 case CompatiblePointerDiscardsQualifiers:
3010 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3011 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003012 case IntToBlockPointer:
3013 DiagKind = diag::err_int_to_block_pointer;
3014 break;
3015 case IncompatibleBlockPointer:
3016 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
3017 break;
3018 case BlockVoidPointer:
3019 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3020 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003021 case Incompatible:
3022 DiagKind = diag::err_typecheck_convert_incompatible;
3023 isInvalid = true;
3024 break;
3025 }
3026
3027 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3028 SrcExpr->getSourceRange());
3029 return isInvalid;
3030}