blob: fe9a13e4643e039da2e7295f9baa7ba7397e1ec0 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Chris Lattnere7a2e912008-07-25 21:10:04 +000026//===----------------------------------------------------------------------===//
27// Standard Promotions and Conversions
28//===----------------------------------------------------------------------===//
29
Chris Lattnere7a2e912008-07-25 21:10:04 +000030/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
31void Sema::DefaultFunctionArrayConversion(Expr *&E) {
32 QualType Ty = E->getType();
33 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
34
35 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
36 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
37 Ty = E->getType();
38 }
39 if (Ty->isFunctionType())
40 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000041 else if (Ty->isArrayType()) {
42 // In C90 mode, arrays only promote to pointers if the array expression is
43 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
44 // type 'array of type' is converted to an expression that has type 'pointer
45 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
46 // that has type 'array of type' ...". The relevant change is "an lvalue"
47 // (C90) to "an expression" (C99).
Chris Lattner28be73f2008-07-26 21:30:36 +000048 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000049 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
50 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000051}
52
53/// UsualUnaryConversions - Performs various conversions that are common to most
54/// operators (C99 6.3). The conversions of array and function types are
55/// sometimes surpressed. For example, the array->pointer conversion doesn't
56/// apply if the array is an argument to the sizeof or address (&) operators.
57/// In these instances, this routine should *not* be called.
58Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
59 QualType Ty = Expr->getType();
60 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
61
62 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
63 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
64 Ty = Expr->getType();
65 }
66 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67 ImpCastExprToType(Expr, Context.IntTy);
68 else
69 DefaultFunctionArrayConversion(Expr);
70
71 return Expr;
72}
73
Chris Lattner05faf172008-07-25 22:25:12 +000074/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78 QualType Ty = Expr->getType();
79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81 // If this is a 'float' (CVR qualified or typedef) promote to double.
82 if (const BuiltinType *BT = Ty->getAsBuiltinType())
83 if (BT->getKind() == BuiltinType::Float)
84 return ImpCastExprToType(Expr, Context.DoubleTy);
85
86 UsualUnaryConversions(Expr);
87}
88
Chris Lattnere7a2e912008-07-25 21:10:04 +000089/// UsualArithmeticConversions - Performs various conversions that are common to
90/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
91/// routine returns the first non-arithmetic type found. The client is
92/// responsible for emitting appropriate error diagnostics.
93/// FIXME: verify the conversion rules for "complex int" are consistent with
94/// GCC.
95QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
96 bool isCompAssign) {
97 if (!isCompAssign) {
98 UsualUnaryConversions(lhsExpr);
99 UsualUnaryConversions(rhsExpr);
100 }
101 // For conversion purposes, we ignore any qualifiers.
102 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000103 QualType lhs =
104 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
105 QualType rhs =
106 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000107
108 // If both types are identical, no conversion is needed.
109 if (lhs == rhs)
110 return lhs;
111
112 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
113 // The caller can deal with this (e.g. pointer + int).
114 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
115 return lhs;
116
117 // At this point, we have two different arithmetic types.
118
119 // Handle complex types first (C99 6.3.1.8p1).
120 if (lhs->isComplexType() || rhs->isComplexType()) {
121 // if we have an integer operand, the result is the complex type.
122 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
123 // convert the rhs to the lhs complex type.
124 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
125 return lhs;
126 }
127 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
128 // convert the lhs to the rhs complex type.
129 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
130 return rhs;
131 }
132 // This handles complex/complex, complex/float, or float/complex.
133 // When both operands are complex, the shorter operand is converted to the
134 // type of the longer, and that is the type of the result. This corresponds
135 // to what is done when combining two real floating-point operands.
136 // The fun begins when size promotion occur across type domains.
137 // From H&S 6.3.4: When one operand is complex and the other is a real
138 // floating-point type, the less precise type is converted, within it's
139 // real or complex domain, to the precision of the other type. For example,
140 // when combining a "long double" with a "double _Complex", the
141 // "double _Complex" is promoted to "long double _Complex".
142 int result = Context.getFloatingTypeOrder(lhs, rhs);
143
144 if (result > 0) { // The left side is bigger, convert rhs.
145 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
146 if (!isCompAssign)
147 ImpCastExprToType(rhsExpr, rhs);
148 } else if (result < 0) { // The right side is bigger, convert lhs.
149 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
150 if (!isCompAssign)
151 ImpCastExprToType(lhsExpr, lhs);
152 }
153 // At this point, lhs and rhs have the same rank/size. Now, make sure the
154 // domains match. This is a requirement for our implementation, C99
155 // does not require this promotion.
156 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
157 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
158 if (!isCompAssign)
159 ImpCastExprToType(lhsExpr, rhs);
160 return rhs;
161 } else { // handle "_Complex double, double".
162 if (!isCompAssign)
163 ImpCastExprToType(rhsExpr, lhs);
164 return lhs;
165 }
166 }
167 return lhs; // The domain/size match exactly.
168 }
169 // Now handle "real" floating types (i.e. float, double, long double).
170 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
171 // if we have an integer operand, the result is the real floating type.
172 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
173 // convert rhs to the lhs floating point type.
174 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
175 return lhs;
176 }
177 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
178 // convert lhs to the rhs floating point type.
179 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
180 return rhs;
181 }
182 // We have two real floating types, float/complex combos were handled above.
183 // Convert the smaller operand to the bigger result.
184 int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186 if (result > 0) { // convert the rhs
187 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
188 return lhs;
189 }
190 if (result < 0) { // convert the lhs
191 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
192 return rhs;
193 }
194 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
195 }
196 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
197 // Handle GCC complex int extension.
198 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
199 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
200
201 if (lhsComplexInt && rhsComplexInt) {
202 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
203 rhsComplexInt->getElementType()) >= 0) {
204 // convert the rhs
205 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
206 return lhs;
207 }
208 if (!isCompAssign)
209 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
210 return rhs;
211 } else if (lhsComplexInt && rhs->isIntegerType()) {
212 // convert the rhs to the lhs complex type.
213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214 return lhs;
215 } else if (rhsComplexInt && lhs->isIntegerType()) {
216 // convert the lhs to the rhs complex type.
217 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
218 return rhs;
219 }
220 }
221 // Finally, we have two differing integer types.
222 // The rules for this case are in C99 6.3.1.8
223 int compare = Context.getIntegerTypeOrder(lhs, rhs);
224 bool lhsSigned = lhs->isSignedIntegerType(),
225 rhsSigned = rhs->isSignedIntegerType();
226 QualType destType;
227 if (lhsSigned == rhsSigned) {
228 // Same signedness; use the higher-ranked type
229 destType = compare >= 0 ? lhs : rhs;
230 } else if (compare != (lhsSigned ? 1 : -1)) {
231 // The unsigned type has greater than or equal rank to the
232 // signed type, so use the unsigned type
233 destType = lhsSigned ? rhs : lhs;
234 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
235 // The two types are different widths; if we are here, that
236 // means the signed type is larger than the unsigned type, so
237 // use the signed type.
238 destType = lhsSigned ? lhs : rhs;
239 } else {
240 // The signed type is higher-ranked than the unsigned type,
241 // but isn't actually any bigger (like unsigned int and long
242 // on most 32-bit systems). Use the unsigned type corresponding
243 // to the signed type.
244 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
245 }
246 if (!isCompAssign) {
247 ImpCastExprToType(lhsExpr, destType);
248 ImpCastExprToType(rhsExpr, destType);
249 }
250 return destType;
251}
252
253//===----------------------------------------------------------------------===//
254// Semantic Analysis for various Expression Types
255//===----------------------------------------------------------------------===//
256
257
Steve Narofff69936d2007-09-16 03:34:24 +0000258/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000259/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
260/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
261/// multiple tokens. However, the common case is that StringToks points to one
262/// string.
263///
264Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000265Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 assert(NumStringToks && "Must have at least one string!");
267
268 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
269 if (Literal.hadError)
270 return ExprResult(true);
271
272 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
273 for (unsigned i = 0; i != NumStringToks; ++i)
274 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000275
276 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000277 if (Literal.Pascal && Literal.GetStringLength() > 256)
278 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
279 SourceRange(StringToks[0].getLocation(),
280 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000281
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000282 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000283 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000284 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
285
286 // Get an array type for the string, according to C99 6.4.5. This includes
287 // the nul terminator character as well as the string length for pascal
288 // strings.
289 StrTy = Context.getConstantArrayType(StrTy,
290 llvm::APInt(32, Literal.GetStringLength()+1),
291 ArrayType::Normal, 0);
292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
294 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000295 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000296 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 StringToks[NumStringToks-1].getLocation());
298}
299
300
Steve Naroff08d92e42007-09-15 18:49:24 +0000301/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000302/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000303/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000304Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 IdentifierInfo &II,
306 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000307 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000308 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000309
310 // If this reference is in an Objective-C method, then ivar lookup happens as
311 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000312 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000313 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000314 // There are two cases to handle here. 1) scoped lookup could have failed,
315 // in which case we should look for an ivar. 2) scoped lookup could have
316 // found a decl, but that decl is outside the current method (i.e. a global
317 // variable). In these two cases, we do a lookup for an ivar with this
318 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000319 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000320 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000321 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000322 // FIXME: This should use a new expr for a direct reference, don't turn
323 // this into Self->ivar, just return a BareIVarExpr or something.
324 IdentifierInfo &II = Context.Idents.get("self");
325 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
326 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
327 static_cast<Expr*>(SelfExpr.Val), true, true);
328 }
329 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000330 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000331 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000332 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000333 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000334 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000335 }
Chris Lattner8a934232008-03-31 00:36:02 +0000336 }
337
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 if (D == 0) {
339 // Otherwise, this could be an implicitly declared function reference (legal
340 // in C90, extension in C99).
341 if (HasTrailingLParen &&
Chris Lattner8a934232008-03-31 00:36:02 +0000342 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 D = ImplicitlyDefineFunction(Loc, II, S);
344 else {
345 // If this name wasn't predeclared and if this is not a function call,
346 // diagnose the problem.
347 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
348 }
349 }
Chris Lattner8a934232008-03-31 00:36:02 +0000350
Steve Naroffe1223f72007-08-28 03:03:08 +0000351 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner7e669b22008-02-29 16:48:43 +0000352 // check if referencing an identifier with __attribute__((deprecated)).
353 if (VD->getAttr<DeprecatedAttr>())
354 Diag(Loc, diag::warn_deprecated, VD->getName());
355
Steve Naroff53a32342007-08-28 18:45:29 +0000356 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000357 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000358 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000360 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000361
362 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
364 if (MD->isStatic())
365 // "invalid use of member 'x' in static member function"
366 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
367 FD->getName());
368 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
369 // "invalid use of nonstatic data member 'x'"
370 return Diag(Loc, diag::err_invalid_non_static_member_use,
371 FD->getName());
372
373 if (FD->isInvalidDecl())
374 return true;
375
376 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
377 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
378 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
379 true, FD, Loc, FD->getType());
380 }
381
382 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
383 }
Chris Lattner8a934232008-03-31 00:36:02 +0000384
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 if (isa<TypedefDecl>(D))
386 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000388 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000389 if (isa<NamespaceDecl>(D))
390 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
392 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000393 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000394}
395
Chris Lattnerd9f69102008-08-10 01:53:14 +0000396Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000397 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000398 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000401 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000402 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
403 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
404 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000406
407 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000408 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000409 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000410
Chris Lattnerfa28b302008-01-12 08:14:25 +0000411 // Pre-defined identifiers are of type char[x], where x is the length of the
412 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000413 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000414 if (getCurFunctionDecl())
415 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000416 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000417 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000418
Chris Lattner8f978d52008-01-12 19:32:28 +0000419 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000420 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000421 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000422 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000423}
424
Steve Narofff69936d2007-09-16 03:34:24 +0000425Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 llvm::SmallString<16> CharBuffer;
427 CharBuffer.resize(Tok.getLength());
428 const char *ThisTokBegin = &CharBuffer[0];
429 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
430
431 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
432 Tok.getLocation(), PP);
433 if (Literal.hadError())
434 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000435
436 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
437
Chris Lattnerc250aae2008-06-07 22:35:38 +0000438 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
439 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
Steve Narofff69936d2007-09-16 03:34:24 +0000442Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // fast path for a single digit (which is quite common). A single digit
444 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
445 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000446 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000447
Chris Lattner98be4942008-03-05 18:54:05 +0000448 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000449 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 Context.IntTy,
451 Tok.getLocation()));
452 }
453 llvm::SmallString<512> IntegerBuffer;
454 IntegerBuffer.resize(Tok.getLength());
455 const char *ThisTokBegin = &IntegerBuffer[0];
456
457 // Get the spelling of the token, which eliminates trigraphs, etc.
458 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
459 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
460 Tok.getLocation(), PP);
461 if (Literal.hadError)
462 return ExprResult(true);
463
Chris Lattner5d661452007-08-26 03:42:43 +0000464 Expr *Res;
465
466 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000467 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000468 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000469 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000470 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000471 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000472 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000473 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000474
475 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
476
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000477 // isExact will be set by GetFloatValue().
478 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000479 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000480 Ty, Tok.getLocation());
481
Chris Lattner5d661452007-08-26 03:42:43 +0000482 } else if (!Literal.isIntegerLiteral()) {
483 return ExprResult(true);
484 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000485 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000486
Neil Boothb9449512007-08-29 22:00:19 +0000487 // long long is a C99 feature.
488 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000489 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000490 Diag(Tok.getLocation(), diag::ext_longlong);
491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000493 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494
495 if (Literal.GetIntegerValue(ResultVal)) {
496 // If this value didn't fit into uintmax_t, warn and force to ull.
497 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000498 Ty = Context.UnsignedLongLongTy;
499 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000500 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 } else {
502 // If this value fits into a ULL, try to figure out what else it fits into
503 // according to the rules of C99 6.4.4.1p5.
504
505 // Octal, Hexadecimal, and integers with a U suffix are allowed to
506 // be an unsigned int.
507 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
508
509 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000510 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000511 if (!Literal.isLong && !Literal.isLongLong) {
512 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000513 unsigned IntSize = Context.Target.getIntWidth();
514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 // Does it fit in a unsigned int?
516 if (ResultVal.isIntN(IntSize)) {
517 // Does it fit in a signed int?
518 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000519 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000521 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000522 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 }
525
526 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000527 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000528 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000529
530 // Does it fit in a unsigned long?
531 if (ResultVal.isIntN(LongSize)) {
532 // Does it fit in a signed long?
533 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000534 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000536 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000537 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 }
540
541 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000542 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000543 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000544
545 // Does it fit in a unsigned long long?
546 if (ResultVal.isIntN(LongLongSize)) {
547 // Does it fit in a signed long long?
548 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000549 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000551 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000552 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 }
554 }
555
556 // If we still couldn't decide a type, we probably have something that
557 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000558 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000560 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000561 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000563
564 if (ResultVal.getBitWidth() != Width)
565 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 }
567
Chris Lattnerf0467b32008-04-02 04:24:33 +0000568 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 }
Chris Lattner5d661452007-08-26 03:42:43 +0000570
571 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
572 if (Literal.isImaginary)
573 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
574
575 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000576}
577
Steve Narofff69936d2007-09-16 03:34:24 +0000578Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000580 Expr *E = (Expr *)Val;
581 assert((E != 0) && "ActOnParenExpr() missing expr");
582 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000583}
584
585/// The UsualUnaryConversions() function is *not* called by this routine.
586/// See C99 6.3.2.1p[2-4] for more details.
587QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000588 SourceLocation OpLoc,
589 const SourceRange &ExprRange,
590 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 // C99 6.5.3.4p1:
592 if (isa<FunctionType>(exprType) && isSizeof)
593 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000594 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000596 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
597 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 else if (exprType->isIncompleteType()) {
599 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
600 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000601 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 return QualType(); // error
603 }
604 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
605 return Context.getSizeType();
606}
607
608Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000609ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 SourceLocation LPLoc, TypeTy *Ty,
611 SourceLocation RPLoc) {
612 // If error parsing type, ignore.
613 if (Ty == 0) return true;
614
615 // Verify that this is a valid expression.
616 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
617
Chris Lattnerbb280a42008-07-25 21:45:37 +0000618 QualType resultType =
619 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000620
621 if (resultType.isNull())
622 return true;
623 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
624}
625
Chris Lattner5d794252007-08-24 21:41:10 +0000626QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000627 DefaultFunctionArrayConversion(V);
628
Chris Lattnercc26ed72007-08-26 05:39:26 +0000629 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000630 if (const ComplexType *CT = V->getType()->getAsComplexType())
631 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000632
633 // Otherwise they pass through real integer and floating point types here.
634 if (V->getType()->isArithmeticType())
635 return V->getType();
636
637 // Reject anything else.
638 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
639 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000640}
641
642
Reid Spencer5f016e22007-07-11 17:01:13 +0000643
Steve Narofff69936d2007-09-16 03:34:24 +0000644Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 tok::TokenKind Kind,
646 ExprTy *Input) {
647 UnaryOperator::Opcode Opc;
648 switch (Kind) {
649 default: assert(0 && "Unknown unary op!");
650 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
651 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
652 }
653 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
654 if (result.isNull())
655 return true;
656 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
657}
658
659Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000660ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000662 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000663
664 // Perform default conversions.
665 DefaultFunctionArrayConversion(LHSExp);
666 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000667
Chris Lattner12d9ff62007-07-16 00:14:47 +0000668 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000669
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000671 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 // in the subscript position. As a result, we need to derive the array base
673 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000674 Expr *BaseExpr, *IndexExpr;
675 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000676 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000677 BaseExpr = LHSExp;
678 IndexExpr = RHSExp;
679 // FIXME: need to deal with const...
680 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000681 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000682 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000683 BaseExpr = RHSExp;
684 IndexExpr = LHSExp;
685 // FIXME: need to deal with const...
686 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000687 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
688 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000689 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000690
691 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000692 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
693 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000694 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000695 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000696 // FIXME: need to deal with const...
697 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000699 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
700 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 }
702 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000703 if (!IndexExpr->getType()->isIntegerType())
704 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
705 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000706
Chris Lattner12d9ff62007-07-16 00:14:47 +0000707 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
708 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000709 // void (*)(int)) and pointers to incomplete types. Functions are not
710 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000711 if (!ResultType->isObjectType())
712 return Diag(BaseExpr->getLocStart(),
713 diag::err_typecheck_subscript_not_object,
714 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
715
716 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000717}
718
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000719QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000720CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000721 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000722 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000723
724 // This flag determines whether or not the component is to be treated as a
725 // special name, or a regular GLSL-style component access.
726 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000727
728 // The vector accessor can't exceed the number of elements.
729 const char *compStr = CompName.getName();
730 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000731 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000732 baseType.getAsString(), SourceRange(CompLoc));
733 return QualType();
734 }
Nate Begeman8a997642008-05-09 06:41:27 +0000735
736 // Check that we've found one of the special components, or that the component
737 // names must come from the same set.
738 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
739 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
740 SpecialComponent = true;
741 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000742 do
743 compStr++;
744 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
745 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
746 do
747 compStr++;
748 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
749 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
750 do
751 compStr++;
752 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
753 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000754
Nate Begeman8a997642008-05-09 06:41:27 +0000755 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000756 // We didn't get to the end of the string. This means the component names
757 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000758 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000759 std::string(compStr,compStr+1), SourceRange(CompLoc));
760 return QualType();
761 }
762 // Each component accessor can't exceed the vector type.
763 compStr = CompName.getName();
764 while (*compStr) {
765 if (vecType->isAccessorWithinNumElements(*compStr))
766 compStr++;
767 else
768 break;
769 }
Nate Begeman8a997642008-05-09 06:41:27 +0000770 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000771 // We didn't get to the end of the string. This means a component accessor
772 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000773 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000774 baseType.getAsString(), SourceRange(CompLoc));
775 return QualType();
776 }
Nate Begeman8a997642008-05-09 06:41:27 +0000777
778 // If we have a special component name, verify that the current vector length
779 // is an even number, since all special component names return exactly half
780 // the elements.
781 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
782 return QualType();
783 }
784
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000785 // The component accessor looks fine - now we need to compute the actual type.
786 // The vector type is implied by the component accessor. For example,
787 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000788 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
789 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
790 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000791 if (CompSize == 1)
792 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000793
Nate Begeman213541a2008-04-18 23:10:10 +0000794 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000795 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000796 // diagostics look bad. We want extended vector types to appear built-in.
797 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
798 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
799 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000800 }
801 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000802}
803
Reid Spencer5f016e22007-07-11 17:01:13 +0000804Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000805ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 tok::TokenKind OpKind, SourceLocation MemberLoc,
807 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000808 Expr *BaseExpr = static_cast<Expr *>(Base);
809 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000810
811 // Perform default conversions.
812 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000814 QualType BaseType = BaseExpr->getType();
815 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000816
Chris Lattner68a057b2008-07-21 04:36:39 +0000817 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
818 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000820 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000821 BaseType = PT->getPointeeType();
822 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000823 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
824 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000826
Chris Lattner68a057b2008-07-21 04:36:39 +0000827 // Handle field access to simple records. This also handles access to fields
828 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000829 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000830 RecordDecl *RDecl = RTy->getDecl();
831 if (RTy->isIncompleteType())
832 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
833 BaseExpr->getSourceRange());
834 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000835 FieldDecl *MemberDecl = RDecl->getMember(&Member);
836 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000837 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
838 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000839
840 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000841 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000842 QualType MemberType = MemberDecl->getType();
843 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000844 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000845 MemberType = MemberType.getQualifiedType(combinedQualifiers);
846
Chris Lattner68a057b2008-07-21 04:36:39 +0000847 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000848 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000849 }
850
Chris Lattnera38e6b12008-07-21 04:59:05 +0000851 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
852 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000853 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
854 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000855 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000856 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000857 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000858 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000859 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000860 }
861
Chris Lattnera38e6b12008-07-21 04:59:05 +0000862 // Handle Objective-C property access, which is "Obj.property" where Obj is a
863 // pointer to a (potentially qualified) interface type.
864 const PointerType *PTy;
865 const ObjCInterfaceType *IFTy;
866 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
867 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
868 ObjCInterfaceDecl *IFace = IFTy->getDecl();
869
Chris Lattner6562fda2008-07-21 06:44:27 +0000870 // FIXME: The logic for looking up nullary and unary selectors should be
871 // shared with the code in ActOnInstanceMessage.
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000872
873 // FIXME: This logic is not correct, we should search for
874 // properties first. Additionally, the AST node doesn't currently
875 // have enough information to store the setter argument.
876#if 0
Chris Lattnera38e6b12008-07-21 04:59:05 +0000877 // Before we look for explicit property declarations, we check for
878 // nullary methods (which allow '.' notation).
879 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Chris Lattnera38e6b12008-07-21 04:59:05 +0000880 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel))
881 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
882 MemberLoc, BaseExpr);
883
Chris Lattner6562fda2008-07-21 06:44:27 +0000884 // If this reference is in an @implementation, check for 'private' methods.
885 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
886 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
887 if (ObjCImplementationDecl *ImpDecl =
888 ObjCImplementations[ClassDecl->getIdentifier()])
889 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel))
890 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
891 MemberLoc, BaseExpr);
892 }
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000893#endif
Chris Lattner6562fda2008-07-21 06:44:27 +0000894
Chris Lattnera38e6b12008-07-21 04:59:05 +0000895 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
896 // @interface NSBundle : NSObject {}
897 // - (NSString *)bundlePath;
898 // - (void)setBundlePath:(NSString *)x;
899 // @end
900 // void someMethod() { frameworkBundle.bundlePath = 0; }
901 //
902 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
903 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
904
905 // Lastly, check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000906 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
907 E = IFTy->qual_end(); I != E; ++I)
908 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
909 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000910 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000911
912 // Handle 'field access' to vectors, such as 'V.xx'.
913 if (BaseType->isExtVectorType() && OpKind == tok::period) {
914 // Component access limited to variables (reject vec4.rg.g).
915 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
916 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +0000917 return Diag(MemberLoc, diag::err_ext_vector_component_access,
918 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000919 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
920 if (ret.isNull())
921 return true;
922 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
923 }
924
Chris Lattner2a01b722008-07-21 05:35:34 +0000925 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
926 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000927}
928
Steve Narofff69936d2007-09-16 03:34:24 +0000929/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000930/// This provides the location of the left/right parens and a list of comma
931/// locations.
932Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000933ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +0000934 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +0000935 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000936 Expr *Fn = static_cast<Expr *>(fn);
937 Expr **Args = reinterpret_cast<Expr**>(args);
938 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +0000939 FunctionDecl *FDecl = NULL;
Chris Lattner04421082008-04-08 04:40:51 +0000940
941 // Promote the function operand.
942 UsualUnaryConversions(Fn);
943
944 // If we're directly calling a function, get the declaration for
945 // that function.
946 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
947 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
948 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
949
Chris Lattner925e60d2007-12-28 05:29:59 +0000950 // Make the call expr early, before semantic checks. This guarantees cleanup
951 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +0000952 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +0000953 Context.BoolTy, RParenLoc));
954
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
956 // type pointer to function".
Chris Lattner925e60d2007-12-28 05:29:59 +0000957 const PointerType *PT = Fn->getType()->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 if (PT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +0000959 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
960 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +0000961 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
962 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +0000963 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
964 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +0000965
966 // We know the result type of the call, set it.
967 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000968
Chris Lattner925e60d2007-12-28 05:29:59 +0000969 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
971 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +0000972 unsigned NumArgsInProto = Proto->getNumArgs();
973 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000974
Chris Lattner04421082008-04-08 04:40:51 +0000975 // If too few arguments are available (and we don't have default
976 // arguments for the remaining parameters), don't make the call.
977 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +0000978 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +0000979 // Use default arguments for missing arguments
980 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +0000981 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +0000982 } else
983 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
984 Fn->getSourceRange());
985 }
986
Chris Lattner925e60d2007-12-28 05:29:59 +0000987 // If too many are passed and not variadic, error on the extras and drop
988 // them.
989 if (NumArgs > NumArgsInProto) {
990 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000991 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000992 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000993 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000994 Args[NumArgs-1]->getLocEnd()));
995 // This deletes the extra arguments.
996 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 }
998 NumArgsToCheck = NumArgsInProto;
999 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001000
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001002 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001003 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001004
1005 Expr *Arg;
1006 if (i < NumArgs)
1007 Arg = Args[i];
1008 else
1009 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001010 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001011
Chris Lattner925e60d2007-12-28 05:29:59 +00001012 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001013 AssignConvertType ConvTy =
1014 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001015 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001016
Chris Lattner5cf216b2008-01-04 18:04:52 +00001017 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1018 ArgType, Arg, "passing"))
1019 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001021
1022 // If this is a variadic call, handle args passed through "...".
1023 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001024 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001025 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1026 Expr *Arg = Args[i];
1027 DefaultArgumentPromotion(Arg);
1028 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001029 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001030 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001031 } else {
1032 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1033
Steve Naroffb291ab62007-08-28 23:30:39 +00001034 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001035 for (unsigned i = 0; i != NumArgs; i++) {
1036 Expr *Arg = Args[i];
1037 DefaultArgumentPromotion(Arg);
1038 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001039 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001041
Chris Lattner59907c42007-08-10 20:18:51 +00001042 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001043 if (FDecl)
1044 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001045
Chris Lattner925e60d2007-12-28 05:29:59 +00001046 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001047}
1048
1049Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001050ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001051 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001052 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001053 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001054 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001055 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001056 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001057
Eli Friedman6223c222008-05-20 05:22:08 +00001058 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001059 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001060 return Diag(LParenLoc,
1061 diag::err_variable_object_no_init,
1062 SourceRange(LParenLoc,
1063 literalExpr->getSourceRange().getEnd()));
1064 } else if (literalType->isIncompleteType()) {
1065 return Diag(LParenLoc,
1066 diag::err_typecheck_decl_incomplete_type,
1067 literalType.getAsString(),
1068 SourceRange(LParenLoc,
1069 literalExpr->getSourceRange().getEnd()));
1070 }
1071
Steve Naroffd0091aa2008-01-10 22:15:12 +00001072 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001073 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001074
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001075 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001076 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001077 if (CheckForConstantInitializer(literalExpr, literalType))
1078 return true;
1079 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001080 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001081}
1082
1083Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001084ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001085 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001086 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001087
Steve Naroff08d92e42007-09-15 18:49:24 +00001088 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001089 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001090
Chris Lattnerf0467b32008-04-02 04:24:33 +00001091 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1092 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1093 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001094}
1095
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001096/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001097bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001098 UsualUnaryConversions(castExpr);
1099
1100 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1101 // type needs to be scalar.
1102 if (castType->isVoidType()) {
1103 // Cast to void allows any expr type.
1104 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1105 // GCC struct/union extension: allow cast to self.
1106 if (Context.getCanonicalType(castType) !=
1107 Context.getCanonicalType(castExpr->getType()) ||
1108 (!castType->isStructureType() && !castType->isUnionType())) {
1109 // Reject any other conversions to non-scalar types.
1110 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1111 castType.getAsString(), castExpr->getSourceRange());
1112 }
1113
1114 // accept this, but emit an ext-warn.
1115 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1116 castType.getAsString(), castExpr->getSourceRange());
1117 } else if (!castExpr->getType()->isScalarType() &&
1118 !castExpr->getType()->isVectorType()) {
1119 return Diag(castExpr->getLocStart(),
1120 diag::err_typecheck_expect_scalar_operand,
1121 castExpr->getType().getAsString(),castExpr->getSourceRange());
1122 } else if (castExpr->getType()->isVectorType()) {
1123 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1124 return true;
1125 } else if (castType->isVectorType()) {
1126 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1127 return true;
1128 }
1129 return false;
1130}
1131
Chris Lattnerfe23e212007-12-20 00:44:32 +00001132bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001133 assert(VectorTy->isVectorType() && "Not a vector type!");
1134
1135 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001136 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001137 return Diag(R.getBegin(),
1138 Ty->isVectorType() ?
1139 diag::err_invalid_conversion_between_vectors :
1140 diag::err_invalid_conversion_between_vector_and_integer,
1141 VectorTy.getAsString().c_str(),
1142 Ty.getAsString().c_str(), R);
1143 } else
1144 return Diag(R.getBegin(),
1145 diag::err_invalid_conversion_between_vector_and_scalar,
1146 VectorTy.getAsString().c_str(),
1147 Ty.getAsString().c_str(), R);
1148
1149 return false;
1150}
1151
Steve Naroff4aa88f82007-07-19 01:06:55 +00001152Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001153ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001155 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001156
1157 Expr *castExpr = static_cast<Expr*>(Op);
1158 QualType castType = QualType::getFromOpaquePtr(Ty);
1159
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001160 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1161 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001162 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001163}
1164
Chris Lattnera21ddb32007-11-26 01:40:58 +00001165/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1166/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001167inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001168 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001169 UsualUnaryConversions(cond);
1170 UsualUnaryConversions(lex);
1171 UsualUnaryConversions(rex);
1172 QualType condT = cond->getType();
1173 QualType lexT = lex->getType();
1174 QualType rexT = rex->getType();
1175
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001177 if (!condT->isScalarType()) { // C99 6.5.15p2
1178 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1179 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 return QualType();
1181 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001182
1183 // Now check the two expressions.
1184
1185 // If both operands have arithmetic type, do the usual arithmetic conversions
1186 // to find a common type: C99 6.5.15p3,5.
1187 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001188 UsualArithmeticConversions(lex, rex);
1189 return lex->getType();
1190 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001191
1192 // If both operands are the same structure or union type, the result is that
1193 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001194 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001195 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001196 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001197 // "If both the operands have structure or union type, the result has
1198 // that type." This implies that CV qualifiers are dropped.
1199 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001201
1202 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001203 // The following || allows only one side to be void (a GCC-ism).
1204 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001205 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001206 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1207 rex->getSourceRange());
1208 if (!rexT->isVoidType())
1209 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001210 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001211 ImpCastExprToType(lex, Context.VoidTy);
1212 ImpCastExprToType(rex, Context.VoidTy);
1213 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001214 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001215 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1216 // the type of the other operand."
1217 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001218 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001219 return lexT;
1220 }
1221 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001222 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001223 return rexT;
1224 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001225 // Handle the case where both operands are pointers before we handle null
1226 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001227 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1228 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1229 // get the "pointed to" types
1230 QualType lhptee = LHSPT->getPointeeType();
1231 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001232
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001233 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1234 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001235 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001236 // Figure out necessary qualifiers (C99 6.5.15p6)
1237 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001238 QualType destType = Context.getPointerType(destPointee);
1239 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1240 ImpCastExprToType(rex, destType); // promote to void*
1241 return destType;
1242 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001243 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001244 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001245 QualType destType = Context.getPointerType(destPointee);
1246 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1247 ImpCastExprToType(rex, destType); // promote to void*
1248 return destType;
1249 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001250
Steve Naroffec0550f2007-10-15 20:41:53 +00001251 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1252 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001253 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001254 lexT.getAsString(), rexT.getAsString(),
1255 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara56f7462008-08-26 00:41:39 +00001256 // In this situation, assume a conservative type; in general
1257 // we assume void* type. No especially good reason, but this
1258 // is what gcc does, and we do have to pick to get a
1259 // consistent AST. However, if either type is an Objective-C
1260 // object type then use id.
1261 QualType incompatTy;
1262 if (Context.isObjCObjectPointerType(lexT) ||
1263 Context.isObjCObjectPointerType(rexT)) {
1264 incompatTy = Context.getObjCIdType();
1265 } else {
1266 incompatTy = Context.getPointerType(Context.VoidTy);
1267 }
1268 ImpCastExprToType(lex, incompatTy);
1269 ImpCastExprToType(rex, incompatTy);
1270 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001271 }
1272 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001273 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1274 // differently qualified versions of compatible types, the result type is
1275 // a pointer to an appropriately qualified version of the *composite*
1276 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001277 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001278 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001279 QualType compositeType = lexT;
1280 ImpCastExprToType(lex, compositeType);
1281 ImpCastExprToType(rex, compositeType);
1282 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 }
1284 }
Steve Naroffaa73eec2008-05-31 22:33:45 +00001285 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1286 // evaluates to "struct objc_object *" (and is handled above when comparing
Daniel Dunbara56f7462008-08-26 00:41:39 +00001287 // id with statically typed objects).
Steve Naroffaa73eec2008-05-31 22:33:45 +00001288 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
Daniel Dunbara56f7462008-08-26 00:41:39 +00001289 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true)) {
1290 // FIXME: This is not the correct composite type.
1291 QualType compositeType = Context.getObjCIdType();
1292 ImpCastExprToType(lex, compositeType);
1293 ImpCastExprToType(rex, compositeType);
1294 return compositeType;
1295 }
Steve Naroffaa73eec2008-05-31 22:33:45 +00001296 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001297 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001299 lexT.getAsString(), rexT.getAsString(),
1300 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 return QualType();
1302}
1303
Steve Narofff69936d2007-09-16 03:34:24 +00001304/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001305/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001306Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 SourceLocation ColonLoc,
1308 ExprTy *Cond, ExprTy *LHS,
1309 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001310 Expr *CondExpr = (Expr *) Cond;
1311 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001312
1313 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1314 // was the condition.
1315 bool isLHSNull = LHSExpr == 0;
1316 if (isLHSNull)
1317 LHSExpr = CondExpr;
1318
Chris Lattner26824902007-07-16 21:39:03 +00001319 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1320 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 if (result.isNull())
1322 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001323 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1324 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001325}
1326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327
1328// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1329// being closely modeled after the C99 spec:-). The odd characteristic of this
1330// routine is it effectively iqnores the qualifiers on the top level pointee.
1331// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1332// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001333Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001334Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1335 QualType lhptee, rhptee;
1336
1337 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001338 lhptee = lhsType->getAsPointerType()->getPointeeType();
1339 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001340
1341 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001342 lhptee = Context.getCanonicalType(lhptee);
1343 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001344
Chris Lattner5cf216b2008-01-04 18:04:52 +00001345 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346
1347 // C99 6.5.16.1p1: This following citation is common to constraints
1348 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1349 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001350 // FIXME: Handle ASQualType
1351 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1352 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001353 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001354
1355 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1356 // incomplete type and the other is a pointer to a qualified or unqualified
1357 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001358 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001359 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001360 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001361
1362 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001363 assert(rhptee->isFunctionType());
1364 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001365 }
1366
1367 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001368 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001369 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001370
1371 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001372 assert(lhptee->isFunctionType());
1373 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001374 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001375
1376 // Check for ObjC interfaces
1377 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1378 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1379 if (LHSIface && RHSIface &&
1380 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1381 return ConvTy;
1382
1383 // ID acts sort of like void* for ObjC interfaces
1384 if (LHSIface && Context.isObjCIdType(rhptee))
1385 return ConvTy;
1386 if (RHSIface && Context.isObjCIdType(lhptee))
1387 return ConvTy;
1388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1390 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001391 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1392 rhptee.getUnqualifiedType()))
1393 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001394 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001395}
1396
1397/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1398/// has code to accommodate several GCC extensions when type checking
1399/// pointers. Here are some objectionable examples that GCC considers warnings:
1400///
1401/// int a, *pint;
1402/// short *pshort;
1403/// struct foo *pfoo;
1404///
1405/// pint = pshort; // warning: assignment from incompatible pointer type
1406/// a = pint; // warning: assignment makes integer from pointer without a cast
1407/// pint = a; // warning: assignment makes pointer from integer without a cast
1408/// pint = pfoo; // warning: assignment from incompatible pointer type
1409///
1410/// As a result, the code for dealing with pointers is more complex than the
1411/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001412///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001413Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001414Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001415 // Get canonical types. We're not formatting these types, just comparing
1416 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001417 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1418 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001419
1420 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001421 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001422
Anders Carlsson793680e2007-10-12 23:56:29 +00001423 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001424 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001425 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001426 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001427 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001428
Chris Lattnereca7be62008-04-07 05:30:13 +00001429 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1430 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001431 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001432 // Relax integer conversions like we do for pointers below.
1433 if (rhsType->isIntegerType())
1434 return IntToPointer;
1435 if (lhsType->isIntegerType())
1436 return PointerToInt;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001437 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001438 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001439
Nate Begemanbe2341d2008-07-14 18:02:46 +00001440 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001441 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001442 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1443 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001444 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001445
Nate Begemanbe2341d2008-07-14 18:02:46 +00001446 // If we are allowing lax vector conversions, and LHS and RHS are both
1447 // vectors, the total size only needs to be the same. This is a bitcast;
1448 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001449 if (getLangOptions().LaxVectorConversions &&
1450 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001451 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1452 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001453 }
1454 return Incompatible;
1455 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001456
Chris Lattnere8b3e962008-01-04 23:32:24 +00001457 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001459
Chris Lattner78eca282008-04-07 06:49:41 +00001460 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001462 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001463
Chris Lattner78eca282008-04-07 06:49:41 +00001464 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001466 return Incompatible;
1467 }
1468
Chris Lattner78eca282008-04-07 06:49:41 +00001469 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001471 if (lhsType == Context.BoolTy)
1472 return Compatible;
1473
1474 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001475 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001476
Chris Lattner78eca282008-04-07 06:49:41 +00001477 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001479 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001480 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001481
Chris Lattnerfc144e22008-01-04 23:18:45 +00001482 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001483 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 }
1486 return Incompatible;
1487}
1488
Chris Lattner5cf216b2008-01-04 18:04:52 +00001489Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001490Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001491 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1492 // a null pointer constant.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001493 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001494 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001495 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001496 return Compatible;
1497 }
Chris Lattner943140e2007-10-16 02:55:40 +00001498 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001499 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001500 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001501 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001502 //
1503 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1504 // are better understood.
1505 if (!lhsType->isReferenceType())
1506 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001507
Chris Lattner5cf216b2008-01-04 18:04:52 +00001508 Sema::AssignConvertType result =
1509 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001510
1511 // C99 6.5.16.1p2: The value of the right operand is converted to the
1512 // type of the assignment expression.
1513 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001514 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001515 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001516}
1517
Chris Lattner5cf216b2008-01-04 18:04:52 +00001518Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001519Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1520 return CheckAssignmentConstraints(lhsType, rhsType);
1521}
1522
Chris Lattnerca5eede2007-12-12 05:47:28 +00001523QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 Diag(loc, diag::err_typecheck_invalid_operands,
1525 lex->getType().getAsString(), rex->getType().getAsString(),
1526 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001527 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001528}
1529
Steve Naroff49b45262007-07-13 16:58:59 +00001530inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1531 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001532 // For conversion purposes, we ignore any qualifiers.
1533 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001534 QualType lhsType =
1535 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1536 QualType rhsType =
1537 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001538
Nate Begemanbe2341d2008-07-14 18:02:46 +00001539 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001540 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001542
Nate Begemanbe2341d2008-07-14 18:02:46 +00001543 // Handle the case of a vector & extvector type of the same size and element
1544 // type. It would be nice if we only had one vector type someday.
1545 if (getLangOptions().LaxVectorConversions)
1546 if (const VectorType *LV = lhsType->getAsVectorType())
1547 if (const VectorType *RV = rhsType->getAsVectorType())
1548 if (LV->getElementType() == RV->getElementType() &&
1549 LV->getNumElements() == RV->getNumElements())
1550 return lhsType->isExtVectorType() ? lhsType : rhsType;
1551
1552 // If the lhs is an extended vector and the rhs is a scalar of the same type
1553 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001554 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001555 QualType eltType = V->getElementType();
1556
1557 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1558 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1559 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001560 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001561 return lhsType;
1562 }
1563 }
1564
Nate Begemanbe2341d2008-07-14 18:02:46 +00001565 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001566 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001567 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001568 QualType eltType = V->getElementType();
1569
1570 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1571 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1572 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001573 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001574 return rhsType;
1575 }
1576 }
1577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 // You cannot convert between vector values of different size.
1579 Diag(loc, diag::err_typecheck_vector_not_convertable,
1580 lex->getType().getAsString(), rex->getType().getAsString(),
1581 lex->getSourceRange(), rex->getSourceRange());
1582 return QualType();
1583}
1584
1585inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001586 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001587{
Steve Naroff90045e82007-07-13 23:32:42 +00001588 QualType lhsType = lex->getType(), rhsType = rex->getType();
1589
1590 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001592
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001593 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594
Steve Naroffa4332e22007-07-17 00:58:39 +00001595 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001596 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001597 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001598}
1599
1600inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001601 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001602{
Steve Naroff90045e82007-07-13 23:32:42 +00001603 QualType lhsType = lex->getType(), rhsType = rex->getType();
1604
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001605 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001606
Steve Naroffa4332e22007-07-17 00:58:39 +00001607 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001608 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001609 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001610}
1611
1612inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001613 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001614{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001615 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001616 return CheckVectorOperands(loc, lex, rex);
1617
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001618 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001619
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001621 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001622 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623
Eli Friedmand72d16e2008-05-18 18:08:51 +00001624 // Put any potential pointer into PExp
1625 Expr* PExp = lex, *IExp = rex;
1626 if (IExp->getType()->isPointerType())
1627 std::swap(PExp, IExp);
1628
1629 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1630 if (IExp->getType()->isIntegerType()) {
1631 // Check for arithmetic on pointers to incomplete types
1632 if (!PTy->getPointeeType()->isObjectType()) {
1633 if (PTy->getPointeeType()->isVoidType()) {
1634 Diag(loc, diag::ext_gnu_void_ptr,
1635 lex->getSourceRange(), rex->getSourceRange());
1636 } else {
1637 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1638 lex->getType().getAsString(), lex->getSourceRange());
1639 return QualType();
1640 }
1641 }
1642 return PExp->getType();
1643 }
1644 }
1645
Chris Lattnerca5eede2007-12-12 05:47:28 +00001646 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001647}
1648
Chris Lattnereca7be62008-04-07 05:30:13 +00001649// C99 6.5.6
1650QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1651 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001652 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001654
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001655 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001656
Chris Lattner6e4ab612007-12-09 21:53:25 +00001657 // Enforce type constraints: C99 6.5.6p3.
1658
1659 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001660 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001661 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001662
1663 // Either ptr - int or ptr - ptr.
1664 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001665 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001666
Chris Lattner6e4ab612007-12-09 21:53:25 +00001667 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001668 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001669 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001670 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001671 Diag(loc, diag::ext_gnu_void_ptr,
1672 lex->getSourceRange(), rex->getSourceRange());
1673 } else {
1674 Diag(loc, diag::err_typecheck_sub_ptr_object,
1675 lex->getType().getAsString(), lex->getSourceRange());
1676 return QualType();
1677 }
1678 }
1679
1680 // The result type of a pointer-int computation is the pointer type.
1681 if (rex->getType()->isIntegerType())
1682 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001683
Chris Lattner6e4ab612007-12-09 21:53:25 +00001684 // Handle pointer-pointer subtractions.
1685 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001686 QualType rpointee = RHSPTy->getPointeeType();
1687
Chris Lattner6e4ab612007-12-09 21:53:25 +00001688 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001689 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001690 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001691 if (rpointee->isVoidType()) {
1692 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001693 Diag(loc, diag::ext_gnu_void_ptr,
1694 lex->getSourceRange(), rex->getSourceRange());
1695 } else {
1696 Diag(loc, diag::err_typecheck_sub_ptr_object,
1697 rex->getType().getAsString(), rex->getSourceRange());
1698 return QualType();
1699 }
1700 }
1701
1702 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001703 if (!Context.typesAreCompatible(
1704 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1705 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001706 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1707 lex->getType().getAsString(), rex->getType().getAsString(),
1708 lex->getSourceRange(), rex->getSourceRange());
1709 return QualType();
1710 }
1711
1712 return Context.getPointerDiffType();
1713 }
1714 }
1715
Chris Lattnerca5eede2007-12-12 05:47:28 +00001716 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001717}
1718
Chris Lattnereca7be62008-04-07 05:30:13 +00001719// C99 6.5.7
1720QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1721 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00001722 // C99 6.5.7p2: Each of the operands shall have integer type.
1723 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1724 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725
Chris Lattnerca5eede2007-12-12 05:47:28 +00001726 // Shifts don't perform usual arithmetic conversions, they just do integer
1727 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001728 if (!isCompAssign)
1729 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001730 UsualUnaryConversions(rex);
1731
1732 // "The type of the result is that of the promoted left operand."
1733 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001734}
1735
Eli Friedman3d815e72008-08-22 00:56:42 +00001736static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1737 ASTContext& Context) {
1738 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1739 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1740 // ID acts sort of like void* for ObjC interfaces
1741 if (LHSIface && Context.isObjCIdType(RHS))
1742 return true;
1743 if (RHSIface && Context.isObjCIdType(LHS))
1744 return true;
1745 if (!LHSIface || !RHSIface)
1746 return false;
1747 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1748 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1749}
1750
Chris Lattnereca7be62008-04-07 05:30:13 +00001751// C99 6.5.8
1752QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1753 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001754 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1755 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1756
Chris Lattnera5937dd2007-08-26 01:18:55 +00001757 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001758 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1759 UsualArithmeticConversions(lex, rex);
1760 else {
1761 UsualUnaryConversions(lex);
1762 UsualUnaryConversions(rex);
1763 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001764 QualType lType = lex->getType();
1765 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001766
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001767 // For non-floating point types, check for self-comparisons of the form
1768 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1769 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001770 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001771 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1772 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001773 if (DRL->getDecl() == DRR->getDecl())
1774 Diag(loc, diag::warn_selfcomparison);
1775 }
1776
Chris Lattnera5937dd2007-08-26 01:18:55 +00001777 if (isRelational) {
1778 if (lType->isRealType() && rType->isRealType())
1779 return Context.IntTy;
1780 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001781 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001782 if (lType->isFloatingType()) {
1783 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001784 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001785 }
1786
Chris Lattnera5937dd2007-08-26 01:18:55 +00001787 if (lType->isArithmeticType() && rType->isArithmeticType())
1788 return Context.IntTy;
1789 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001790
Chris Lattnerd28f8152007-08-26 01:10:14 +00001791 bool LHSIsNull = lex->isNullPointerConstant(Context);
1792 bool RHSIsNull = rex->isNullPointerConstant(Context);
1793
Chris Lattnera5937dd2007-08-26 01:18:55 +00001794 // All of the following pointer related warnings are GCC extensions, except
1795 // when handling null pointer constants. One day, we can consider making them
1796 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001797 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001798 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00001799 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00001800 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00001801 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00001802
Steve Naroff66296cb2007-11-13 14:57:38 +00001803 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001804 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1805 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00001806 RCanPointeeTy.getUnqualifiedType()) &&
1807 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001808 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1809 lType.getAsString(), rType.getAsString(),
1810 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00001812 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001813 return Context.IntTy;
1814 }
Steve Naroff20373222008-06-03 14:04:54 +00001815 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1816 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1817 ImpCastExprToType(rex, lType);
1818 return Context.IntTy;
1819 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001820 }
Steve Naroff20373222008-06-03 14:04:54 +00001821 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1822 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001823 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001824 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1825 lType.getAsString(), rType.getAsString(),
1826 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001827 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001828 return Context.IntTy;
1829 }
Steve Naroff20373222008-06-03 14:04:54 +00001830 if (lType->isIntegerType() &&
1831 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001832 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001833 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1834 lType.getAsString(), rType.getAsString(),
1835 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001836 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001837 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001839 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001840}
1841
Nate Begemanbe2341d2008-07-14 18:02:46 +00001842/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1843/// operates on extended vector types. Instead of producing an IntTy result,
1844/// like a scalar comparison, a vector comparison produces a vector of integer
1845/// types.
1846QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1847 SourceLocation loc,
1848 bool isRelational) {
1849 // Check to make sure we're operating on vectors of the same type and width,
1850 // Allowing one side to be a scalar of element type.
1851 QualType vType = CheckVectorOperands(loc, lex, rex);
1852 if (vType.isNull())
1853 return vType;
1854
1855 QualType lType = lex->getType();
1856 QualType rType = rex->getType();
1857
1858 // For non-floating point types, check for self-comparisons of the form
1859 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1860 // often indicate logic errors in the program.
1861 if (!lType->isFloatingType()) {
1862 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1863 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1864 if (DRL->getDecl() == DRR->getDecl())
1865 Diag(loc, diag::warn_selfcomparison);
1866 }
1867
1868 // Check for comparisons of floating point operands using != and ==.
1869 if (!isRelational && lType->isFloatingType()) {
1870 assert (rType->isFloatingType());
1871 CheckFloatComparison(loc,lex,rex);
1872 }
1873
1874 // Return the type for the comparison, which is the same as vector type for
1875 // integer vectors, or an integer type of identical size and number of
1876 // elements for floating point vectors.
1877 if (lType->isIntegerType())
1878 return lType;
1879
1880 const VectorType *VTy = lType->getAsVectorType();
1881
1882 // FIXME: need to deal with non-32b int / non-64b long long
1883 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1884 if (TypeSize == 32) {
1885 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1886 }
1887 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1888 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1889}
1890
Reid Spencer5f016e22007-07-11 17:01:13 +00001891inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001892 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001893{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001894 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001896
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001897 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001898
Steve Naroffa4332e22007-07-17 00:58:39 +00001899 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001900 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001901 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001902}
1903
1904inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001905 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001906{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001907 UsualUnaryConversions(lex);
1908 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001909
Eli Friedman5773a6c2008-05-13 20:16:47 +00001910 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001912 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001913}
1914
1915inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001916 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001917{
1918 QualType lhsType = lex->getType();
1919 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00001920 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00001921
1922 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00001923 case Expr::MLV_Valid:
1924 break;
1925 case Expr::MLV_ConstQualified:
1926 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1927 return QualType();
1928 case Expr::MLV_ArrayType:
1929 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1930 lhsType.getAsString(), lex->getSourceRange());
1931 return QualType();
1932 case Expr::MLV_NotObjectType:
1933 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1934 lhsType.getAsString(), lex->getSourceRange());
1935 return QualType();
1936 case Expr::MLV_InvalidExpression:
1937 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1938 lex->getSourceRange());
1939 return QualType();
1940 case Expr::MLV_IncompleteType:
1941 case Expr::MLV_IncompleteVoidType:
1942 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1943 lhsType.getAsString(), lex->getSourceRange());
1944 return QualType();
1945 case Expr::MLV_DuplicateVectorComponents:
1946 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1947 lex->getSourceRange());
1948 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00001950
Chris Lattner5cf216b2008-01-04 18:04:52 +00001951 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00001952 if (compoundType.isNull()) {
1953 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00001954 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00001955
1956 // If the RHS is a unary plus or minus, check to see if they = and + are
1957 // right next to each other. If so, the user may have typo'd "x =+ 4"
1958 // instead of "x += 4".
1959 Expr *RHSCheck = rex;
1960 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
1961 RHSCheck = ICE->getSubExpr();
1962 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
1963 if ((UO->getOpcode() == UnaryOperator::Plus ||
1964 UO->getOpcode() == UnaryOperator::Minus) &&
1965 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
1966 // Only if the two operators are exactly adjacent.
1967 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
1968 Diag(loc, diag::warn_not_compound_assign,
1969 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
1970 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
1971 }
1972 } else {
1973 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00001974 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00001975 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00001976
1977 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1978 rex, "assigning"))
1979 return QualType();
1980
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 // C99 6.5.16p3: The type of an assignment expression is the type of the
1982 // left operand unless the left operand has qualified type, in which case
1983 // it is the unqualified version of the type of the left operand.
1984 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1985 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001986 // C++ 5.17p1: the type of the assignment expression is that of its left
1987 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001988 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001989}
1990
1991inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001992 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00001993
1994 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
1995 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001996 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001997}
1998
Steve Naroff49b45262007-07-13 16:58:59 +00001999/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2000/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002001QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002002 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 assert(!resType.isNull() && "no type for increment/decrement expression");
2004
Steve Naroff084f9ed2007-08-24 17:20:07 +00002005 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002006 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002007 if (pt->getPointeeType()->isVoidType()) {
2008 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2009 } else if (!pt->getPointeeType()->isObjectType()) {
2010 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2012 resType.getAsString(), op->getSourceRange());
2013 return QualType();
2014 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002015 } else if (!resType->isRealType()) {
2016 if (resType->isComplexType())
2017 // C99 does not support ++/-- on complex types.
2018 Diag(OpLoc, diag::ext_integer_increment_complex,
2019 resType.getAsString(), op->getSourceRange());
2020 else {
2021 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2022 resType.getAsString(), op->getSourceRange());
2023 return QualType();
2024 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002026 // At this point, we know we have a real, complex or pointer type.
2027 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002028 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 if (mlval != Expr::MLV_Valid) {
2030 // FIXME: emit a more precise diagnostic...
2031 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2032 op->getSourceRange());
2033 return QualType();
2034 }
2035 return resType;
2036}
2037
Anders Carlsson369dee42008-02-01 07:15:58 +00002038/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002039/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002040/// where the declaration is needed for type checking. We only need to
2041/// handle cases when the expression references a function designator
2042/// or is an lvalue. Here are some examples:
2043/// - &(x) => x
2044/// - &*****f => f for f a function designator.
2045/// - &s.xx => s
2046/// - &s.zz[1].yy -> s, if zz is an array
2047/// - *(x + 1) -> x, if x is an array
2048/// - &"123"[2] -> 0
2049/// - & __real__ x -> x
Chris Lattnerf0467b32008-04-02 04:24:33 +00002050static ValueDecl *getPrimaryDecl(Expr *E) {
2051 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002053 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002055 // Fields cannot be declared with a 'register' storage class.
2056 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002057 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002058 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002059 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002060 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002061 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002062
Chris Lattnerf0467b32008-04-02 04:24:33 +00002063 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002064 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002065 return 0;
2066 else
2067 return VD;
2068 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002069 case Stmt::UnaryOperatorClass: {
2070 UnaryOperator *UO = cast<UnaryOperator>(E);
2071
2072 switch(UO->getOpcode()) {
2073 case UnaryOperator::Deref: {
2074 // *(X + 1) refers to X if X is not a pointer.
2075 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2076 if (!VD || VD->getType()->isPointerType())
2077 return 0;
2078 return VD;
2079 }
2080 case UnaryOperator::Real:
2081 case UnaryOperator::Imag:
2082 case UnaryOperator::Extension:
2083 return getPrimaryDecl(UO->getSubExpr());
2084 default:
2085 return 0;
2086 }
2087 }
2088 case Stmt::BinaryOperatorClass: {
2089 BinaryOperator *BO = cast<BinaryOperator>(E);
2090
2091 // Handle cases involving pointer arithmetic. The result of an
2092 // Assign or AddAssign is not an lvalue so they can be ignored.
2093
2094 // (x + n) or (n + x) => x
2095 if (BO->getOpcode() == BinaryOperator::Add) {
2096 if (BO->getLHS()->getType()->isPointerType()) {
2097 return getPrimaryDecl(BO->getLHS());
2098 } else if (BO->getRHS()->getType()->isPointerType()) {
2099 return getPrimaryDecl(BO->getRHS());
2100 }
2101 }
2102
2103 return 0;
2104 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002106 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002107 case Stmt::ImplicitCastExprClass:
2108 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002109 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 default:
2111 return 0;
2112 }
2113}
2114
2115/// CheckAddressOfOperand - The operand of & must be either a function
2116/// designator or an lvalue designating an object. If it is an lvalue, the
2117/// object cannot be declared with storage class register or be a bit field.
2118/// Note: The usual conversions are *not* applied to the operand of the &
2119/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2120QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002121 if (getLangOptions().C99) {
2122 // Implement C99-only parts of addressof rules.
2123 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2124 if (uOp->getOpcode() == UnaryOperator::Deref)
2125 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2126 // (assuming the deref expression is valid).
2127 return uOp->getSubExpr()->getType();
2128 }
2129 // Technically, there should be a check for array subscript
2130 // expressions here, but the result of one is always an lvalue anyway.
2131 }
Anders Carlsson369dee42008-02-01 07:15:58 +00002132 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002133 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002134
2135 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002136 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2137 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2139 op->getSourceRange());
2140 return QualType();
2141 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002142 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2143 if (MemExpr->getMemberDecl()->isBitField()) {
2144 Diag(OpLoc, diag::err_typecheck_address_of,
2145 std::string("bit-field"), op->getSourceRange());
2146 return QualType();
2147 }
2148 // Check for Apple extension for accessing vector components.
2149 } else if (isa<ArraySubscriptExpr>(op) &&
2150 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2151 Diag(OpLoc, diag::err_typecheck_address_of,
2152 std::string("vector"), op->getSourceRange());
2153 return QualType();
2154 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 // We have an lvalue with a decl. Make sure the decl is not declared
2156 // with the register storage-class specifier.
2157 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2158 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002159 Diag(OpLoc, diag::err_typecheck_address_of,
2160 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 return QualType();
2162 }
2163 } else
2164 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002166
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 // If the operand has type "type", the result has type "pointer to type".
2168 return Context.getPointerType(op->getType());
2169}
2170
2171QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002172 UsualUnaryConversions(op);
2173 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002174
Chris Lattnerbefee482007-07-31 16:53:04 +00002175 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002176 // Note that per both C89 and C99, this is always legal, even
2177 // if ptype is an incomplete type or void.
2178 // It would be possible to warn about dereferencing a
2179 // void pointer, but it's completely well-defined,
2180 // and such a warning is unlikely to catch any mistakes.
2181 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 }
2183 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2184 qType.getAsString(), op->getSourceRange());
2185 return QualType();
2186}
2187
2188static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2189 tok::TokenKind Kind) {
2190 BinaryOperator::Opcode Opc;
2191 switch (Kind) {
2192 default: assert(0 && "Unknown binop!");
2193 case tok::star: Opc = BinaryOperator::Mul; break;
2194 case tok::slash: Opc = BinaryOperator::Div; break;
2195 case tok::percent: Opc = BinaryOperator::Rem; break;
2196 case tok::plus: Opc = BinaryOperator::Add; break;
2197 case tok::minus: Opc = BinaryOperator::Sub; break;
2198 case tok::lessless: Opc = BinaryOperator::Shl; break;
2199 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2200 case tok::lessequal: Opc = BinaryOperator::LE; break;
2201 case tok::less: Opc = BinaryOperator::LT; break;
2202 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2203 case tok::greater: Opc = BinaryOperator::GT; break;
2204 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2205 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2206 case tok::amp: Opc = BinaryOperator::And; break;
2207 case tok::caret: Opc = BinaryOperator::Xor; break;
2208 case tok::pipe: Opc = BinaryOperator::Or; break;
2209 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2210 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2211 case tok::equal: Opc = BinaryOperator::Assign; break;
2212 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2213 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2214 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2215 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2216 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2217 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2218 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2219 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2220 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2221 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2222 case tok::comma: Opc = BinaryOperator::Comma; break;
2223 }
2224 return Opc;
2225}
2226
2227static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2228 tok::TokenKind Kind) {
2229 UnaryOperator::Opcode Opc;
2230 switch (Kind) {
2231 default: assert(0 && "Unknown unary op!");
2232 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2233 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2234 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2235 case tok::star: Opc = UnaryOperator::Deref; break;
2236 case tok::plus: Opc = UnaryOperator::Plus; break;
2237 case tok::minus: Opc = UnaryOperator::Minus; break;
2238 case tok::tilde: Opc = UnaryOperator::Not; break;
2239 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2240 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2241 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2242 case tok::kw___real: Opc = UnaryOperator::Real; break;
2243 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2244 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2245 }
2246 return Opc;
2247}
2248
2249// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002250Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 ExprTy *LHS, ExprTy *RHS) {
2252 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2253 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2254
Steve Narofff69936d2007-09-16 03:34:24 +00002255 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2256 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002257
2258 QualType ResultTy; // Result type of the binary operator.
2259 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2260
2261 switch (Opc) {
2262 default:
2263 assert(0 && "Unknown binary expr!");
2264 case BinaryOperator::Assign:
2265 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2266 break;
2267 case BinaryOperator::Mul:
2268 case BinaryOperator::Div:
2269 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2270 break;
2271 case BinaryOperator::Rem:
2272 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2273 break;
2274 case BinaryOperator::Add:
2275 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2276 break;
2277 case BinaryOperator::Sub:
2278 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2279 break;
2280 case BinaryOperator::Shl:
2281 case BinaryOperator::Shr:
2282 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2283 break;
2284 case BinaryOperator::LE:
2285 case BinaryOperator::LT:
2286 case BinaryOperator::GE:
2287 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002288 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002289 break;
2290 case BinaryOperator::EQ:
2291 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002292 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 break;
2294 case BinaryOperator::And:
2295 case BinaryOperator::Xor:
2296 case BinaryOperator::Or:
2297 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2298 break;
2299 case BinaryOperator::LAnd:
2300 case BinaryOperator::LOr:
2301 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2302 break;
2303 case BinaryOperator::MulAssign:
2304 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002305 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 if (!CompTy.isNull())
2307 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2308 break;
2309 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002310 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 if (!CompTy.isNull())
2312 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2313 break;
2314 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002315 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 if (!CompTy.isNull())
2317 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2318 break;
2319 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002320 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 if (!CompTy.isNull())
2322 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2323 break;
2324 case BinaryOperator::ShlAssign:
2325 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002326 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 if (!CompTy.isNull())
2328 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2329 break;
2330 case BinaryOperator::AndAssign:
2331 case BinaryOperator::XorAssign:
2332 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002333 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002334 if (!CompTy.isNull())
2335 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2336 break;
2337 case BinaryOperator::Comma:
2338 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2339 break;
2340 }
2341 if (ResultTy.isNull())
2342 return true;
2343 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002344 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002346 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002347}
2348
2349// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002350Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 ExprTy *input) {
2352 Expr *Input = (Expr*)input;
2353 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2354 QualType resultType;
2355 switch (Opc) {
2356 default:
2357 assert(0 && "Unimplemented unary expr!");
2358 case UnaryOperator::PreInc:
2359 case UnaryOperator::PreDec:
2360 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2361 break;
2362 case UnaryOperator::AddrOf:
2363 resultType = CheckAddressOfOperand(Input, OpLoc);
2364 break;
2365 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002366 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 resultType = CheckIndirectionOperand(Input, OpLoc);
2368 break;
2369 case UnaryOperator::Plus:
2370 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002371 UsualUnaryConversions(Input);
2372 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2374 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2375 resultType.getAsString());
2376 break;
2377 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002378 UsualUnaryConversions(Input);
2379 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002380 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2381 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2382 // C99 does not support '~' for complex conjugation.
2383 Diag(OpLoc, diag::ext_integer_complement_complex,
2384 resultType.getAsString(), Input->getSourceRange());
2385 else if (!resultType->isIntegerType())
2386 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2387 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002388 break;
2389 case UnaryOperator::LNot: // logical negation
2390 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002391 DefaultFunctionArrayConversion(Input);
2392 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002393 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2394 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2395 resultType.getAsString());
2396 // LNot always has type int. C99 6.5.3.3p5.
2397 resultType = Context.IntTy;
2398 break;
2399 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002400 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2401 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 break;
2403 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002404 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2405 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002407 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002408 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002409 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002410 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002412 resultType = Input->getType();
2413 break;
2414 }
2415 if (resultType.isNull())
2416 return true;
2417 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2418}
2419
Steve Naroff1b273c42007-09-16 14:56:35 +00002420/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2421Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 SourceLocation LabLoc,
2423 IdentifierInfo *LabelII) {
2424 // Look up the record for this label identifier.
2425 LabelStmt *&LabelDecl = LabelMap[LabelII];
2426
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002427 // If we haven't seen this label yet, create a forward reference. It
2428 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002429 if (LabelDecl == 0)
2430 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2431
2432 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002433 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2434 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002435}
2436
Steve Naroff1b273c42007-09-16 14:56:35 +00002437Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002438 SourceLocation RPLoc) { // "({..})"
2439 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2440 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2441 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2442
2443 // FIXME: there are a variety of strange constraints to enforce here, for
2444 // example, it is not possible to goto into a stmt expression apparently.
2445 // More semantic analysis is needed.
2446
2447 // FIXME: the last statement in the compount stmt has its value used. We
2448 // should not warn about it being unused.
2449
2450 // If there are sub stmts in the compound stmt, take the type of the last one
2451 // as the type of the stmtexpr.
2452 QualType Ty = Context.VoidTy;
2453
Chris Lattner611b2ec2008-07-26 19:51:01 +00002454 if (!Compound->body_empty()) {
2455 Stmt *LastStmt = Compound->body_back();
2456 // If LastStmt is a label, skip down through into the body.
2457 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2458 LastStmt = Label->getSubStmt();
2459
2460 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002461 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002462 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002463
2464 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2465}
Steve Naroffd34e9152007-08-01 22:05:33 +00002466
Steve Naroff1b273c42007-09-16 14:56:35 +00002467Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002468 SourceLocation TypeLoc,
2469 TypeTy *argty,
2470 OffsetOfComponent *CompPtr,
2471 unsigned NumComponents,
2472 SourceLocation RPLoc) {
2473 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2474 assert(!ArgTy.isNull() && "Missing type argument!");
2475
2476 // We must have at least one component that refers to the type, and the first
2477 // one is known to be a field designator. Verify that the ArgTy represents
2478 // a struct/union/class.
2479 if (!ArgTy->isRecordType())
2480 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2481
2482 // Otherwise, create a compound literal expression as the base, and
2483 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002484 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002485
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002486 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2487 // GCC extension, diagnose them.
2488 if (NumComponents != 1)
2489 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2490 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2491
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002492 for (unsigned i = 0; i != NumComponents; ++i) {
2493 const OffsetOfComponent &OC = CompPtr[i];
2494 if (OC.isBrackets) {
2495 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002496 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002497 if (!AT) {
2498 delete Res;
2499 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2500 Res->getType().getAsString());
2501 }
2502
Chris Lattner704fe352007-08-30 17:59:59 +00002503 // FIXME: C++: Verify that operator[] isn't overloaded.
2504
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002505 // C99 6.5.2.1p1
2506 Expr *Idx = static_cast<Expr*>(OC.U.E);
2507 if (!Idx->getType()->isIntegerType())
2508 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2509 Idx->getSourceRange());
2510
2511 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2512 continue;
2513 }
2514
2515 const RecordType *RC = Res->getType()->getAsRecordType();
2516 if (!RC) {
2517 delete Res;
2518 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2519 Res->getType().getAsString());
2520 }
2521
2522 // Get the decl corresponding to this.
2523 RecordDecl *RD = RC->getDecl();
2524 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2525 if (!MemberDecl)
2526 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2527 OC.U.IdentInfo->getName(),
2528 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002529
2530 // FIXME: C++: Verify that MemberDecl isn't a static field.
2531 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002532 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2533 // matter here.
2534 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002535 }
2536
2537 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2538 BuiltinLoc);
2539}
2540
2541
Steve Naroff1b273c42007-09-16 14:56:35 +00002542Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002543 TypeTy *arg1, TypeTy *arg2,
2544 SourceLocation RPLoc) {
2545 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2546 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2547
2548 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2549
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002550 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002551}
2552
Steve Naroff1b273c42007-09-16 14:56:35 +00002553Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002554 ExprTy *expr1, ExprTy *expr2,
2555 SourceLocation RPLoc) {
2556 Expr *CondExpr = static_cast<Expr*>(cond);
2557 Expr *LHSExpr = static_cast<Expr*>(expr1);
2558 Expr *RHSExpr = static_cast<Expr*>(expr2);
2559
2560 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2561
2562 // The conditional expression is required to be a constant expression.
2563 llvm::APSInt condEval(32);
2564 SourceLocation ExpLoc;
2565 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2566 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2567 CondExpr->getSourceRange());
2568
2569 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2570 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2571 RHSExpr->getType();
2572 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2573}
2574
Nate Begeman67295d02008-01-30 20:50:20 +00002575/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00002576/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00002577/// The number of arguments has already been validated to match the number of
2578/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002579static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2580 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00002581 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00002582 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002583 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2584 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00002585
2586 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00002587 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00002588 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002589 return true;
2590}
2591
2592Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2593 SourceLocation *CommaLocs,
2594 SourceLocation BuiltinLoc,
2595 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002596 // __builtin_overload requires at least 2 arguments
2597 if (NumArgs < 2)
2598 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2599 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00002600
Nate Begemane2ce1d92008-01-17 17:46:27 +00002601 // The first argument is required to be a constant expression. It tells us
2602 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002603 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00002604 Expr *NParamsExpr = Args[0];
2605 llvm::APSInt constEval(32);
2606 SourceLocation ExpLoc;
2607 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2608 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2609 NParamsExpr->getSourceRange());
2610
2611 // Verify that the number of parameters is > 0
2612 unsigned NumParams = constEval.getZExtValue();
2613 if (NumParams == 0)
2614 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2615 NParamsExpr->getSourceRange());
2616 // Verify that we have at least 1 + NumParams arguments to the builtin.
2617 if ((NumParams + 1) > NumArgs)
2618 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2619 SourceRange(BuiltinLoc, RParenLoc));
2620
2621 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00002622 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002623 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002624 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2625 // UsualUnaryConversions will convert the function DeclRefExpr into a
2626 // pointer to function.
2627 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00002628 const FunctionTypeProto *FnType = 0;
2629 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2630 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00002631
2632 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2633 // parameters, and the number of parameters must match the value passed to
2634 // the builtin.
2635 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00002636 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2637 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00002638
2639 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00002640 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00002641 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002642 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002643 if (OE)
2644 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2645 OE->getFn()->getSourceRange());
2646 // Remember our match, and continue processing the remaining arguments
2647 // to catch any errors.
2648 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2649 BuiltinLoc, RParenLoc);
2650 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002651 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00002652 // Return the newly created OverloadExpr node, if we succeded in matching
2653 // exactly one of the candidate functions.
2654 if (OE)
2655 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002656
2657 // If we didn't find a matching function Expr in the __builtin_overload list
2658 // the return an error.
2659 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00002660 for (unsigned i = 0; i != NumParams; ++i) {
2661 if (i != 0) typeNames += ", ";
2662 typeNames += Args[i+1]->getType().getAsString();
2663 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002664
2665 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2666 SourceRange(BuiltinLoc, RParenLoc));
2667}
2668
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002669Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2670 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002671 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002672 Expr *E = static_cast<Expr*>(expr);
2673 QualType T = QualType::getFromOpaquePtr(type);
2674
2675 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00002676
2677 // Get the va_list type
2678 QualType VaListType = Context.getBuiltinVaListType();
2679 // Deal with implicit array decay; for example, on x86-64,
2680 // va_list is an array, but it's supposed to decay to
2681 // a pointer for va_arg.
2682 if (VaListType->isArrayType())
2683 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00002684 // Make sure the input expression also decays appropriately.
2685 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00002686
2687 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002688 return Diag(E->getLocStart(),
2689 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2690 E->getType().getAsString(),
2691 E->getSourceRange());
2692
2693 // FIXME: Warn if a non-POD type is passed in.
2694
2695 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2696}
2697
Chris Lattner5cf216b2008-01-04 18:04:52 +00002698bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2699 SourceLocation Loc,
2700 QualType DstType, QualType SrcType,
2701 Expr *SrcExpr, const char *Flavor) {
2702 // Decode the result (notice that AST's are still created for extensions).
2703 bool isInvalid = false;
2704 unsigned DiagKind;
2705 switch (ConvTy) {
2706 default: assert(0 && "Unknown conversion type");
2707 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002708 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00002709 DiagKind = diag::ext_typecheck_convert_pointer_int;
2710 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002711 case IntToPointer:
2712 DiagKind = diag::ext_typecheck_convert_int_pointer;
2713 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002714 case IncompatiblePointer:
2715 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2716 break;
2717 case FunctionVoidPointer:
2718 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2719 break;
2720 case CompatiblePointerDiscardsQualifiers:
2721 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2722 break;
2723 case Incompatible:
2724 DiagKind = diag::err_typecheck_convert_incompatible;
2725 isInvalid = true;
2726 break;
2727 }
2728
2729 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2730 SrcExpr->getSourceRange());
2731 return isInvalid;
2732}